public async Task <IActionResult> Login(JObject credentials) { if (!credentials.TryGetValue("username", StringComparison.InvariantCultureIgnoreCase, out JToken username) || !credentials.TryGetValue("password", StringComparison.InvariantCultureIgnoreCase, out JToken password)) { return(BadRequest()); } string realUsername = username.Value <string>().ToLower(); User user = await userService.GetByUsername(realUsername); if (user == null) { return(Unauthorized()); } if (passwordService.CheckPassword(password.Value <string>(), user.encryptedPassword)) { JObject obj = new JObject(); obj.Add("token", authorization.GenerateToken(user.username, user.role)); obj.Add("role", user.role.ToString()); var result = new JsonResult(obj); result.StatusCode = StatusCodes.Status200OK; return(result); } return(Unauthorized()); }
public async Task <IActionResult> Login([FromBody] ApiV1LoginRequestModel model) { if (model != null && ModelState.IsValid) { logger.LogDebug($"Attempting to login user with email {model.EMail}."); try { var error = new ApiV1ErrorResponseModel("The combination of password an username is wrong or the user does not exist at all."); // Throw bad request if a user is logged-in already if (loginService.IsLoggedIn()) { return(BadRequest(new ApiV1ErrorResponseModel("Cannot login twice. Please logout first."))); } // Try to get user from database var user = await userService.GetByEMailAsync(model.EMail); // Check if user exists. // If the user does not exist, we return 403 to not reveal that it does not exist if (user == null) { logger.LogWarning($"Error while logging in user with email {model.EMail}. The user does not exist."); return(StatusCode(403, error)); } // Check if password is correct if (passwordService.CheckPassword(model.Password, user.Password)) { loginService.Login(user.Id); logger.LogInformation($"Successfully logged in user with email {model.EMail}."); return(Ok(new { user.Id, user.FirstName, user.LastName, user.Email, user.IsAdmin })); } else { logger.LogWarning($"Error while logging in user with email {model.EMail}: The password is incorrect."); return(StatusCode(403, error)); } } catch (Exception ex) { logger.LogError(ex, $"Error while logging in: {ex.Message}"); return(StatusCode(500, new ApiV1ErrorResponseModel("Error while handling request."))); } } else { logger.LogWarning($"Error while logging in. Validation failed."); return(BadRequest(ModelState.ToApiV1ErrorResponseModel())); } }
public async Task <User> AssertAuthorityToOperateOn(Guid requestUserRefKey, string password) { // Get the requested user. User user = await _context.Users.GetByRefKeyOrDefault(requestUserRefKey); if (user == null) { throw new UserNotFoundException(requestUserRefKey); } // Can the current user manipulate it? long currentUserId = _currentUserService.GetCurrentUserId(); if (currentUserId != user.Id) { bool isAdmin = await CheckIsAdmin(currentUserId); if (!isAdmin) { throw new MustBeAdminException(); } } else { bool matches = _passService.CheckPassword(password, user); if (!matches) { bool isAdmin = await CheckIsAdmin(currentUserId); if (!isAdmin) { throw new PasswordIncorrectException(); } } } return(user); }
public async Task <JwtTokenDto> SignInAsync(SignInDto dto) { IUserEntity userEntity = await _userRepository.GetByEmailAsync(dto.Email); if (userEntity is null) { throw new InvalidUserCredentialsException(); } if (!_passwordService.CheckPassword(dto.Password, userEntity.Password)) { throw new InvalidUserCredentialsException(); } var token = _tokenService.CreateToken(userEntity); var refresh = _passwordService.GenerateSalt(); await _refreshTokenRepository.SaveTokenAsync(userEntity.Id, refresh, DateTime.Now.AddHours(3)); return(new JwtTokenDto(token, refresh)); }
public string Login(LoginModel model) { var user = GetDto(model.Username); if (user == null) { return(null); } if (!user.EmailVerified) { throw new ArgumentException("Please verify your email address"); } if (_passwordService.CheckPassword(user.Id, model.Password)) { var token = _tokenService.Create(user.Id); _tokenService.Get(token); return(token); } return(null); }
public async Task <User> AuthenticateUserWithPassword(string email, string password) { var checkUser = await _userRepository.GetUser(email); if (checkUser != null) { if (_passwordService.CheckPassword(checkUser, password)) { return(checkUser); } else { //bad password return(null); } } else { //not found with email return(null); } }
public async Task <string> CreateNewTestimonialCode(CreateTestimonialCodeDto createTestimonialCodeDto) { if (!_passwordService.CheckPassword(createTestimonialCodeDto.AdminPassword, _adminPasswordHash)) { throw new IncorrectAdminPasswordException(); } string code; // Ensure no clashes no matter how unlikely do { code = _cryptoService.GenerateCode(6); } while (_databaseContext.TestimonialCodes.Any(c => c.Code == code)); await _databaseContext.TestimonialCodes.AddAsync(new TestimonialCodeModel( createTestimonialCodeDto.FirstName, createTestimonialCodeDto.LastName, createTestimonialCodeDto.Description, code, DateTime.Now.AddDays(28))); await _databaseContext.SaveChangesAsync(); return(code); }
public bool CheckPassword(string UserId, string password) { return(passwordService.CheckPassword(UserId, password)); }