Ejemplo n.º 1
0
        public async Task AssertReferenceAllowedAsync(UserId requester, Shared.FileId fileId)
        {
            requester.AssertNotNull("requester");
            fileId.AssertNotNull("fileId");

            var isUsageAllowed = await this.IsReferenceAllowedAsync(requester, fileId);

            if (!isUsageAllowed)
            {
                throw new UnauthorizedException("The user " + requester.Value + " does not have permission to reference file " + fileId.Value);
            }
        }
Ejemplo n.º 2
0
        public async Task AssertReadAllowedAsync(UserId requester, PostId postId, DateTime timestamp)
        {
            requester.AssertNotNull("requester");
            postId.AssertNotNull("postId");

            var isAllowed = await this.IsReadAllowedAsync(requester, postId, timestamp);

            if (isAllowed == PostSecurityResult.Denied)
            {
                throw new UnauthorizedException("Not allowed to read post. {0} {1}", requester, postId);
            }
        }
Ejemplo n.º 3
0
        public async Task AssertCommentAllowedAsync(UserId requester, PostId postId, DateTime timestamp)
        {
            requester.AssertNotNull("requester");
            postId.AssertNotNull("postId");

            var isCommentOrLikeAllowed = await this.IsCommentAllowedAsync(requester, postId, timestamp);

            if (!isCommentOrLikeAllowed)
            {
                throw new UnauthorizedException("Not allowed to comment on post. {0} {1}", requester, postId);
            }
        }
Ejemplo n.º 4
0
        public async Task AssertWriteAllowedAsync(UserId requester, Shared.QueueId queueId)
        {
            requester.AssertNotNull("requester");
            queueId.AssertNotNull("queueId");

            var isWriteAllowed = await this.IsWriteAllowedAsync(requester, queueId);

            if (!isWriteAllowed)
            {
                throw new UnauthorizedException("Not allowed to write to collection. {0} {1}", requester, queueId);
            }
        }
Ejemplo n.º 5
0
        public async Task AssertWriteAllowedAsync(UserId requester, PostId postId)
        {
            requester.AssertNotNull("requester");
            postId.AssertNotNull("postId");

            var isPostingAllowed = await this.IsWriteAllowedAsync(requester, postId);

            if (!isPostingAllowed)
            {
                throw new UnauthorizedException("Not allowed to write post. {0} {1}", requester, postId);
            }
        }
Ejemplo n.º 6
0
        public async Task AssertWriteAllowedAsync(UserId requester, BlogId blogId)
        {
            requester.AssertNotNull("requester");
            blogId.AssertNotNull("blogId");

            var isUpdateAllowed = await this.IsWriteAllowedAsync(requester, blogId);

            if (!isUpdateAllowed)
            {
                throw new UnauthorizedException("Not allowed to update blog. {0} {1}", requester, blogId);
            }
        }
Ejemplo n.º 7
0
        public async Task HandleAsync(
            UserId userId,
            PositiveInt amount)
        {
            userId.AssertNotNull("userId");
            amount.AssertNotNull("amount");

            var timestamp = this.timestampCreator.Now();

            // Just update account balance directly.
            await this.setTestUserAccountBalance.ExecuteAsync(userId, timestamp, amount);
        }
Ejemplo n.º 8
0
        public async Task ExecuteAsync(UserId userId, PostId postId, DateTime timestamp)
        {
            userId.AssertNotNull("userId");
            postId.AssertNotNull("postId");

            var like = new Like(postId.Value, null, userId.Value, null, timestamp);

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.UpsertAsync(
                    like,
                    Like.Fields.CreationDate);
            }
        }
        public async Task <int> ExecuteAsync(UserId userId)
        {
            userId.AssertNotNull("userId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                return(await connection.ExecuteScalarAsync <int>(
                           Sql,
                           new
                {
                    UserId = userId.Value,
                }));
            }
        }
Ejemplo n.º 10
0
        public async Task <UserId> AuthenticateAsAsync(Requester requester, UserId userId)
        {
            requester.AssertNotNull("requester");
            userId.AssertNotNull("userId");

            var authenticatedUserId = await this.AuthenticateAsync(requester);

            if (!userId.Equals(authenticatedUserId))
            {
                throw new UnauthorizedException("User '{0}' is could not be authenticated as '{1}'.", requester.UserId, userId);
            }

            return(authenticatedUserId);
        }
Ejemplo n.º 11
0
        public async Task ExecuteAsync(
            UserId subscriberId,
            UserId creatorId,
            IReadOnlyList <AppendOnlyLedgerRecord> ledgerRecords,
            UncommittedSubscriptionPayment uncommittedRecord)
        {
            subscriberId.AssertNotNull("subscriberId");
            creatorId.AssertNotNull("creatorId");
            ledgerRecords.AssertNotNull("ledgerRecords");

            using (PaymentsPerformanceLogger.Instance.Log(typeof(PersistCommittedAndUncommittedRecordsDbStatement)))
                using (var transaction = TransactionScopeBuilder.CreateAsync())
                {
                    using (var connection = this.connectionFactory.CreateConnection())
                    {
                        if (ledgerRecords.Any())
                        {
                            await connection.InsertAsync(ledgerRecords, false);
                        }

                        if (uncommittedRecord != null)
                        {
                            var uncommittedFields = UncommittedSubscriptionPayment.Fields.StartTimestampInclusive
                                                    | UncommittedSubscriptionPayment.Fields.EndTimestampExclusive
                                                    | UncommittedSubscriptionPayment.Fields.Amount
                                                    | UncommittedSubscriptionPayment.Fields.InputDataReference;

                            await connection.UpsertAsync(uncommittedRecord, uncommittedFields);
                        }
                        else
                        {
                            // Remove the existing uncommitted record.
                            await connection.ExecuteAsync(
                                string.Format(
                                    @"DELETE FROM {0} WHERE {1}=@SubscriberId AND {2}=@CreatorId",
                                    UncommittedSubscriptionPayment.Table,
                                    UncommittedSubscriptionPayment.Fields.SubscriberId,
                                    UncommittedSubscriptionPayment.Fields.CreatorId),
                                new
                            {
                                SubscriberId = subscriberId.Value,
                                CreatorId    = creatorId.Value
                            });
                        }
                    }

                    transaction.Complete();
                }
        }
Ejemplo n.º 12
0
        public async Task ExecuteAsync(UserId userId, BlogId blogId, IReadOnlyList <AcceptedChannelSubscription> channels, DateTime now)
        {
            userId.AssertNotNull("userId");
            blogId.AssertNotNull("blogId");

            if (channels == null || channels.Count == 0)
            {
                channels = new List <AcceptedChannelSubscription>();
            }

            using (var transaction = TransactionScopeBuilder.CreateAsync())
            {
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    await connection.ExecuteAsync(
                        DeleteStatement,
                        new
                    {
                        BlogId         = blogId.Value,
                        SubscriberId   = userId.Value,
                        KeepChannelIds = channels.Select(v => v.ChannelId.Value).ToList()
                    });

                    foreach (var item in channels)
                    {
                        var channelSubscription = new ChannelSubscription(
                            item.ChannelId.Value,
                            null,
                            userId.Value,
                            null,
                            item.AcceptedPrice.Value,
                            now,
                            now);

                        const ChannelSubscription.Fields UpdateFields
                            = ChannelSubscription.Fields.AcceptedPrice
                              | ChannelSubscription.Fields.PriceLastAcceptedDate;

                        await connection.UpsertAsync(
                            channelSubscription,
                            UpdateFields);
                    }
                }

                await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.SubscriberChannels);

                transaction.Complete();
            }
        }
Ejemplo n.º 13
0
        public async Task ExecuteAsync(UserId userId)
        {
            userId.AssertNotNull("userId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.UpsertAsync(
                    new UserPaymentOrigin
                {
                    UserId        = userId.Value,
                    PaymentStatus = PaymentStatus.Failed,
                },
                    UserPaymentOrigin.Fields.PaymentStatus);
            }
        }
Ejemplo n.º 14
0
        public async Task <bool> IsOwnerAsync(UserId userId, Shared.QueueId queueId)
        {
            userId.AssertNotNull("userId");
            queueId.AssertNotNull("queueId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                return(await connection.ExecuteScalarAsync <bool>(
                           Sql,
                           new
                {
                    QueueId = queueId.Value,
                    CreatorId = userId.Value
                }));
            }
        }
Ejemplo n.º 15
0
        public async Task <bool> ExecuteAsync(UserId userId, Shared.PostId postId)
        {
            userId.AssertNotNull("userId");
            postId.AssertNotNull("postId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                return(await connection.ExecuteScalarAsync <bool>(
                           Sql,
                           new
                {
                    PostId = postId.Value,
                    UserId = userId.Value
                }));
            }
        }
Ejemplo n.º 16
0
        public async Task ExecuteAsync(UserId userId, PostId postId)
        {
            userId.AssertNotNull("userId");
            postId.AssertNotNull("postId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.ExecuteAsync(
                    Sql,
                    new
                {
                    UserId = userId.Value,
                    PostId = postId.Value,
                });
            }
        }
Ejemplo n.º 17
0
        public async Task ExecuteAsync(
            Shared.FileId fileId,
            UserId userId,
            ChannelId channelId,
            string fileNameWithoutExtension,
            string fileExtension,
            string purpose,
            DateTime timeStamp)
        {
            fileId.AssertNotNull("fileId");
            userId.AssertNotNull("userId");
            fileNameWithoutExtension.AssertNotNull("fileNameWithoutExtension");
            fileExtension.AssertNotNull("fileExtension");
            purpose.AssertNotNull("purpose");

            if (fileNameWithoutExtension.Length > File.MaximumFileNameLength)
            {
                fileNameWithoutExtension = fileNameWithoutExtension.Substring(0, File.MaximumFileNameLength);
            }

            if (fileExtension.Length > File.MaximumFileExtensionLength)
            {
                fileExtension = fileExtension.Substring(0, File.MaximumFileExtensionLength);
            }

            var file = new File(
                fileId.Value,
                userId.Value,
                channelId == null ? (Guid?)null : channelId.Value,
                FileState.WaitingForUpload,
                timeStamp,
                null,
                null,
                null,
                null,
                fileNameWithoutExtension,
                fileExtension,
                0L,
                purpose,
                null,
                null);

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.InsertAsync(file);
            }
        }
Ejemplo n.º 18
0
        public async Task <UserRoles> ExecuteAsync(UserId userId)
        {
            userId.AssertNotNull("userId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                var result = await connection.QueryAsync <FifthweekRole>(
                    Sql,
                    new
                {
                    UserId = userId.Value
                });

                return(new UserRoles(
                           result.Select(v => new UserRoles.UserRole(v.Id, v.Name)).ToList()));
            }
        }
Ejemplo n.º 19
0
        public async Task ExecuteAsync(UserId userId, DateTime timestamp, PositiveInt amount)
        {
            userId.AssertNotNull("userId");
            amount.AssertNotNull("amount");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.ExecuteAsync(
                    Sql,
                    new
                {
                    UserId    = userId.Value,
                    Timestamp = timestamp,
                    Amount    = amount.Value,
                });
            }
        }
        public async Task ExecuteAsync(UserId subscriberId, DateTime endTimeExclusive, IKeepAliveHandler keepAliveHandler, List <PaymentProcessingException> errors)
        {
            keepAliveHandler.AssertNotNull("keepAliveHandler");
            subscriberId.AssertNotNull("subscriberId");
            errors.AssertNotNull("errors");

            var creators = await this.getCreatorsAndFirstSubscribedDates.ExecuteAsync(subscriberId);

            var committedAccountBalanceValue = await this.getCommittedAccountBalanceDbStatement.ExecuteAsync(subscriberId);

            if (committedAccountBalanceValue < 0)
            {
                errors.Add(new PaymentProcessingException(string.Format("Committed account balance was {0} for user {1}.", committedAccountBalanceValue, subscriberId), subscriberId, null));
                committedAccountBalanceValue = 0m;
            }

            var committedAccountBalance = new CommittedAccountBalance(committedAccountBalanceValue);

            foreach (var creator in creators)
            {
                try
                {
                    await keepAliveHandler.KeepAliveAsync();

                    var latestCommittedLedgerDate = await this.getLatestCommittedLedgerDate.ExecuteAsync(subscriberId, creator.CreatorId);

                    var startTimeInclusive = latestCommittedLedgerDate ?? PaymentProcessingUtilities.GetPaymentProcessingStartDate(creator.FirstSubscribedDate);

                    if ((endTimeExclusive - startTimeInclusive) <= MinimumProcessingPeriod)
                    {
                        continue;
                    }

                    committedAccountBalance = await this.processPaymentsBetweenSubscriberAndCreator.ExecuteAsync(
                        subscriberId,
                        creator.CreatorId,
                        startTimeInclusive,
                        endTimeExclusive,
                        committedAccountBalance);
                }
                catch (Exception t)
                {
                    errors.Add(new PaymentProcessingException(t, subscriberId, creator.CreatorId));
                }
            }
        }
Ejemplo n.º 21
0
        public async Task ExecuteAsync(UserId userId, ChannelId channelId)
        {
            userId.AssertNotNull("userId");
            channelId.AssertNotNull("channelId");

            using (var transaction = TransactionScopeBuilder.CreateAsync())
            {
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    await connection.ExecuteAsync(DeleteStatement, new { ChannelId = channelId.Value, UserId = userId.Value });
                }

                await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.SubscriberChannels);

                transaction.Complete();
            }
        }
        public async Task <bool> ExecuteAsync(UserId userId, PostId postId, DateTime now)
        {
            userId.AssertNotNull("userId");
            postId.AssertNotNull("postId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                return(await connection.ExecuteScalarAsync <bool>(
                           Sql,
                           new
                {
                    PostId = postId.Value,
                    RequestorId = userId.Value,
                    Now = now
                }));
            }
        }
Ejemplo n.º 23
0
        public async Task <decimal> ExecuteAsync(UserId userId)
        {
            userId.AssertNotNull("userId");

            using (PaymentsPerformanceLogger.Instance.Log(typeof(GetCommittedAccountBalanceDbStatement)))
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    var result = await connection.ExecuteScalarAsync <decimal>(
                        Sql,
                        new
                    {
                        UserId = userId.Value
                    });

                    return(result);
                }
        }
        public async Task <GetBlogChannelsAndQueuesDbResult> ExecuteAsync(UserId userId)
        {
            userId.AssertNotNull("userId");

            List <Blog>              blogs;
            List <Channel>           channels;
            List <PartialQueue>      queues;
            List <WeeklyReleaseTime> releaseTimes;

            using (var connection = this.connectionFactory.CreateConnection())
            {
                using (var multi = await connection.QueryMultipleAsync(Query, new { UserId = userId.Value }))
                {
                    blogs        = multi.Read <Blog>().ToList();
                    channels     = multi.Read <Channel>().ToList();
                    queues       = multi.Read <PartialQueue>().ToList();
                    releaseTimes = multi.Read <WeeklyReleaseTime>().ToList();
                }
            }

            var blog = blogs.SingleOrDefault();

            if (blog == null)
            {
                return(null);
            }

            var queueResult = queues.Select(
                q => new QueueResult(
                    new QueueId(q.Id),
                    q.Name,
                    releaseTimes.Where(wrt => wrt.QueueId == q.Id).Select(wrt => new HourOfWeek(wrt.HourOfWeek)).ToArray())).ToList();

            var blogResult = GetBlogDbResult(blog, queueResult);

            var channelsAndCollectionsResult = channels.Select(
                c => new ChannelResult(
                    new ChannelId(c.Id),
                    c.Name,
                    c.Price,
                    c.IsVisibleToNonSubscribers)).ToList();

            return(new GetBlogChannelsAndQueuesDbResult(blogResult, channelsAndCollectionsResult));
        }
        public async Task ExecuteAsync(UserId userId, PostId postId, CommentId commentId, Shared.Comment content, DateTime timestamp)
        {
            userId.AssertNotNull("userId");
            postId.AssertNotNull("postId");
            commentId.AssertNotNull("commentId");
            content.AssertNotNull("content");

            var comment = new Persistence.Comment(commentId.Value, postId.Value, null, userId.Value, null, content.Value, timestamp);

            using (var connection = this.connectionFactory.CreateConnection())
            {
                await connection.UpsertAsync(
                    comment,
                    Persistence.Comment.Fields.PostId
                    | Persistence.Comment.Fields.UserId
                    | Persistence.Comment.Fields.Content
                    | Persistence.Comment.Fields.CreationDate);
            }
        }
        public async Task <CommittedAccountBalance> ExecuteAsync(UserId subscriberId, UserId creatorId, DateTime startTimeInclusive, DateTime endTimeExclusive, CommittedAccountBalance committedAccountBalance)
        {
            subscriberId.AssertNotNull("subscriberId");
            creatorId.AssertNotNull("creatorId");
            committedAccountBalance.AssertNotNull("committedAccountBalance");

            var paymentProcessingData = await this.getPaymentProcessingData.ExecuteAsync(
                subscriberId,
                creatorId,
                startTimeInclusive,
                endTimeExclusive,
                committedAccountBalance);

            var results = await this.processPaymentProcessingData.ExecuteAsync(paymentProcessingData);

            await this.persistPaymentProcessingResults.ExecuteAsync(paymentProcessingData, results);

            return(results.CommittedAccountBalance);
        }
Ejemplo n.º 27
0
        public async Task <string> ExecuteAsync(UserId userId, string tokenId, UserType userType)
        {
            userId.AssertNotNull("userId");
            tokenId.AssertNotNull("tokenId");

            var apiKey = this.apiKeyRepository.GetApiKey(userType);

            var options = new StripeCustomerCreateOptions
            {
                Description = userId.ToString(),
                Source      = new StripeSourceOptions
                {
                    TokenId = tokenId,
                }
            };

            var customer = await this.stripeService.CreateCustomerAsync(options, apiKey);

            return(customer.Id);
        }
        public async Task <bool> ExecuteAsync(UserId requestorId, PostId postId, DateTime timestamp, int maximumPosts)
        {
            requestorId.AssertNotNull("requestorId");
            postId.AssertNotNull("postId");

            using (var connection = this.connectionFactory.CreateConnection())
            {
                var result = await connection.ExecuteScalarAsync <bool>(
                    Sql,
                    new
                {
                    PostId       = postId.Value,
                    UserId       = requestorId.Value,
                    Timestamp    = timestamp,
                    MaximumPosts = maximumPosts
                });

                return(result);
            }
        }
        public async Task <GetNewsfeedDbResult> ExecuteAsync(
            UserId requestorId,
            UserId creatorId,
            IReadOnlyList <ChannelId> requestedChannelIds,
            DateTime now,
            DateTime origin,
            bool searchForwards,
            NonNegativeInt startIndex,
            PositiveInt count)
        {
            requestorId.AssertNotNull("requestorId");
            startIndex.AssertNotNull("startIndex");
            count.AssertNotNull("count");

            var parameters = new
            {
                RequestorId         = requestorId.Value,
                CreatorId           = creatorId == null ? null : (Guid?)creatorId.Value,
                RequestedChannelIds = requestedChannelIds == null ? null : requestedChannelIds.Select(v => v.Value).ToList(),
                Now        = now,
                Origin     = origin,
                StartIndex = startIndex.Value,
                Count      = count.Value
            };

            using (var connection = this.connectionFactory.CreateConnection())
            {
                var query = new StringBuilder();

                query.Append(GetSqlStart(requestorId, SqlQuerySource.Newsfeed));

                query.Append(CreateFilter(requestorId, creatorId, requestedChannelIds, now, origin, searchForwards, startIndex, count, false));

                query.Append(SqlEnd);

                var entities = (await connection.QueryAsync <NewsfeedPost.Builder>(query.ToString(), parameters)).ToList();
                ProcessNewsfeedResults(entities);

                return(new GetNewsfeedDbResult(entities.Select(_ => _.Build()).ToList()));
            }
        }
        public async Task <IReadOnlyList <BacklogPost> > ExecuteAsync(UserId creatorId, DateTime now)
        {
            creatorId.AssertNotNull("creatorId");

            var parameters = new
            {
                CreatorId = creatorId.Value,
                Now       = now
            };

            using (var connection = this.connectionFactory.CreateConnection())
            {
                var entities = (await connection.QueryAsync <BacklogPost.Builder>(Sql, parameters)).ToList();
                foreach (var entity in entities)
                {
                    entity.LiveDate = DateTime.SpecifyKind(entity.LiveDate, DateTimeKind.Utc);
                }

                return(entities.Select(_ => _.Build()).ToList());
            }
        }