public async Task <IActionResult> Login([FromBody] UserLoginViewModel model) { if (!ModelState.IsValid) { return(BadRequest("Спробуйте знову")); } if (!_recaptchaService.IsValid(model.RecaptchaToken)) { return(BadRequest("Я вас упізнав. Ви - бот!!!")); } var user = _context.Users.FirstOrDefault(u => u.Email == model.Email); if (user == null) { return(BadRequest("Даний користувач не знайдений!")); } var result = _signInManager .PasswordSignInAsync(user, model.Password, false, false).Result; if (!result.Succeeded) { return(BadRequest("Невірно введений пароль!")); } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _IJwtTokenService.CreateToken(user) })); }
public async Task <IActionResult> Login([FromBody] UserLoginViewModel model) { if (!ModelState.IsValid) { //var errrors = CustomValidator.GetErrorsByModel(ModelState); return(BadRequest("Bad Model")); } var user = _context.Users.FirstOrDefault(u => u.Email == model.Email); if (user == null) { return(BadRequest(new { invalid = "Даний користувач не знайденний" })); } var result = _signInManager .PasswordSignInAsync(user, model.Password, false, false).Result; if (!result.Succeeded) { return(BadRequest(new { invalid = "Невірно введений пароль" })); } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _IJwtTokenService.CreateToken(user) })); }
public async Task <LoginResponse> Login(LoginRequest request) { var result = await _signInManager.PasswordSignInAsync(request.Username, request.Password, request.RememberMe, true); if (result.RequiresTwoFactor) { return(LoginResponse.TwoFactorAuthenticationEnabled()); } if (result.IsLockedOut) { return(LoginResponse.LockedOut()); } if (result.Succeeded) { var user = _applicationUserManager.Users.Include(y => y.Groups).First(x => x.UserName.ToLower().Equals(request.Username)); var roles = await _applicationUserManager.GetRolesAsync(user); var groups = user.Groups.Select(x => x.Group.Name); var token = _jwtTokenService.CreateToken(HelperService.ToUser(user), roles); return(LoginResponse.Success(token, GetResponseUser(user, token))); } else { return(LoginResponse.Failure("Invalid Username or Password")); } }
public async Task <ActionResult> Login([FromBody] LoginViewModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { return(Ok(_jwtTokenService.CreateToken(user))); } return(Unauthorized()); }
public async Task <ResultDto> Login(LoginDTO model) { var res = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!res.Succeeded) { return new ResultDto() { IsSuccessful = false, Message = "error data" } } ; var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, isPersistent : false); //return new ResultDto() { IsSuccessful = true, Message = "good" }; return(new ResultLoginDTO { IsSuccessful = true, Token = _jwtTokenService.CreateToken(user) }); } }
//Logins user public async Task <UserModel> LoginAsync(LoginModel login) { UserModel user = await _userRepository.GetByUsernameAsync(login.Username); if (user == null) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Username", "Username is not registered"); errors.Throw(); } if (user.Password != login.Password) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("Password", "Username and password is not matched"); errors.Throw(); } if (user.Status == (int)UserStatus.Banned) { CustomException errors = new CustomException((int)HttpStatusCode.BadRequest); errors.AddError("User Is Banned", "User is banned from application"); errors.Throw(); } user.Token = _jwtTokenService.CreateToken(user); user.DeviceId = login.DeviceId; _userRepository.Update(user); return(user); }
public async Task <IActionResult> CreateOrder([FromBody] OrdertoBeReserved ordertoBeReserved) { if (ModelState.IsValid) { try { var appUser = new AppUser { UserName = Guid.NewGuid().ToString(), SecurityStamp = Guid.NewGuid().ToString(), Email = "Guest@eventdb" }; var result = await _userManager.CreateAsync(appUser); if (result.Succeeded) { List <Claim> Claims = new List <Claim>() { new Claim(ClaimTypes.Role, "GuestCustomer") }; await _userManager.AddClaimsAsync(appUser, Claims); } else { return(NotFound()); } var Orderreserved = await _orderRepository.CreatOrder(ordertoBeReserved.Eventid, appUser.Id, ordertoBeReserved.TicketsToReserve, ordertoBeReserved.Recurring, ordertoBeReserved.NoofTicketsInOrder, ordertoBeReserved.OrderStartDate.ToUniversalTime(), ordertoBeReserved.OrderEndDate.ToUniversalTime()); return(Ok(new { token = _jwtTokenService.CreateToken(appUser), order = Orderreserved })); } catch (Exception ex) { throw; } } return(NotFound()); }
public async Task <ActionResult <AuthorizationResponse> > Authenticate([FromBody] AuthorizationRequest authorizationRequest) { RoadkillIdentityUser identityUser = await _userManager.FindByEmailAsync(authorizationRequest.Email); if (identityUser == null) { return(NotFound($"The user with the email {authorizationRequest.Email} could not be found.")); } SignInResult result = await _signInManager.PasswordSignInAsync(identityUser, authorizationRequest.Password, true, false); if (result.Succeeded) { IList <Claim> existingClaims = await _userManager.GetClaimsAsync(identityUser); if (existingClaims.Count == 0) { return(StatusCode(StatusCodes.Status403Forbidden)); } // When testing on localhost, RemoteIpAddress is null. var ipAddress = HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; string ip = ipAddress.ToString(); var token = new AuthorizationResponse() { JwtToken = _jwtTokenService.CreateToken(existingClaims, identityUser.Email), RefreshToken = await _jwtTokenService.CreateRefreshToken(identityUser.Email, ip) }; return(Ok(token)); } // don't use Forbid() as it goes through ASP.NET Core's authentication middleware return(StatusCode(StatusCodes.Status403Forbidden)); }
public async Task <IActionResult> SignIn([FromBody] SignInModel model) { if (!ModelState.IsValid) { var errors = CustomValidator.GetErrorsByModel(ModelState); return(BadRequest(errors)); } var user = await userManager.FindByEmailAsync(model.UserName); if (user == null) { return(NotFound($"User email = {model.UserName} was not found")); } var result = await signInManager.PasswordSignInAsync(user, model.Password, false, false); if (!result.Succeeded) { return(BadRequest($"Incorrect password!")); } var token = jwtTokenService.CreateToken(user); var userInfoModel = new UserInfoModel { Token = token }; return(Ok(userInfoModel)); }
public async Task <HttpResponseMessage> Post([FromBody] SignUpModel model) { if (ModelState.IsValid) { IEnumerable <string> jwtAudiance = GetAudience(); if (jwtAudiance == null || !jwtAudiance.Any()) { return(Request.CreateResponse("Null or invalid Audiance.")); } User user = await loginService.SignUp(new User { Username = model.Username, Password = model.Senha, Email = model.Email, Name = model.Name }); string token = jwtService.CreateToken(user.Username, jwtAudiance.First(), user.Roles.Select(x => x.Descricao)); return(Request.CreateResponse(HttpStatusCode.OK, token)); } return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.Select(x => x.Value))); }
public async Task <User> Login(UserLogin user) { var dbUser = await _userRepository.Login(user); if (dbUser == null) { return(null); } if (_passwordHasher.VerifyHashedPassword(dbUser.Password, user.Password) == PasswordVerificationResult.Failed) { return(null); } var userModel = _mapper.Map <UserEntity, User>(dbUser); userModel.Token = _jwtTokenService.CreateToken(userModel.Id.ToString()); return(userModel); }
public async Task <IActionResult> Login([FromBody] LoginViewmodel value) { var user = await _userManager.FindByEmailAsync(value.Email); if (user != null && await _userManager.CheckPasswordAsync(user, value.Password)) { _jwtTokenService.CreateToken(user); } return(Unauthorized()); }
public async Task <IActionResult> RegisterUserAsync([FromBody] RegisterUserRequestDto dto) { try { var user = await _userService.CreateAsync(dto.Username, dto.Password, dto.Email); var response = _mapper.Map <RegisterUserResponseDto>(user); response.Token = _jwtTokenService.CreateToken(user); return(Ok(response)); } catch (BaseBusinessLogicException e) { return(NotFound(e.Message)); } catch (Exception e) { return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message)); } }
public async Task RegisterUserAsync_Should_Return_Correct_Result_If_No_Exceptions(RegisterUserRequestDto registerUserRequestDto, UserModel userModel, string token, RegisterUserResponseDto registerUserResponseDto) { _userService.CreateAsync(registerUserRequestDto.Username, registerUserRequestDto.Password, registerUserRequestDto.Email).Returns(userModel); _mapper.Map <RegisterUserResponseDto>(userModel).Returns(registerUserResponseDto); _jwtTokenService.CreateToken(userModel).Returns(token); var result = await _userControllerInstance.RegisterUserAsync(registerUserRequestDto); var response = result as OkObjectResult; Assert.NotNull(response); var responseObject = response.Value as RegisterUserResponseDto; Assert.NotNull(responseObject); Assert.AreEqual(registerUserResponseDto.Username, responseObject.Username); Assert.AreEqual(token, responseObject.Token); }
/// <summary> /// Create an authorize token for valid users /// </summary> /// <param name="model">User credentials</param> /// <returns>Auth token</returns> public async Task <HttpResponseMessage> Post([FromBody] AuthModel model) { IEnumerable <string> roles = await loginService.Login(model.Username, model.Password); IEnumerable <string> jwtAudiance = GetAudience(); if (jwtAudiance == null || !jwtAudiance.Any()) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid or null audiance.")); } string jwtToken = jwtService.CreateToken(model.Username, jwtAudiance.First(), roles); return(Request.CreateResponse(HttpStatusCode.OK, jwtToken)); }
public async Task <JsonWebToken> HandleAsync(SignInCommand command) { var user = await _usersRepository.GetAsync(command.Email); if (user is null) { throw new MyShopException("invalid_credentials", "Invalid credenctials."); } var refreshToken = new RefreshToken(user, _passwordHasher); var jwt = _jwtTokenService.CreateToken(user.Id, user.Role); jwt.SetRefreshToken(refreshToken.Token); await _refreshTokensRepository.AddAsync(refreshToken); return(jwt); }
public async Task <JsonWebToken> HandleAsync(RefreshAccessTokenCommand command) { var refreshToken = await _refreshTokensRepository.GetAsync(command.Token); if (refreshToken is null) { throw new NotFoundException(ErrorCodes.refresh_token_not_found); } var user = await _usersRepository.GetAsync(refreshToken.UserId); user.NullCheck(ErrorCodes.user_not_found, refreshToken.UserId); var jwt = _jwtTokenService.CreateToken(user.Id, user.Role); jwt.SetRefreshToken(refreshToken.Token); return(jwt); }
public IHttpActionResult CreateToken(CreateTokenRequest paramaters) { try { return(Ok( new CreateTokenResult( _tokenService.CreateToken( paramaters.Name, paramaters.UniqueId, paramaters.Payload != null ? paramaters.Payload.ToDictionary(c => c.Key, c => c.Value) : null ) ) )); } catch (Exception ex) { return(InternalServerError(ex)); } }
public async Task <ResultDTO> Login(UserLoginDTO model) { if (!ModelState.IsValid) { return(new ErrorResultDTO { StatusCode = 500, Message = "Login Error", Errors = CustomValidator.GetErrorsByModel(ModelState) }); } var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { return(new ErrorResultDTO { StatusCode = 402, Message = "Login failed", Errors = new List <string> { "Login or password error" } }); } else { var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, false); return(new SuccessResultDTO { StatusCode = 200, Message = "Ok", Token = _iJWTTokenService.CreateToken(user) }); } }
public async Task<IActionResult> Login([FromBody] LoginModel model) { if (!ModelState.IsValid) { return BadRequest("Введіть всі данні"); } var user = _context.Users.Include(u=> u.BaseProfile).FirstOrDefault(x => x.Email == model.Email); if (user == null) { return BadRequest("Не правильна електронна пошта!"); } var res = _signInManager .PasswordSignInAsync(user, model.Password, false, false).Result; if (!res.Succeeded) { return BadRequest("Не правильний пароль!"); } await _signInManager.SignInAsync(user, isPersistent: false); return Ok(new {token=_jwtTokenService.CreateToken(user)}); }
public async Task <ResultDto> Login(LoginDto model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { return(new ResultDto { IsSuccessful = false }); } var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, isPersistent : false); return(new ResultLoginDto { IsSuccessful = true, Token = _jwtTokenService.CreateToken(user) }); }
public async Task <ResultDto> Login(LoginDto model) { try { var res = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!res.Succeeded) { return new ResultDto { IsSuccessful = false } } ; var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, isPersistent : false); var id = ctx.Users.Where(el => el.Email == model.Email).FirstOrDefault().Id; return(new ResultLoginDto { IsSuccessful = true, Token = _jwtTokenService.CreateToken(user), Message = id }); } catch (Exception ex) { return(new ResultDto { IsSuccessful = false, Message = ex.Message }); } }
public async Task <IActionResult> Get(int id, int userid) { return(Ok(new { Order = await _orderRepository.Getorder(id), token = _jwtTokenService.CreateToken(await _userManager.FindByIdAsync(userid.ToString())) })); }
public async Task Authenticate_should_return_jwt_and_refresh_token_logging_ip() { // given string ipAddress = "9.8.7.6"; string refreshToken = "refresh token"; string jwtToken = "jwt token"; string email = "*****@*****.**"; string password = "******"; var roadkillUser = new RoadkillIdentityUser() { Id = "1", UserName = email, NormalizedUserName = email.ToUpperInvariant(), Email = email, NormalizedEmail = email.ToUpperInvariant(), RoleClaims = new List <string>() }; var model = new AuthorizationRequest() { Email = email, Password = password }; _userManagerMock.FindByEmailAsync(email) .Returns(Task.FromResult(roadkillUser)); _signinManagerMock.PasswordSignInAsync(roadkillUser, password, true, false) .Returns(Task.FromResult(SignInResult.Success)); var claims = new List <Claim>() { new Claim("any", "thing") } as IList <Claim>; _userManagerMock.GetClaimsAsync(roadkillUser) .Returns(Task.FromResult(claims)); _jwtTokenService .CreateToken(claims, roadkillUser.Email) .Returns(jwtToken); var httpContext = new DefaultHttpContext(); httpContext.Connection.RemoteIpAddress = IPAddress.Parse(ipAddress); _authorizationController.ControllerContext.HttpContext = httpContext; _jwtTokenService .CreateRefreshToken(roadkillUser.Email, ipAddress) .Returns(refreshToken); // when ActionResult <AuthorizationResponse> actionResult = await _authorizationController.Authenticate(model); // then actionResult.Result.ShouldBeOfType <OkObjectResult>(); var okResult = actionResult.Result as OkObjectResult; var response = okResult.Value as AuthorizationResponse; response.ShouldNotBeNull(); response.JwtToken.ShouldBe(jwtToken); response.RefreshToken.ShouldBe(refreshToken); }