public async Task <object> CreateNewTokenWithRToken(Guid userId, string refreshToken) { var userToken = await _userTokenServices.GetByUserIdAsync(userId); if (userToken == null) { throw new ExternalException("Token Is Not Valid", 1); } if (userToken.RefreshToken.Trim() != refreshToken.Trim()) { throw new ExternalException("RefreshToken Is not Valid", 2); } if (userToken.GenerationDate.AddMinutes(15) < DateTime.Now) { throw new ExternalException("RefreshToken Is Expired", 3); } var userTokenInfo = new UserTokenViewModel { UserId = userId, GenerationDate = DateTime.Now, IsValid = true, RefreshToken = Guid.NewGuid().ToString() }; await _userTokenServices.UpdateRefreshTokenByUserIdAsync(userTokenInfo); return(userTokenInfo); }
public IHttpActionResult LoginUser(UsersModel model) { try { RegisterDL obj = new RegisterDL(); UsersModel list = obj.UserLogin(model); list.BookingID = entities.Bookings.Where(x => x.PatientID == list.RefID).Select(x => x.BookingID).FirstOrDefault(); responseData.success = true; responseData.code = 200; responseData.message = "Login successfully"; UserTokenViewModel userToken = GenerateAccessTokenForUser(list); list.UserTokenInfo = userToken; responseData.success = true; responseData.data = list; responseData.code = 200; return(Ok(responseData)); } catch (Exception ex) { responseData.message = ex.Message != null?ex.Message.ToString() : "server error"; return(Ok(responseData)); } }
public async Task <UserTokenViewModel> UserTokenManagementAsync(UserViewModel model) { var userTokenInfo = new UserTokenViewModel { UserId = model.Id, GenerationDate = DateTime.Now, IsValid = true, RefreshToken = Guid.NewGuid().ToString() }; var userToken = await _userTokenServices.GetByUserIdAsync(model.Id); if (userToken == null) { await _userTokenServices.AddNewAsync(userTokenInfo); } else { try { await _userTokenServices.UpdateRefreshTokenByUserIdAsync(userTokenInfo); } catch (Exception ex) { var s = ex.Message; throw; } } return(userTokenInfo); }
public IActionResult Authenticate([FromBody] UserLoginViewModel loginViewModel) { var user = _userService.GetByLogin(loginViewModel.Login); if (user == null) { throw new ArgumentException($"User not found"); } if (user.Password != loginViewModel.Password) { throw new ArgumentException("Invalid password"); } var token = TokenService.GenerateToken(user.Id, user.Name, "admin"); var tokenViewModel = new UserTokenViewModel { Id = user.Id, Name = user.Name, Token = token, Login = user.Login, TypeId = user.TypeId }; return(Ok(tokenViewModel)); }
//[HttpGet] //[Route("CountryList")] //public IHttpActionResult CountryList() //{ // try // { // GeneralBusiness generalBusiness = new GeneralBusiness(false); // var listCountries = generalBusiness.GetAllCountries(); // responseData.success = true; // responseData.code = 200; // responseData.message = "country list updated successfully"; // responseData.data = listCountries; // return Ok(responseData); // } // catch (Exception ex) // { // responseData.message = "server error"; // return Ok(responseData); // } //} //[HttpGet] //[Route("StateList/{countryId}")] //public IHttpActionResult StateList(Guid countryId) //{ // try // { // GeneralBusiness generalBusiness = new GeneralBusiness(false); // var listStates = generalBusiness.GetStatesByCountry(countryId); // responseData.success = true; // responseData.code = 200; // responseData.message = "states list updated successfully"; // responseData.data = listStates; // return Ok(responseData); // } // catch (Exception ex) // { // responseData.message = "server error"; // return Ok(responseData); // } //} //[HttpGet] //[Route("CityList/{stateId}")] //public IHttpActionResult CityList(Guid stateId) //{ // try // { // GeneralBusiness generalBusiness = new GeneralBusiness(false); // var listCities = generalBusiness.GetCitiesByState(stateId); // responseData.success = true; // responseData.code = 200; // responseData.message = "cities list updated successfully"; // responseData.data = listCities; // return Ok(responseData); // } // catch (Exception ex) // { // responseData.message = "server error"; // return Ok(responseData); // } //} /// <summary> /// Create access token and refresh token for user login with facebook or google /// </summary> /// <param name="objUser">User Model Object</param> /// <returns>Return Json object with access_token and refresh_token</returns> private UserTokenViewModel GenerateAccessTokenForUser(UsersModel userVM) { var tokenExpirationTimeSpan = TimeSpan.FromDays(1); // var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); //identity.AddClaim(new Claim(ClaimTypes.Role, userVM.UserType)); //identity.AddClaim(new Claim(ClaimTypes.Email, userVM.EmailID)); //identity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.UserID))); ClaimsIdentity oAuthIdentity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.RefType))); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Sid, Convert.ToString(userVM.RefID))); oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Convert.ToString(userVM.UserID))); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Email, userVM.Email)); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()); var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan); var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); AuthenticationTokenCreateContext rtokenContext = new AuthenticationTokenCreateContext(HttpContext.Current.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket); AuthenticationTokenProvider rtokenProvider = new AuthenticationTokenProvider(); var refresh_token = rtokenProvider.CreateRefreshToken(rtokenContext); UserTokenViewModel userToken = new UserTokenViewModel(); userToken.access_token = accessToken; userToken.expires_in = tokenExpirationTimeSpan.TotalSeconds.ToString(); userToken.refresh_token = refresh_token; return(userToken); }
public async Task <IActionResult> ConfirmEmail([FromBody] UserTokenViewModel model) { if (ModelState.IsValid) { var user = await _userService.GetUserById(model.UserId, true); if (user == null) { ModelState.AddModelError("", _localizer["UserNotFound"]); } else { var result = await _userManager.ConfirmEmailAsync(user, model.Code); if (result.Succeeded) { return(Ok(true)); } var hostName = $"{user.TenantId}.{_config["BaseUrlApi"]}"; await SendEmailConfirmLink(user, hostName); ModelState.AddModelError(_localizer["LinkExpired"], _localizer["LinkExpireMsg"]); AddErrors(result); } } return(BadRequest(Errors.GetErrorList(ModelState))); }
public IActionResult Authenticate([FromBody] UserTokenViewModel userParam) { var user = _loginService.Authenticate(userParam.Account, userParam.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user)); }
public async Task UpdateRefreshTokenByUserIdAsync(UserTokenViewModel model) { var userToken = await _context.UserToken.Where(ut => ut.UserId.ToString().ToLower() == model.UserId.ToString().ToLower()).SingleOrDefaultAsync(); if (userToken != null) { userToken.RefreshToken = model.RefreshToken.Trim(); userToken.IsValid = model.IsValid; userToken.GenerationDate = model.GenerationDate; await _context.SaveChangesAsync(); } }
async Task SendTokenEmail(UserTokenViewModel model) { try { var mailUser = new MailAddress(model.UserEmail); var subject = String.Format("{0}, Password Reset !", AppConfig.Settings.AppName); await Mailer.SendAsync("UserToken", model, subject, mailUser); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } }
public async Task AddNewAsync(UserTokenViewModel model) { var userToken = _mapper.Map <UserToken>(model); await _context.AddAsync(userToken); try { await _context.SaveChangesAsync(); } catch (Exception ex) { var exception = ex.Message; throw; } }
public async Task Should_Return_Error_If_ConfirmEmail_UserNotFound() { var model = new UserTokenViewModel { UserId = "3" }; var key = "UserNotFound"; var localizedString = new LocalizedString(key, key); _accountLocalizerMock.Setup(_ => _[key]).Returns(localizedString); var result = await _controller.ConfirmEmail(model); var actionResult = Assert.IsType <BadRequestObjectResult>(result); var actionResultList = actionResult.Value as List <ErrorViewModel>; Assert.Equal(key, actionResultList?[0].Description); }
public async Task Should_Confirm_User() { _context.Users.Add(new ApplicationUser { Email = "*****@*****.**", FirstName = "test", LastName = "Test", CreatedAt = DateTime.UtcNow, SecurityStamp = new Guid().ToString(), EmailConfirmed = false, Id = "2", IsDeleted = false, UserDetail = new UserDetail { AuthorityPercent = 30, LanguagePreference = "tr" } }); _context.SaveChanges(); _userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())) .Callback( (ApplicationUser usr, string token) => { usr.EmailConfirmed = true; _context.SaveChanges(); }) .ReturnsAsync(IdentityResult.Success); var model = new UserTokenViewModel { UserId = "2", Code = new Guid().ToString() }; var result = await _controller.ConfirmEmail(model); var user = _context.Users.FirstOrDefault(x => x.Id == model.UserId); Assert.IsType <OkObjectResult>(result); Assert.NotNull(user); Assert.True(user.EmailConfirmed); }
public ApiResponse Login([FromBody] LoginViewModel login) { if (login == null) { return(new ApiResponse(false, "Objeto de entrada no formato incorreto ou não informado.")); } else if (String.IsNullOrEmpty(login.Email)) { return(new ApiResponse(false, "E-mail não pode ser nulo.")); } else if (String.IsNullOrEmpty(login.Password)) { return(new ApiResponse(false, "Senha não pode ser nula.")); } UserViewModel model = Mapper.Map <UserViewModel>(this._userAppService.GetByLogin(login.Email, login.Password)); if (model != null) { UserTokenViewModel userToken = new UserTokenViewModel(); userToken.Inserted = DateTime.Now; userToken.UserId = model.Id; userToken.Token = ""; string token = this._userTokenAppService.Add(Mapper.Map <UserToken>(userToken)); if (!string.IsNullOrEmpty(token)) { model.Token = token; return(new ApiResponse(true, model)); } else { return(new ApiResponse(false, "Erro ao gravar o token.")); } } else { return(new ApiResponse(false, "E-mail ou senha inválido.")); } }
public async Task <IActionResult> GeneratePasswordResetToken([FromBody] CustomEmailViewModel model) { User user = await UserManager.FindByEmailAsync(model.To); if (user == null) { return(NotFound($"No email ({model.To}) could be found on this platform")); } string body = model.Body; try { string token = await UserManager.GeneratePasswordResetTokenAsync(user); UserTokenViewModel context = Mapper.Map <UserTokenViewModel>(user); context.Token = HttpUtility.UrlEncode(token); body = body.BindTo(context); Logger.LogDebug(body); } catch (Exception ex) { Logger.LogError(ex, "An error occured while formatting input body.\n{0}", body); return(BadRequest("The format of the email body is invalid.")); } bool success = await EmailService. SendEmailAsync(user.Email.ToLower(), model.Subject, body); if (!success) { return(BadRequest("An error occured while sending the password reset email")); } return(Ok()); }
public async Task <IActionResult> DestroyToken([DataSourceRequest] DataSourceRequest request, UserTokenViewModel viewModel) { if (isSysAdmin) { var model = db.UserTokens.First(n => n.LoginProvider == viewModel.LoginProvider && n.Name == viewModel.Name && n.UserId == viewModel.UserId); if (ModelState.IsValid) { db.UserTokens.Remove(model); await db.SaveChangesAsync(); } return(Json(await new[] { viewModel }.ToDataSourceResultAsync(request, ModelState))); } return(Unauthorized()); }
public static UserTokenViewModel WithoutPassword(this UserTokenViewModel user) { user.Password = null; return(user); }
public async Task <LoginResponseViewModel> GetJwt(string email) { var user = await _userManager.FindByEmailAsync(email); var claims = await _userManager.GetClaimsAsync(user); var userRoles = await _userManager.GetRolesAsync(user); claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email)); claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64)); foreach (var userRole in userRoles) { claims.Add(new Claim("role", userRole)); } var identityClaims = new ClaimsIdentity(claims); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var token = tokenHandler.CreateToken(new SecurityTokenDescriptor { Issuer = _appSettings.Issuer, Audience = _appSettings.ValidOn, Subject = identityClaims, Expires = DateTime.UtcNow.AddHours(_appSettings.ExpirationHours), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }); var encodedToken = tokenHandler.WriteToken(token); var userToken = new UserTokenViewModel(user.Id.ToString(), user.Email, claims); if (user.ProfileUser != null) { userToken.Profile = new ProfileViewModel(); userToken.Profile.BirthDate = user.ProfileUser.BirthDate; userToken.Profile.Name = user.ProfileUser.Name; userToken.Profile.LastName = user.ProfileUser.LastName; switch (user.ProfileUser.Type) { case 1: userToken.Profile.Type = TypeProfile.Admin.ToString(); break; case 2: userToken.Profile.Type = TypeProfile.Client.ToString(); break; case 3: userToken.Profile.Type = TypeProfile.Restaurant.ToString(); break; default: throw new Exception("Access denied"); } if (user.ProfileUser.AddressUser != null) { userToken.Address = new AddressViewModel(); userToken.Address.Street = user.ProfileUser.AddressUser.Street; userToken.Address.District = user.ProfileUser.AddressUser.District; userToken.Address.County = user.ProfileUser.AddressUser.County; userToken.Address.City = user.ProfileUser.AddressUser.City; userToken.Address.ZipCode = user.ProfileUser.AddressUser.ZipCode; userToken.Address.Latitude = user.ProfileUser.AddressUser.Latitude; userToken.Address.Longitude = user.ProfileUser.AddressUser.Longitude; } } var response = new LoginResponseViewModel { AccessToken = encodedToken, ExpiresIn = TimeSpan.FromHours(_appSettings.ExpirationHours).TotalSeconds, UserToken = userToken }; return(response); }