public ServiceResult <string> FirstStepLogin(UserAuthenticationBindingModel model) { return(new ServiceResult <string>(StatusCode.Ok) { Data = "MockData" }); }
public bool HasLogin(HttpSession session, UserAuthenticationBindingModel userBindingModel) { if (session == null || userBindingModel == null || !userBindingModel.IsValid()) { return(false); } User currentUser = this.userRepository .Get(u => u.Email == userBindingModel.Email) .FirstOrDefault(); if (currentUser != null) { Login login = new Login { IsActive = true, SessionId = session.Id, UserId = currentUser.Id }; this.loginRepository.Insert(login); this.unitOfWork.Save(); return(true); } return(false); }
protected async Task RegisterAsync() { this._logger?.LogInformation("'{0}' Method execution started", nameof(this.RegisterAsync)); await this._jsRuntime.InvokeAsync <object>("homeController.ShowLoadingIndicator"); try { var response = new SingleResponse <dynamic>(); string jsonModel = string.Empty; try { response = await this._authenticationDataService.RegisterAsync(this.RegisterUserBindingModel); jsonModel = JsonConvert.SerializeObject(response.Model); } catch (HttpRequestException ex) { this._logger?.LogInformation(response.Message); await this._jsRuntime.InvokeAsync <object>("homeController.HideLoadingIndicator"); await this._jsRuntime.InvokeAsync <object>("homeController.showWarningMessagePopUp", response.ErrorMessage); } if (response.DidValidationError) { Dictionary <string, string> validationErrors = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonModel); foreach (var item in validationErrors) { if (item.Key == "UserName") { UserNameValidatationMessage = item.Value; } } } else if (response.DidError) { } else { UserAuthenticationBindingModel userAuthentication = new UserAuthenticationBindingModel(); userAuthentication = JsonConvert.DeserializeObject <UserAuthenticationBindingModel>(jsonModel); await this._appState.SaveJwtTokenAsync(userAuthentication); await this._jsRuntime .InvokeAsync <object> ("registerController.onUserRegistrationSuccess", userAuthentication.UserName, "/"); } await this._jsRuntime.InvokeAsync <object>("homeController.HideLoadingIndicator"); this._logger?.LogInformation("'{0}' Method execution completed successfully", nameof(this.RegisterAsync)); } catch (Exception ex) { this._logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(this.RegisterAsync), ex); } }
[ProducesResponseType(500)] //If there was an internal server error public async Task <IActionResult> AuthenticateUserAsync([FromBody] UserLoginBindingModel userLoginBindingModel) { var response = new SingleResponse <dynamic>(); var user = this._mapper.Map <User>(userLoginBindingModel); var userAuthenticationDetails = await this._authenticationService.AuthenticateUserAsync(user); var userAuthentication = userAuthenticationDetails.Item2; var userDetails = userAuthenticationDetails.Item1; UserAuthenticationBindingModel userAuthenticationBindingModel = new UserAuthenticationBindingModel(); userAuthenticationBindingModel = this._mapper.Map <UserAuthenticationBindingModel>(userAuthentication); userAuthenticationBindingModel.UserName = userLoginBindingModel.UserName; if (userAuthenticationBindingModel.IsUserAuthenticated) { response.Message = "User " + userAuthentication.UserName + " authenticated successfully. Redirecting to Home screen."; this.CreateJWTToken(response, userAuthenticationBindingModel); } else { response.Model = userAuthenticationBindingModel; response.DidValidationError = true; response.Message = "User Name or Password is Incorrect. Please try again"; } return(response.ToHttpResponse()); }
private void CreateJWTToken(dynamic response, UserAuthenticationBindingModel userAuthentication) { userAuthentication.ExpiresOn = DateTime.Now.AddDays(1); userAuthentication.LoggedOn = DateTime.Now; userAuthentication.IsUserAuthenticated = true; userAuthentication.IsUserAccountFound = true; var token = new JwtSecurityToken( issuer: GlobalAppConfigurations.Instance.GetValue("ValidIssuer").ToString(), audience: GlobalAppConfigurations.Instance.GetValue("ValidAudience").ToString(), claims: new[] { // You can add more claims if you want new Claim(JwtRegisteredClaimNames.Sub, userAuthentication.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.Role, CoreWebApiRoles.Admin) }, expires: userAuthentication.ExpiresOn, notBefore: userAuthentication.LoggedOn, signingCredentials: this._jwtAuthentication.Value.SigningCredentials); userAuthentication.Token = new JwtSecurityTokenHandler().WriteToken(token); response.Model = userAuthentication; }
[ProducesResponseType(500)] //If there was an internal server error public async Task <IActionResult> RegisterUserAsync([FromBody] UserBindingModel userBindingModel) { var errors = new Dictionary <string, string>(); var response = new SingleCreatedResponse <dynamic>(); User user = await this._authenticationService.GetUserDetailsByUserNameAsync(userBindingModel.UserName); if (user != null) { errors.Add("UserName", "User Name " + userBindingModel.UserName + " already exists"); response.ErrorMessage = "Validation error occured"; response.DidValidationError = true; response.Model = errors; return(response.ToHttpResponse()); } user = this._mapper.Map <User>(userBindingModel); var userCreationSuccess = await this._authenticationService.RegisterUserAsync(user); if (userCreationSuccess > 0) { UserAuthenticationBindingModel userAuthentication = new UserAuthenticationBindingModel(); userAuthentication.UserName = userBindingModel.UserName; response.Message = "User " + userAuthentication.UserName + " created successfully. Redirecting to Home screen."; this.CreateJWTToken(response, userAuthentication); } return(response.ToHttpResponse()); }
public async Task SaveJwtTokenAsync(UserAuthenticationBindingModel userAuthentication) { this._localStorage .SetItem("AuthenticationToken", userAuthentication.Token); this._localStorage .SetItem("ExpiresOn", userAuthentication.ExpiresOn); this._localStorage .SetItem("LoggedOn", userAuthentication.LoggedOn); this._localStorage .SetItem("UserName", userAuthentication.UserName); }
public ServiceResult <string> FirstStepLogin(UserAuthenticationBindingModel model) { var User = _userRepository.GetMany(P => P.Username == model.Username && P.Password == model.Password).FirstOrDefault(); if (User == null) { return(new ServiceResult <string>(StatusCode.NotFound, new IncorrectUsernameOrPasswordMessage())); } var token = _jsonWebTokenEngine.GenerateToken(User.Id, User.Username, null, string.Empty, string.Empty); return(new ServiceResult <string>(token)); }
public ServiceResult <string> FirstStepLogin(UserAuthenticationBindingModel model) { IRestRequest LoginRequest = new RestRequest("api/Authentication", method: Method.POST); LoginRequest.AddJsonBody(model); IRestResponse <ServiceResult <string> > Result = RestProvider.GetInstance().Post <ServiceResult <string> >(LoginRequest); if (Result != null) { RestProvider.Renew().AddDefaultHeader("Authorization", Result.Data.Data); return(Result.Data); } throw new Exception(); }
public void Login(HttpSession session, HttpResponse response, UserAuthenticationBindingModel userBindingModel) { if (this.securityService.IsAuthenticated(session)) { this.Redirect(response, "/home/index"); return; } if (!this.securityService.HasLogin(session, userBindingModel)) { this.Redirect(response, "/user/login"); return; } this.Redirect(response, "/home/index"); }
public async Task <IActionResult> Login(UserLoginBindingModel userLoginBindingModel) { if (!ModelState.IsValid) { return(await Task.Run(() => this.View(userLoginBindingModel))); } dynamic ajaxReturn = new JObject(); var user = this._mapper.Map <User>(userLoginBindingModel); var userAuthenticationDetails = await this._authenticationService.ValidateAndAuthenticateUserAsync(user); User userDetails = new User(); List <UserRole> userRoles = new List <UserRole>(); UserAuthentication userAuthentication = new UserAuthentication(); userDetails = userAuthenticationDetails.user; userRoles = userAuthenticationDetails.userRoles; userAuthentication = userAuthenticationDetails.authenticationDetails; UserAuthenticationBindingModel userAuthenticationBindingModel = new UserAuthenticationBindingModel(); userAuthenticationBindingModel = this._mapper.Map <UserAuthenticationBindingModel>(userAuthentication); userAuthenticationBindingModel.UserName = userLoginBindingModel.UserName; if (userAuthenticationBindingModel.IsUserAuthenticated) { var identity = (ClaimsIdentity)HttpContext.User.Identity; List <Claim> claims = new List <Claim> { new Claim("http://example.org/claims/UserName", userDetails.UserName), new Claim(ClaimTypes.Name, user.UserName), new Claim("http://example.org/claims/UserId", userDetails.UserId.ToString()), new Claim(ClaimTypes.NameIdentifier, userDetails.UserId.ToString()), new Claim(ClaimTypes.Authentication, "Authenticated"), new Claim("http://example.org/claims/LoggedInTime", "LoggedInTime", DateTime.Now.ToString()) }; foreach (var item in userRoles) { claims.Add(new Claim(ClaimTypes.Role, item.RoleName)); } var identityClaims = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); // create principal ClaimsPrincipal principal = new ClaimsPrincipal(identityClaims); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); ajaxReturn.Status = "Success"; ajaxReturn.GetGoodJobVerb = "Congratulations"; ajaxReturn.Message = userLoginBindingModel.UserName + " - user authenticated successfully." + " "; } else { ajaxReturn.Status = "Warning"; ajaxReturn.GetGoodJobVerb = "Opps"; ajaxReturn.Message = "User Name or Password is incorrect. Please try again." + " "; } return(this.Json(ajaxReturn)); }
public ServiceResult <string> Post(UserAuthenticationBindingModel request) { return(_authenticationCommand.FirstStepLogin(request)); }