Ejemplo n.º 1
0
        public async Task <DefaultCommandResponse> Handle(ForgotPasswordCommand command)
        {
            this._adminUnitOfWork.Begin();

            try
            {
                var user = await this._userRepository.GetForUpdate(command.Login);

                if (user == null)
                {
                    this._validationResult.Errors.Add(new ValidationFailure("Login", "Invalid User"));
                }

                if (this._validationResult.IsValid)
                {
                    await this._userTokenRepository.DeleteAll(user);

                    var userToken = UserToken.Create(user);
                    await this._userTokenRepository.Save(userToken);

                    await this._emailSender.Send(new ForgottenPasswordEmailMessage(userToken));
                }

                this._adminUnitOfWork.SoftCommit();
            }
            catch (Exception e)
            {
                this._adminUnitOfWork.Rollback();
                Console.WriteLine(e);
                throw;
            }

            return(DefaultCommandResponse.Create(this._validationResult));
        }
        public Token Authenticate(string login, string password)
        {
            // authentication by the Login and Password
            var now = CommonService.Now;

            Token result = null;

            // создаем новый контекст, дабы не использовать "уже загруженные" сущности
            using (var dbContext = new FamilyDbContext())
            {
                UserToken userToken = null;

                // authentication for Managers
                if (userToken == null)
                {
                    // находим пользователя по логину
                    var manager = dbContext.Set <Manager>()
                                  .Include(t => t.Person.Avatar)
                                  .Include(t => t.Roles)
                                  //.Where(m => m.Person.State == Common.Enums.ObjectState.Active)
                                  .FirstOrDefault(m => m.Login.ToLower() == login.ToLower());

                    if (manager != null && CommonService.VerifyPassword(password, manager.Password))
                    {
                        userToken = UserToken.Create(manager, null, now.AddHours(DefaultExpirationHours));
                    }
                }

                // authentication for Guests
                if (userToken == null)
                {
                    var guest = dbContext.Set <Guest>()
                                .FirstOrDefault(g => g.Date <= now && now <= g.Expire && g.Login.ToLower() == login.ToLower());

                    if (guest != null && CommonService.VerifyPassword(password, guest.Password))
                    {
                        userToken = UserToken.Create(null, guest, guest.Expire);
                    }
                }

                // saving new token
                if (userToken != null)
                {
                    dbContext.Set <UserToken>().Add(userToken);
                    dbContext.SaveChanges();

                    result = this.BuildToken(userToken);
                }
            }

            return(result);
        }
        private UserToken GenerateToken(Credential credential)
        {
            var jwtTokenHandler = new JwtSecurityTokenHandler();
            var expiresOn       = DateTime.Now.Add(_tokenConfigurations.ExpiresOn);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, credential.Username) }),
                Audience           = _tokenConfigurations.Audience,
                Issuer             = _tokenConfigurations.Issuer,
                Expires            = expiresOn,
                SigningCredentials = _signingConfigurations.SigningCredentials
            };

            var stoken = jwtTokenHandler.CreateToken(tokenDescriptor);
            var token  = jwtTokenHandler.WriteToken(stoken);

            return(UserToken.Create(token, expiresOn));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get a new token for the parametrized user
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <UserToken> GetNewTokenAsync(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            UserToken userToken = _userTokenRepository.GetByUser(user);

            if (userToken == null)
            {
                userToken = UserToken.Create(user, _appSettings.TokenExpirationInHours);
                _userTokenRepository.Add(userToken);
            }
            else
            {
                userToken.CreateToken(_appSettings.TokenExpirationInHours);
                _userTokenRepository.Update(userToken);
            }
            await _userTokenRepository.SaveChangesAsync();

            return(userToken);
        }