Example #1
0
        public bool VerifyUser([FromQuery] string userName, [FromQuery] string password)
        {
            var user = GetUserByUserName(userName);

            return(user != null && BC.Verify(password, user.UserPassword));
        }
Example #2
0
 public bool Verify(string hash, string password)
 {
     return(Crypto.Verify(password, hash));
 }
Example #3
0
        public async Task <bool> Authenticate(User model)
        {
            var account = await GetOne(x => x.Username.Equals(model.Username));

            return(!(account == null || !BC.Verify(model.Password, account.Password)));
        }
 public bool ValidatePassword(string passWord, string hashPassword)
 {
     return(BC.Verify(passWord, hashPassword));
 }
Example #5
0
 public static bool Verify(string password, string hash)
 {
     return(BCrypt.Verify(password, hash));
 }
 public bool VerifyPassword(string password, string passwordHash)
 {
     return(BC.Verify(password, passwordHash));
 }
 public bool VerifyUser(string email, string password, string hash)
 => Hash.Verify(HashPair(email, password), hash);
Example #8
0
        public async Task <IActionResult> ResetPasswordAsync([FromBody] PasswordResetRequest request)
        {
            var resetToken = await _userService.GetPasswordResetTokenByIdAsync(request.TokenId);

            if (resetToken == null || resetToken.ExpirationDate <= DateTime.Now || resetToken.TokenUsed || !BC.Verify(request.Token, resetToken.TokenHash))
            {
                return(BadRequest());
            }
            else
            {
                var user = await _userService.GetUserByIdAsync(resetToken.UserId);

                user.Password        = BC.HashPassword(request.NewPassword);
                resetToken.TokenUsed = true;

                var claims = _userService.GetUserClaims(user);

                var accessToken  = _tokenService.GenerateAccessToken(claims);
                var refreshToken = _tokenService.GenerateRefreshToken();

                user.RefreshToken           = refreshToken;
                user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7);
                await _userService.UpdateUserAsync(user);

                await _userService.UpdatePasswordResetTokenAsync(resetToken);

                return(Ok(new TokenApiModel(accessToken, refreshToken)));
            }
        }
Example #9
0
 public static bool ValidatePassword(string password, string correctHash)
 {
     password += "!aS@#d";
     return(BC.Verify(password, correctHash));
 }
        public async Task <TokenResponse> GenerateTokenAsync(TokenRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
            {
                throw ExceptionHelper.CreatePublicException(PublicExceptionMessage);
            }

            var user = await _repositoryUser.FindFirstAsync(new UsersByEmail(request.Email)) ??
                       throw ExceptionHelper.CreateNotFoundException(
                                 $"Пользователь не найден. Электронная почта: {request.Email}.",
                                 PublicExceptionMessage);

            var role = user.UserRoles
                       .Select(x => x.Role.Name)
                       .FirstOrDefault() ??
                       throw ExceptionHelper.CreatePublicException("Не удалось получить роль пользователя.");

            if (UserRoles.All.ToLowerInvariant().Contains(role.ToLowerInvariant()) == false)
            {
                throw ExceptionHelper.CreatePublicException("Роль пользователя не поддерживается системой.");
            }

            if (!Crypt.Verify(request.Password, user.Password))
            {
                _logger.LogInformation(
                    $"Пользователь найден, но пароль указан неверно. " +
                    $"Идентификатор пользователя: {user.Id}.");

                throw ExceptionHelper.CreatePublicException(PublicExceptionMessage);
            }

            if (user.Active == false)
            {
                throw ExceptionHelper.CreatePublicException("Аккаунт не подтверждён администратором.");
            }

            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, role)
            };

            var identity = new ClaimsIdentity(claims, "Token",
                                              ClaimsIdentity.DefaultNameClaimType,
                                              ClaimsIdentity.DefaultRoleClaimType);

            var tokenParameters = _configuration
                                  .GetSection(nameof(TokenParameters))
                                  .Get <TokenParameters>();

            var now     = DateTime.UtcNow;
            var expires = now.Add(TimeSpan.FromMinutes(tokenParameters.LifeTimeInMinutes));

            var signingCredentials = new SigningCredentials(
                new SymmetricSecurityKey(tokenParameters.SecretKeyInBytes),
                SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                tokenParameters.Issuer,
                tokenParameters.Audience,
                identity.Claims, now, expires, signingCredentials);

            return(new TokenResponse(new JwtSecurityTokenHandler().WriteToken(token)));
        }
Example #11
0
 public async Task <Result <TokenResponse> > Handle(LoginCommand command, CancellationToken cancellationToken)
 => await _repository.FetchUserAggregate(command.Email)
 .ToResult()
 .Ensure(user => user != null && BC.Verify(command.Password, user.Password), string.Empty, HttpCode.Unauthorized)
 .Finally(_mapper.Map <TokenResponse>);
Example #12
0
 public static bool HashValidate(String value, String hash)
 {
     return(Bcrypt.Verify(value, hash));
 }
Example #13
0
 public override bool Verify(string text, string hash)
 {
     return(BCN.Verify(text, hash));
 }
Example #14
0
        public async Task <AuthenticateResponse> Authenticate(AuthenticateRequest model, string ipAddress)
        {
            var emailBuidler = Builders <Account> .Filter;
            var emailFilter  = emailBuidler.Eq("Email", model.Email);
            var account      = await accountRepository.FindAsync((emailFilter));

            if (account == null)
            {
                var userEmailFilter = Builders <User> .Filter.Eq("phone_number", model.Email);

                var user = await userRepository.FindAsync(userEmailFilter);

                if (user == null)
                {
                    throw new Exception("Tài khoản hoặc mật khẩu không đúng. ");
                }
                emailFilter = emailBuidler.Eq("Email", user.Email);
                account     = await accountRepository.FindAsync((emailFilter));
            }
            if (!BC.Verify(model.Password, account.PasswordHash))
            {
                throw new Exception("Tài khoản hoặc mật khẩu không đúng. ");
            }

            if (!account.IsVerified)
            {
                throw new Exception("Tài khoản chưa được xác thực. ");
            }

            var _user = await userRepository.FindAsync(Builders <User> .Filter.Eq("email", account.Email));

            var existJwts = _user.JwtTokens;

            foreach (var jwt in _user.JwtTokens.ToList().Where(jwt => Feature.ValidateToken(jwt, appSettings.Secret) == null))
            {
                _user.JwtTokens.Remove(jwt);
            }

            var refreshToken = generateRefreshToken(ipAddress);

            account.RefreshTokens.Add(refreshToken);
            removeOldRefreshTokens(account);
            var response = mapper.Map <AuthenticateResponse>(account);

            response.RefreshToken    = refreshToken.Token;
            _user.LatestRefreshToken = refreshToken.Token;
            if (_user.JwtTokens.Any())
            {
                response.JwtToken = _user.JwtTokens.ElementAt(0);
            }
            else
            {
                var jwtToken = generateJwtToken(account);
                response.JwtToken = jwtToken;
                _user.JwtTokens.Add(jwtToken);
            }
            await accountRepository.UpdateAsync(account, account.Id);

            await userRepository.UpdateAsync(_user, _user.Id);

            return(response);
        }
Example #15
0
        public static bool VerifyWithBCrypt(this string hashedPassword, string plainText)
        {
            var result = BCrypt.Verify(plainText, hashedPassword);

            return(result);
        }
 public bool ValidatePassword(string password, string correctHash)
 {
     return(Bcrypt.Verify(password, correctHash));
 }
Example #17
0
 public static bool Validate(string password, string passwordHash)
 => Crypt.Verify(password, passwordHash);
        public async Task <GetAccountResult> Handle(GetAccountQuery query, CancellationToken cancellationToken)
        {
            try
            {
                AccountDetailModel acctDetails = new AccountDetailModel();
                acctDetails = await _accountService.GetAccountDetail(query.AccountNumber, query.AccountPIN);

                if (acctDetails != null)
                {
                    //Validate PIN
                    if (!BC.Verify(query.AccountPIN, acctDetails.AccountPIN))
                    {
                        return(new GetAccountResult
                        {
                            StatusCode = Convert.ToInt32(HttpStatusCode.OK),
                            Message = Convert.ToString(HttpStatusCode.OK),
                            MessageDetails = ManageAccountStatus.InvalidAccountPIN,
                            AcctId = acctDetails.AcctId,
                            FirstName = acctDetails.FirstName,
                            MiddleName = acctDetails.MiddleName,
                            LastName = acctDetails.LastName,
                            AccountNumber = acctDetails.AccountNumber
                        });
                    }
                    else
                    {
                        return(new GetAccountResult
                        {
                            StatusCode = Convert.ToInt32(HttpStatusCode.OK),
                            Message = Convert.ToString(HttpStatusCode.OK),
                            MessageDetails = ManageAccountStatus.AccountDetailRetrieveSuccessful,
                            AcctId = acctDetails.AcctId,
                            FirstName = acctDetails.FirstName,
                            MiddleName = acctDetails.MiddleName,
                            LastName = acctDetails.LastName,
                            AccountNumber = acctDetails.AccountNumber,
                            AccountPIN = acctDetails.AccountPIN,
                            AccountType = acctDetails.AccountType,
                            AccountStatus = acctDetails.AccountStatus,
                            InitialAmountDeposit = acctDetails.InitialAmountDeposit,
                            DateCreated = acctDetails.DateCreated,
                            DateUpdated = acctDetails.DateUpdated
                        });
                    }
                }
                else
                {
                    return(new GetAccountResult
                    {
                        StatusCode = Convert.ToInt32(HttpStatusCode.OK),
                        Message = Convert.ToString(HttpStatusCode.OK),
                        MessageDetails = ManageAccountStatus.InvalidAccountNumber
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error retrieving account details : {ExceptionMessage}", ex.ToString());

                return(new GetAccountResult
                {
                    StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError),
                    Message = Convert.ToString(HttpStatusCode.InternalServerError),
                    MessageDetails = ManageAccountStatus.AccountDetailRetrieveFailed
                });
            }
        }
Example #19
0
 public static bool HashValida(string senha, string hash)
 => BCHash.Verify(senha, hash);
Example #20
0
 public static bool CheckPassword(string passwordToCheck, string hashedPassword)
 {
     return(Encrypt.Verify(passwordToCheck + extraSalt, hashedPassword));
 }
 public bool Verify(string password, string hash)
 => Hash.Verify(password, hash);
Example #22
0
 public bool Verify(string password, string passwordHash) => BC.Verify(password, passwordHash);
        public async Task <IActionResult> Login(LoginViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                bool passwordOk;

                // Get user from database
                var user = _unitOfWork.User.GetFirstOrDefault(u => u.Id == viewModel.Id, "Branch");

                if (user != null)
                {
                    if (user.UserLocked == true)
                    {
                        TempData["LoginAttemptsMaxed"] = "Your account has been locked. Please contact Admin";
                        return(View("Login"));
                    }

                    if (user.FailedLoginAttempts == MaxLoginAttempts)
                    {
                        TempData["LoginAttemptsMaxed"] = "Your account has been locked. Please contact Admin";
                        user.UserLocked = true;
                        _unitOfWork.Save();
                        return(View("Login"));
                    }

                    // Verify the password
                    passwordOk = BC.Verify(viewModel.Password, user.Password);

                    // If password is incorrect increase their failed login attempts in DB
                    if (!passwordOk)
                    {
                        user.FailedLoginAttempts++;
                        _unitOfWork.Save();
                        TempData["PasswordInvalid"] = "The password entered is invalid.";
                        return(View("Login"));
                    }

                    // This would be executed if the user is logging in for the first time
                    // They will need to change there password to something they want
                    if (user.LastLoginTime == null)
                    {
                        return(View("ChangePassword"));
                    }
                }
                else
                {
                    TempData["IdNotFound"] = "The EmployeeId not found.";
                    return(View("Login"));
                }

                // Set users login attempts and set their login time when they successfully login
                user.FailedLoginAttempts = 0;
                user.LastLoginTime       = DateTime.Now;
                _unitOfWork.Save();

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.Email),
                    new Claim("FirstName", user.FirstName),
                    new Claim("BranchId", user.BranchId.ToString()),
                    new Claim("BranchName", user.Branch.BranchName)
                };

                // Gets the roles the user has
                var userRoles = _context.UserRoles.Join(
                    _context.Roles,
                    ur => ur.RoleId,
                    r => r.Id,
                    (ur, r) => new
                {
                    ur.RoleId,
                    r.RoleName,
                    ur.UserId
                }).Where(_ => _.UserId == user.Id).ToList();

                foreach (var ur in userRoles)
                {
                    var roleClaim = new Claim(ClaimTypes.Role, ur.RoleName);
                    claims.Add(roleClaim);
                }

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties()
                {
                    IsPersistent = viewModel.IsPersistant
                };
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                              new ClaimsPrincipal(claimsIdentity), authProperties);

                return(Redirect("/"));
            }

            return(View(viewModel));
        }
Example #24
0
 /// <summary>
 /// Сравнение пароля с его хешем
 /// </summary>
 /// <param name="password">Пароль</param>
 /// <param name="correctHash">Хеш пароля из БД</param>
 /// <returns></returns>
 public static bool ValidatePassword(string password, string correctHash)
 {
     return(CryptoManager.Verify(password, correctHash));
 }
Example #25
0
        public AuthenticateResponse Authenticate(AuthenticateRequest authDto)
        {
            var _users = _context.account.ToList();
            var user   = _users.SingleOrDefault(x => x.UserName == authDto.UserName && BC.Verify(authDto.Password, x.PasswordInHash));

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

            using (_context)
            {
                var accounts = _context.account
                               .Include(acc => acc.Role)
                               .ToList();
            }
            var token = new JwtService(_config).GenerateSecurityToken(user);

            return(new AuthenticateResponse(user, token));
        }
Example #26
0
        public UserMutation(IUserRepository userRepository, ISeriesRepository seriesRepository, IEpisodeRepository episodeRepository, TokenHelper tokenHelper)
        {
            _userRepository    = userRepository;
            _seriesRepository  = seriesRepository;
            _episodeRepository = episodeRepository;
            _tokenHelper       = tokenHelper;

            Name = "UserMutation";

            Field <StringGraphType>(
                "login",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "email"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "password"
            }
                    ),
                resolve: context =>
            {
                // Get arguments
                string email = context.GetArgument <string>("email");
                string pass  = context.GetArgument <string>("password");

                // Find the corresponding user
                var user = _userRepository.FindByEmail(email);

                // Throw errors
                if (user == null)
                {
                    throw new ExecutionError("User not found");
                }
                if (string.IsNullOrEmpty(user.Password) || !BCr.Verify(pass, user.Password))
                {
                    throw new ExecutionError("Incorrect password");
                }

                // If no errors, generate and give a token
                return(_tokenHelper.GenerateToken(user.Id));
            });

            Field <UserType>(
                "register",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <UserInputType> > {
                Name = "user"
            }),
                resolve: context =>
            {
                // Get the arguments
                var userInput = context.GetArgument <User>("user");

                // If the email is already registered, don't bother
                if (_userRepository.FindByEmail(userInput.Email) != null)
                {
                    throw new ExecutionError("Already registered");
                }

                // Construct a user with the arguments
                var user = ConstructUserFromRegister(userInput);

                // Add and return the result
                var added = _userRepository.Add(user);
                _userRepository.SaveChanges();
                return(added);
            });

            FieldAsync <UserType>(
                "addWatchedEpisode",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "episodeId"
            }),
                resolve: async context =>
            {
                // Args
                int episodeId = context.GetArgument <int>("episodeId");

                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                // Check if episodeid not already in watched
                if (user.WatchedEpisodes.Any(fs => fs.EpisodeId == episodeId))
                {
                    return(user);
                }

                // Get Episode and its Series from db or API
                var episode    = await _episodeRepository.GetByIdAsync(episodeId);
                episode.Series = await _seriesRepository.GetByIdAsync(episode.SeriesId);

                // Add the episode to the users watched episodes and persist
                user.AddWatchedEpisode(episode);
                _userRepository.Update(user);
                _userRepository.SaveChanges();
                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this

            Field <UserType>(
                "removeWatchedEpisode",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "episodeId"
            }),
                resolve: context =>
            {
                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                // Get episode and remove it from watched
                var episode = user.WatchedEpisodes.SingleOrDefault(we => we.EpisodeId == context.GetArgument <int>("episodeId"));
                user.WatchedEpisodes.Remove(episode);
                _userRepository.Update(user);
                _userRepository.SaveChanges();

                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this


            FieldAsync <UserType>(
                "addFavoriteSeries",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "seriesId"
            }),
                resolve: async context =>
            {
                int seriesId = context.GetArgument <int>("seriesId");

                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                // Check if seriesid not already in favorites
                if (user.FavoriteSeries.Any(fs => fs.SeriesId == seriesId))
                {
                    return(user);
                }

                // Get series from db or API
                var series = await _seriesRepository.GetByIdAsync(seriesId);

                // Add the favorite and persist
                user.AddFavoriteSeries(series);
                _userRepository.Update(user);
                _userRepository.SaveChanges();
                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this

            Field <UserType>(
                "removeFavoriteSeries",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "seriesId"
            }
                    ),
                resolve: context =>
            {
                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                //Get series and remove from favorites
                var series = user.FavoriteSeries.Single(fs => fs.SeriesId == context.GetArgument <int>("seriesId"));
                user.FavoriteSeries.Remove(series);
                _userRepository.Update(user);
                _userRepository.SaveChanges();

                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this

            FieldAsync <UserType>(
                "addSeriesToWatchList",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "seriesId"
            }),
                resolve: async context =>
            {
                // Args
                int seriesId = context.GetArgument <int>("seriesId");

                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                // Check if seriesid not already in watchlist
                if (user.WatchListedSeries.Any(fs => fs.SeriesId == seriesId))
                {
                    return(user);
                }

                // Get series from db or API
                var series = await _seriesRepository.GetByIdAsync(seriesId);

                // Add the favorite and persist
                user.AddSeriesToWatchList(series);
                _userRepository.Update(user);
                _userRepository.SaveChanges();
                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this

            Field <UserType>(
                "removeSeriesFromWatchList",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "seriesId"
            }),
                resolve: context =>
            {
                // Get logged in user
                int userId = (context.UserContext as GraphQLUserContext).UserId;
                var user   = _userRepository.GetById(userId);

                // get series
                var series = user.WatchListedSeries.Single(fs => fs.SeriesId == context.GetArgument <int>("seriesId"));

                //remove series from watched
                user.WatchListedSeries.Remove(series);
                _userRepository.Update(user);
                _userRepository.SaveChanges();

                return(user);
            }
                ).AuthorizeWith("UserPolicy"); //Only authenticated users can do this
        }
Example #27
0
 public IActionResult Login(UserVM userVM)
 {
     if (ModelState.IsValid)
     {
         var getUserRole = _context.RoleUsers.Include("User").Include("Role").SingleOrDefault(x => x.User.Email == userVM.Email);
         if (getUserRole == null)
         {
             return(NotFound());
         }
         else if (userVM.Password == null || userVM.Password.Equals(""))
         {
             return(BadRequest(new { msg = "Password must filled" }));
         }
         else if (!Bcrypt.Verify(userVM.Password, getUserRole.User.PasswordHash))
         {
             return(BadRequest(new { msg = "Password is Wrong" }));
         }
         else
         {
             //var user = new UserVM();
             //user.Id = getUserRole.User.Id;
             //user.UserName = getUserRole.User.UserName;
             //user.Email = getUserRole.User.Email;
             //user.Password = getUserRole.User.PasswordHash;
             //user.Phone = getUserRole.User.PhoneNumber;
             //user.RoleName = getUserRole.Role.Name;
             if (getUserRole != null)
             {
                 if (getUserRole.User.SecurityStamp != null)
                 {
                     var claims = new List <Claim> {
                         new Claim("Id", getUserRole.User.Id),
                         new Claim("UserName", getUserRole.User.UserName),
                         new Claim("Email", getUserRole.User.Email),
                         new Claim("RoleName", getUserRole.Role.Name),
                         new Claim("VerifyCode", getUserRole.User.SecurityStamp)
                     };
                     var key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
                     var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                     var token  = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);
                     return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
                 }
                 else
                 {
                     var claims = new List <Claim> {
                         new Claim("Id", getUserRole.User.Id),
                         new Claim("UserName", getUserRole.User.UserName),
                         new Claim("Email", getUserRole.User.Email),
                         new Claim("RoleName", getUserRole.Role.Name)
                     };
                     var key    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
                     var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                     var token  = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);
                     return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
                 }
             }
             return(BadRequest("Invalid credentials"));
         }
     }
     return(BadRequest("Login Failed"));
 }
Example #28
0
        public async Task <IActionResult> Login([FromBody] UserLoginDto user)
        {
            // check if the user(name) exists, if they don't return an error
            var foundUser = await _context.GetUserByUsername(user.Username);

            if (foundUser == null)
            {
                var err = new ErrorObject()
                {
                    Method     = "POST",
                    At         = "/users",
                    StatusCode = 404,
                    Error      = "User not found"
                };
                return(NotFound(err));
            }

            // verify that the password matches, if they don't return an error
            var authenticated = BC.Verify(user.Password, foundUser.Password);

            if (!authenticated)
            {
                var err = new ErrorObject()
                {
                    Method     = "POST",
                    At         = "/users/login",
                    StatusCode = 404,
                    Error      = "Wrong Password"
                };
                return(NotFound(err));
            }

            // create the JWT token
            var tokenHandler = new JwtSecurityTokenHandler();
            // get out signature to sign the token
            var key             = Encoding.ASCII.GetBytes(_secretsOptions.Signature);
            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                // add claims (strings of information along with token)
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("userId", foundUser.Id.ToString()),
                    new Claim("username", foundUser.Username),
                    new Claim(ClaimTypes.Role, foundUser.Role),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                }),
                // how long the token can be used for
                Expires = DateTime.UtcNow.AddHours(4),
                // sign the token with our key
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                // add who issued the token to which audience
                Issuer   = _secretsOptions.Issuer,
                Audience = _secretsOptions.Audience,
            };

            if (foundUser.Role == Roles.User)
            {
                tokenDescriptor.Subject.AddClaims(new Claim[]
                {
                    new Claim("profileId", foundUser.Profile.Id.ToString()),
                    new Claim("firstName", foundUser.Profile.FirstName),
                });
            }

            // create the token, turn it into a string and return it
            var token    = tokenHandler.CreateToken(tokenDescriptor);
            var tokenStr = tokenHandler.WriteToken(token);

            return(Ok(new Token {
                Jwt = tokenStr
            }));
        }
Example #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public async Task <IResult> GetEmployee(UserLoginViewModel loginModel)
        {
            var result = new Result
            {
                Operation  = Operation.Read,
                Status     = Status.Success,
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                if (loginModel != null)
                {
                    var employeeModel = await _employeeRepository.GetEmployeeByEmail(loginModel.Email);

                    if (employeeModel == null)
                    {
                        result.Body       = null;
                        result.Message    = "Account with " + loginModel.Email + " does not exists.";
                        result.Status     = Status.Fail;
                        result.StatusCode = HttpStatusCode.NotFound;
                        return(result);
                    }
                    else
                    {
                        if (!BC.Verify(loginModel.Password, employeeModel.Password))
                        {
                            result.Body       = null;
                            result.Message    = "Password is incorrect";
                            result.Status     = Status.Fail;
                            result.StatusCode = HttpStatusCode.Forbidden;
                            return(result);
                        }
                        // check if employee is confirmed or not
                        if (employeeModel.Status == EntityStatus.Accept)
                        {
                            var roles = new List <EmployeeRoleViewModel>();
                            roles = employeeModel.EmployeeRoles.Select(t =>
                            {
                                var role        = new EmployeeRoleViewModel();
                                role.Id         = t.Id;
                                role.RoleId     = t.RoleId;
                                role.RoleName   = t.Role.Name;
                                role.EmployeeId = t.EmployeeId;
                                return(role);
                            }).ToList();

                            UserViewModel userView = new UserViewModel()
                            {
                                Email        = employeeModel.Email,
                                EmployeeCode = employeeModel.EmployeeCode,
                                Name         = employeeModel.Name,
                                UserId       = employeeModel.Id,
                                CurrentResidentialAddress   = employeeModel.CurrentResidentialAddress,
                                PermanentResidentialAddress = employeeModel.PermanentResidentialAddress,
                                Token = GenerateToken(employeeModel.Name, employeeModel.Email),
                                Roles = roles
                            };
                            result.Body = userView;
                        }
                        else if (employeeModel.Status == EntityStatus.Deny)
                        {
                            result.Body       = null;
                            result.Message    = "Your account has declined by the HR";
                            result.Status     = Status.Fail;
                            result.StatusCode = HttpStatusCode.Forbidden;
                        }
                        else
                        {
                            result.Body       = null;
                            result.Message    = "Your account has not confirmed yet by the HR";
                            result.Status     = Status.Fail;
                            result.StatusCode = HttpStatusCode.Unauthorized;
                        }
                    }
                    return(result);
                }
                else
                {
                    result.Status     = Status.Fail;
                    result.StatusCode = HttpStatusCode.BadRequest;
                    return(result);
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.Status  = Status.Error;
                return(result);
            }
        }
Example #30
0
        public async Task <AuthenticateResponse> Authenticate(AuthenticateRequest model, string ipAddress)
        {
            var user = (await _usersService.GetAllUsers()).FirstOrDefault(user => user.Username == model.Username && BC.Verify(model.Password, user.Password));

            // return null if user not found
            if (user == null)
            {
                throw new Exception("Username or Password is incorrect");
            }

            // authentication successful so generate jwt and refresh tokens
            var jwtToken     = generateJwtToken(user);
            var refreshToken = generateRefreshToken(ipAddress);

            // save refresh token
            user.RefreshTokens.Add(refreshToken);

            // remove old refresh tokens from account
            removeOldRefreshTokens(user);

            //save changes to db
            await _usersService.UpdateUser(user);

            return(new AuthenticateResponse(user, jwtToken, refreshToken.Token));
        }