public IActionResult Auth([FromBody] AuthRequestViewModel authRequest) { try { var appLogin = loginRepo.AsQueryable().Where(l => l.UserName == authRequest.UserName).SingleOrDefault(); if (appLogin == null) { var message = $"Brugernavn {authRequest.UserName} ikke fundet"; logger.LogWarning(message); return(ErrorResult(message, ErrorCodes.InvalidAuthorization, HttpStatusCode.Unauthorized)); } if (appLogin.Password != GetHash(appLogin.Salt, authRequest.Password)) { var message = $"Ugyldigt kodeord for brugeren {authRequest.UserName}"; logger.LogWarning(message); return(ErrorResult(message, ErrorCodes.InvalidAuthorization, HttpStatusCode.Unauthorized)); } var userInfo = GenerateUserInfo(appLogin); return(Ok(userInfo)); } catch (Exception e) { logger.LogError(e, $"{GetType().Name}, Post(), Post method failed"); throw; } }
public LoginDataViewModel Login(AuthRequestViewModel aAuthRequest) { var user = _db.FindUser(aAuthRequest.EmailAddress, aAuthRequest.Password); if (user == null) { return(null); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.UserAccountId), new Claim(ClaimTypes.Name, user.FullName), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.DateOfBirth, user.DateOfBirth.ToString("yyyy-MM-dd")), new Claim(ClaimTypes.Email, user.EmailAddress), new Claim(ClaimTypes.Role, user.IsAdmin ? "Admin" : "User") }; var securityToken = new JwtSecurityToken( "localhost:56653", "localhost:56653", claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: mySigningCredentials); var token = new JwtSecurityTokenHandler().WriteToken(securityToken); return(new LoginDataViewModel(token, user.UserAccountId)); }
public IHttpActionResult Post([FromBody] AuthRequestViewModel user) { AuthResponseDetails responseDetails = new AuthResponseDetails(); try { User validUser = this.db.Users.Where(x => x.Email == user.Email || x.UserName == user.Email).FirstOrDefault(); if (null != validUser) { if (this.IsUserAccountPasswordValid(user.Password, validUser)) { responseDetails.SuccessMessage = "Login successful"; responseDetails.ResponseCode = ResponseCodeEnum.Success; responseDetails.Details = this.db.Users.Where(x => x.UserID == validUser.UserID).FirstOrDefault(); } else { responseDetails.ErrorMessage = "Oops, invalid user account."; } } else { responseDetails.ErrorMessage = "Oops, invalid user account."; } } catch (Exception ex) { responseDetails.ErrorMessage = "Oops, something went wrong."; responseDetails.ResponseCode = ResponseCodeEnum.InternalServerError; } return(Json(responseDetails)); }
public static AuthRequestViewModel EncryptAuthRequest(AuthRequestViewModel auth) { if (auth.UserName != null) { auth.UserName = StringCipher.Encrypt(auth.UserName, EncryptKey); } return(auth); }
public void LoginController_BadPassword() { //Arrange var mockService = new Mock <ILoginService>(); var controller = new LoginController(mockService.Object); var vm = new AuthRequestViewModel { EmailAddress = "", Password = "" }; mockService.Setup(serv => serv.Login(vm)) .Returns((LoginDataViewModel)null); //Act var result = controller.Authenticate(aAuthRequest: vm); //Assert Assert.IsType <UnauthorizedResult>(result); }
public IActionResult Authenticate([FromBody] AuthRequestViewModel aAuthRequest) { if (ModelState.IsValid) { var authenticated = _loginService.Login(aAuthRequest); if (authenticated != null) { return(Ok(authenticated)); } else { return(Unauthorized()); } } else { return(BadRequest()); } }
public async Task <IActionResult> Token([FromBody] AuthRequestViewModel authRequest) { if (!ModelState.IsValid) { return(BadRequestDueToModelState()); } try { var identity = await GetClaimsIdentity(authRequest.LoginId, authRequest.Password); if (identity == null) { //mark modelstate as invalid //return BadRequest(ModelState.AddErrorToModelState(Constants.Errors.LoginFailed.Code,Constants.Errors.LoginFailed.Desc)); return(BadRequest(new ErrorResponseModel { Message = $"{Constants.Errors.LoginFailed.Code},{Constants.Errors.LoginFailed.Desc}", Code = 400, Exception = nameof(Constants.Errors.LoginFailed) })); } var jwt = await identity.GenerateJwtJson(_tokenUtility, authRequest.LoginId, _options, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(new OkObjectResult(jwt)); } catch (Exception ex) { return(BadRequest(new ErrorResponseModel { Message = ex.Message, Code = 400, Exception = ex.GetType().Name })); } }
// POST api/auth public IHttpActionResult Post(AuthRequestViewModel obj) { try { var users = AuthRepo.Get(); UserAuth user = null; foreach (var u in users) { var decryptedUserName = Encryptor.DecryptUserName(u.UserName); if (decryptedUserName.Equals(obj.UserName, StringComparison.CurrentCultureIgnoreCase)) { user = u; } } var auth = Encryptor.EncryptAuthRequest(obj); if (user == null || user.Password != GetHash(user.Salt, obj.Password) || user.Profile.IsActive == false) { _logger.Debug($"{GetType().Name}, Post(), Username or password is incorrect for user: "******"Username or password is incorrect", ErrorCodes.IncorrectUserNameOrPassword, HttpStatusCode.Unauthorized)); } var profile = AutoMapper.Mapper.Map <ProfileViewModel>(user.Profile); profile = Encryptor.DecryptProfile(profile); var currentTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; profile.Employments = profile.Employments.AsQueryable().Where(x => x.StartDateTimestamp < currentTimestamp && (x.EndDateTimestamp > currentTimestamp || x.EndDateTimestamp == 0)).ToList(); var authModel = new AuthorizationViewModel { GuId = user.GuId }; profile.Authorization = Encryptor.DecryptAuthorization(authModel); var currentYear = DateTime.Now.Year; var ui = new UserInfoViewModel { profile = profile, rates = AutoMapper.Mapper.Map <List <RateViewModel> >(RateRepo.Get().Where(x => x.Year == currentYear.ToString() && x.isActive).ToList()) }; //Auditlogging try { Auditlog(auth.UserName, System.Reflection.MethodBase.GetCurrentMethod().Name, "username/password"); } catch (Exception e) { _logger.Error($"{GetType().Name}, Post(), Auditlogging failed", e); return(InternalServerError()); // Method not allowed to continue if auditlogging fails. } return(Ok(ui)); } catch (Exception e) { _logger.Error($"{GetType().Name}, Post(), Post method failed", e); throw; } }