示例#1
0
 private Task <User> GetUserAggregateAsync(Expression <Func <User, bool> > filter)
 {
     return(_entities.Get <User>()
            .EagerLoad(u => u.Permissions)
            .EagerLoad(u => u.EmailAddresses)
            .EagerLoad(u => u.LocalMembership)
            .EagerLoad(u => u.Claims)
            .EagerLoad(u => u.RemoteMemberships)
            .FirstOrDefaultAsync(filter));
 }
示例#2
0
        public async Task Handle(UpdateEmailAddress command)
        {
            // load up the entity
            var entity = await _entities.Get <EmailAddress>()
                         .EagerLoad(x => x.User.EmailAddresses)
                         .ByIdAsync(command.EmailAddressId);

            var commit = false;

            // update the isprimary field when requested to
            if (command.IsPrimary.HasValue && entity.IsPrimary != command.IsPrimary.Value)
            {
                if (entity.IsPrimary && !command.IsPrimary.Value)
                {
                    // todo: unit test validation to make sure this exception can never be thrown.
                    throw new InvalidOperationException(string.Format(
                                                            "Cannot set EmailAddress.IsPrimary to false for #{0}. This should have been caught in the validator.", entity.Id));
                }

                // since the primary email address cannot be changed to non-primary,
                // at this point we must be changing a non-primary to primary.
                commit = true;
                var primaryEmail = entity.User.EmailAddresses.Single(x => x.IsPrimary);
                primaryEmail.IsPrimary = false;
                entity.IsPrimary       = true;
            }

            if (commit)
            {
                await _entities.SaveChangesAsync();
            }
        }
示例#3
0
        public async Task Handle(ResetPassword command)
        {
            var verification = await _entities.Get <EmailVerification>()
                               .EagerLoad(x => x.EmailAddress)
                               .ByTicketAsync(command.Ticket, false);

            verification.RedeemedOnUtc = DateTime.UtcNow;
            var user = verification.EmailAddress.User;

            var localMembership = await _queries.Execute(new LocalMembershipByVerifiedEmail(verification.EmailAddress.Value));

            // if the user has a no local membership, create one
            if (localMembership == null)
            {
                localMembership = new LocalMembership {
                    User = user,
                };
                user.LocalMembership = localMembership;
            }

            // update the password
            var passwordHash = await _queries.Execute(new HashedPassword(command.Password));

            user.LocalMembership.PasswordHash = passwordHash;

            user.SecurityStamp = Guid.NewGuid().ToString();
            await _entities.SaveChangesAsync();
        }
示例#4
0
        public async Task Handle(CreateRemoteMembership command)
        {
            // does user already exist?
            var hasUserId = command.Principal.Identity.HasAppUserId();
            var user      = hasUserId ? await _entities.Get <User>()
                            .EagerLoad(new Expression <Func <User, object> >[]
            {
                x => x.RemoteMemberships,
            })
                            .ByIdAsync(command.Principal.Identity.GetUserId <int>()) : command.User;

            if (user == null)
            {
                var createUser = new CreateUser {
                    Name = command.UserName
                };
                await _commands.Execute(createUser);

                user = createUser.CreatedEntity;

                // verify & associate email address
                await _commands.Execute(new RedeemEmailVerification(user)
                {
                    Commit = false,
                    Token  = command.Token,
                    Ticket = command.Ticket,
                });
            }

            var ticket = await _queries.Execute(new PrincipalRemoteMembershipTicket(command.Principal));

            // do not add this login if it already exists
            if (user.RemoteMemberships.ByUserLoginInfo(ticket.Login) != null)
            {
                return;
            }

            var entity = new RemoteMembership
            {
                User   = user,
                UserId = user.Id,
                Id     =
                {
                    LoginProvider = ticket.Login.LoginProvider,
                    ProviderKey   = ticket.Login.ProviderKey
                },
            };

            user.RemoteMemberships.Add(entity);
            user.SecurityStamp = Guid.NewGuid().ToString();

            if (command.Commit)
            {
                await _entities.SaveChangesAsync();
            }
            command.CreatedEntity = entity;
        }
示例#5
0
        public async Task Handle(DeleteCustomerCommand command, CancellationToken cancellationToken)
        {
            var theCustomer = await _db.Get <Customer>()
                              .SingleOrDefaultAsync(c => c.Id == command.Id, cancellationToken)
                              .ConfigureAwait(false);

            if (theCustomer != null)
            {
                _db.Delete(theCustomer);
            }
        }
示例#6
0
        public async Task Handle(ChangeLocalPassword command)
        {
            var userId = command.Principal.Identity.GetUserId <int>();
            var user   = await _entities.Get <User>()
                         .EagerLoad(new Expression <Func <User, object> >[] { x => x.LocalMembership, })
                         .ByIdAsync(userId);

            user.LocalMembership.PasswordHash = _userManager.PasswordHasher.HashPassword(command.NewPassword);
            user.SecurityStamp = Guid.NewGuid().ToString();
            await _entities.SaveChangesAsync();
        }
        public async Task Handle(DeletePersonCommand command, CancellationToken cancellationToken)
        {
            var person = await _db.Get <Person>().SingleOrDefaultAsync(p => p.Name == command.PersonName, cancellationToken).ConfigureAwait(false);

            if (person == null)
            {
                return;
            }

            _db.Delete(person);
        }
        public async Task Handle(DeleteAddressCommand command, CancellationToken cancellationToken)
        {
            var theAddress = await _db.Get <Address>()
                             .SingleOrDefaultAsync(a => a.Id == command.Id, cancellationToken)
                             .ConfigureAwait(false);

            if (theAddress != null)
            {
                _db.Delete(theAddress);
            }
        }
示例#9
0
        public async Task Handle(CreateEmailVerification command)
        {
            // find or create the email address
            var emailAddress = await _entities.Get <EmailAddress>().ByValueAsync(command.EmailAddress)
                               ?? new EmailAddress
            {
                Value       = command.EmailAddress.ToLower(), // TODO: allow users to change capitalization of email?
                HashedValue = await _queries.Execute(new HashedEmailValueBy(command.EmailAddress)),
            };

            // create random secret and ticket
            // note that changing the length of the secret requires updating the
            // email messages sent to the address, since those mention secret length
            var secret = _queries.Execute(new RandomSecret(10, 12));
            var ticket = _queries.Execute(new RandomSecret(20, 25));

            // make sure ticket is unique
            while (_entities.Query <EmailVerification>().ByTicket(ticket) != null)
            {
                ticket = _queries.Execute(new RandomSecret(20, 25));
            }

            // serialize a new user token to a string
            var token = await _userManager.UserTokenProvider.GenerateAsync(command.Purpose.ToString(), _userManager,
                                                                           new UserTicket
            {
                UserName = ticket,
            });

            // create the verification
            var verification = new EmailVerification
            {
                EmailAddress = emailAddress,
                Purpose      = command.Purpose,
                Secret       = secret,
                Ticket       = ticket,
                Token        = token,

                // change this, and you have to change the content of the email messages to reflect new expiration
                ExpiresOnUtc = DateTime.UtcNow.AddMinutes(30),
            };

            _entities.Create(verification);

            if (command.Commit)
            {
                await _entities.SaveChangesAsync();
            }

            command.CreatedEntity = verification;
        }
示例#10
0
        public void OnDelivered(int emailMessageId, Exception error, bool cancelled)
        {
            var entity = _entities.Get <EmailMessage>(emailMessageId);

            entity.LastSendError  = error != null ? error.Message : null;
            entity.CancelledOnUtc = cancelled ? DateTime.UtcNow : (DateTime?)null;

            if (error == null && !cancelled)
            {
                entity.SentOnUtc = DateTime.UtcNow;
            }

            _entities.SaveChanges();
        }
示例#11
0
        public async Task Handle(RedeemEmailVerification command)
        {
            // verify & associate email address
            var verification = await _entities.Get <EmailVerification>()
                               .EagerLoad(x => x.EmailAddress)
                               .ByTicketAsync(command.Ticket, false);

            verification.RedeemedOnUtc = DateTime.UtcNow;

            var email = verification.EmailAddress;
            var user  = command.User
                        ?? await _entities.Get <User>()
                        .EagerLoad(x => x.EmailAddresses)
                        .ByIdAsync(command.Principal.Identity.GetUserId <int>());

            email.User       = user;
            email.IsVerified = true;

            // is this the user's primary email address?
            email.IsPrimary = !user.EmailAddresses.Any(x => x.IsPrimary);

            // expire unused verifications
            var unusedVerifications = await _entities.Get <EmailVerification>()
                                      .ByEmailAddressId(email.Id)
                                      .ToArrayAsync()
            ;

            foreach (var unusedVerification in unusedVerifications.Except(new[] { verification }))
            {
                unusedVerification.RedeemedOnUtc = unusedVerification.ExpiresOnUtc;
            }

            if (command.Commit)
            {
                await _entities.SaveChangesAsync();
            }
        }
示例#12
0
        public async Task Handle(DeleteRemoteMembership command)
        {
            var userId           = command.Principal.Identity.GetUserId <int>();
            var userLoginInfo    = new UserLoginInfo(command.LoginProvider, command.ProviderKey);
            var remoteMembership = await _entities.Get <RemoteMembership>()
                                   .EagerLoad(new Expression <Func <RemoteMembership, object> >[] { x => x.User, })
                                   .ByUserIdAndLoginInfoAsync(userId, userLoginInfo);

            if (remoteMembership == null)
            {
                return;
            }

            _entities.Delete(remoteMembership);
            await _entities.SaveChangesAsync();
        }
        public async Task Handle(RejectEmailVerification command)
        {
            // reject this email verification
            var verification = await _entities.Get <EmailVerification>()
                               .EagerLoad(x => x.EmailAddress)
                               .ByTicketAsync(command.Ticket, false);

            verification.Token = "Rejected";

            var email = verification.EmailAddress;

            email.UserId        = null;
            verification.Secret = null;
            var ticket = _queries.Execute(new RandomSecret(20, 25));

            // make sure ticket is unique
            while (_entities.Query <EmailVerification>().ByTicket(ticket) != null)
            {
                ticket = _queries.Execute(new RandomSecret(20, 25));
            }
            verification.Ticket = ticket;

            await _entities.SaveChangesAsync();
        }