public AuthenticatedUserModel GenerateJsonWebToken(User user) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( _configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"], claims, expires: DateTime.Now.AddDays(1), signingCredentials: credentials ); var loginResult = new AuthenticatedUserModel() { AccessToken = new JwtSecurityTokenHandler().WriteToken(token), UserName = user.Username }; return(loginResult); }
private async Task <dynamic> GenerateToken(string username, string password) { var model = new UserModel { Username = username, Password = password }; AuthenticatedUserModel AuthenticatedUser = await userData.LoginUser(model); var claims = new List <Claim> { new Claim(ClaimTypes.Name, model.Username), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()), new Claim(ClaimTypes.Role, AuthenticatedUser.RoleName), new Claim(ClaimTypes.NameIdentifier, AuthenticatedUser.Id.ToString()), new Claim("AccessType", AuthenticatedUser.AccessType), new Claim("IsPasswordDefault", AuthenticatedUser.IsPasswordDefault.ToString()) }; var token = new JwtSecurityToken( new JwtHeader( new SigningCredentials( new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])), SecurityAlgorithms.HmacSha256)), new JwtPayload(claims)); var output = new { Access_Token = new JwtSecurityTokenHandler().WriteToken(token), Username = AuthenticatedUser.username }; return(output); }
public IActionResult Renew([FromBody] RenewModel body) { var token = _userService.Renew(body.Token); var authUser = new AuthenticatedUserModel(token); return(Ok(authUser)); }
public async Task <IActionResult> Login(LoginModel model) { try { AuthenticatedUserModel user = null; var result = await _userService.AuthenticateUserAsync(model, AppSettings.UserServiceEndPoint); if (result != null) { await AuthenticationHelper.CreateSessionCookieAsync(HttpContext, result.Token, result.IsAdmin); user = new AuthenticatedUserModel { Token = result.Token, IsAdmin = result.IsAdmin }; return(Ok(user)); } return(Unauthorized()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <Result <AuthenticatedUserModel> > LoginAndGetLayout(LoginFromBody loginFromBody) { var authenticatedUserModel = new AuthenticatedUserModel(); var result = await Login(loginFromBody).OnSuccess(async res => { authenticatedUserModel.Id = res.Id; await GetTeamAsync(res.Id) .OnSuccess(async team => { authenticatedUserModel.Team = new TeamLocalModel() { Id = team.Id, Name = team.Name }; await GetLayoutAsync(team.Layout) .OnSuccess(layout => { authenticatedUserModel.Layout = layout.Diagram; }); }); }); if (result.IsSuccess) { return(Result.Ok(authenticatedUserModel)); } else { return(Result.Fail <AuthenticatedUserModel>(result.Error)); } }
public static bool UserHasAccessToLocation(AuthenticatedUserModel user, string[] roles) { if (user == null) { return(false); } return(true); }
public async Task <IActionResult> LoginLdap([FromBody] LoginModel body) { if (await _emailService.GetCaptchaNotPassed(body.Captcha)) { return(ErrorResponse($"Prvok Re-Captcha je zlý skúste znova.")); } if (body.Email.Contains('@')) { return(ErrorResponse($"Meno nie je správne, použite študentské meno, nie email.")); } _logger.LogInformation($"Request init from ldap."); UserInformations ldapInformations = null; try { ldapInformations = _userService.GetUserFromLDAP(body.Email, body.Password, _logger); } catch (LdapException e) { _logger.LogError($"Exception while logging into ldap: {e}"); return(ErrorResponse(e.ResultCode == 49 ? $"Meno alebo heslo nie je správne, skúste znova prosím." : $"Prepáčte, niečo na serveri nie je v poriadku, skúste neskôr prosím.")); //49 = InvalidCredentials } _logger.LogInformation($"Response received from ldap."); body.Password = _userService.GetDefaultLdapPassword(); if (ldapInformations == null) { _logger.LogInformation($"Invalid ldap login attemp. User {body.Email} doesn't exist."); return(ErrorResponse($"Meno alebo heslo nie je správne, skúste znova prosím.")); } ldapInformations.Email = ldapInformations.Email.ToLower(); User user = await _userService.GetUserByEmailAsync(ldapInformations.Email); if (user == null) { if (!_userService.AddLdapUser(ldapInformations).Result) { _logger.LogInformation($"Invalid ldap login attemp. User with email {body.Email} already exists."); return(ErrorResponse($"Váš študentský email s koncovkou " + ldapInformations.Email.Split('@')[1] + " je už zaregistrovaný.")); } user = await _userService.GetUserByEmailAsync(ldapInformations.Email); _userService.TryAddStudent(user); AuthenticatedUserModel auth = new AuthenticatedUserModel(user, _userService.GenerateJwtToken(ldapInformations.Email)) { FirstTimePN = ldapInformations.PersonalNumber }; return(Ok(auth)); } else { _userService.TryAddStudent(user); AuthenticatedUserModel auth = new AuthenticatedUserModel(user, _userService.GenerateJwtToken(ldapInformations.Email)); return(Ok(auth)); } }
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) { if (HttpContext.User.Identity.IsAuthenticated) { var authenticatedUserModel = AuthenticatedUserModel.GetFromJSON(HttpContext.User.Identity.Name); usuario = usuarioRepository.Get(authenticatedUserModel.ID); ViewBag.Usuario = usuario; } return(base.BeginExecuteCore(callback, state)); }
public async Task <IActionResult> SetNewPassword(Guid token, [FromBody] AuthenticatedUserModel user) { var existingToken = await _context.Accounts.FromSqlInterpolated($"SELECT * FROM accounts WHERE recover_password_token = UNHEX(REPLACE({token}, {"-"}, {""}))").ToListAsync(); if (existingToken.Count > 0) { // token was found, get user id and change their password var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.Id == existingToken[0].UserId); if (existingUser != null) { existingUser.UserPassword = user.UserPassword; _context.Entry(existingUser).State = EntityState.Modified; // invalidate token, now that the password has changed var accountEntry = await _context.Accounts.FirstOrDefaultAsync(a => a.UserId == existingUser.Id); if (accountEntry != null) { accountEntry.RecoverPasswordToken = null; _context.Entry(accountEntry).State = EntityState.Modified; } await _context.SaveChangesAsync(); var origin = Request.Headers["Origin"]; var forgotPasswordLink = $@"{origin}/forgot_password"; var emailBody = $@"Hi {existingUser.UserName}, Your password has been reset @HairdressingProject Admin Portal. If you have not made this request, please contact us or navigate to the page below to reset it again: {forgotPasswordLink} Regards, HairdressingProject Admin. "; try { _emailService.SendEmail(existingUser.UserEmail, existingUser.UserName, "Password successfully reset", emailBody); return(NoContent()); } catch (Exception ex) { Console.WriteLine("Failed to send email:"); Console.WriteLine(ex); return(StatusCode(StatusCodes.Status500InternalServerError, new { errors = new { Email = new string[] { ex.Message } } })); } } return(NotFound(new { errors = new { Token = new string[] { "User not found" } }, status = 404 })); } return(NotFound(new { errors = new { Token = new string[] { "Token not found" } }, status = 404 })); }
public ActionResult Report(string id) { var model = new MedicineReportModel(); model.Complainant = AuthenticatedUserModel.GetUserFromIdentity(); model.ComplainantId = model.Complainant.Id; model.MedicineInfo = model.GetMedicineInfo(id); model.MedicineInfoId = model.MedicineInfo.Id; model.Pharmacies = model.GetAllPharmacies(); return(View(model)); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { IIdentity identity = httpContext.User.Identity; var authenticatedUserModel = AuthenticatedUserModel.GetFromJSON(identity.Name); if (authenticatedUserModel != null && identity.IsAuthenticated) { return(true); } httpContext.Response.Redirect(FormsAuthentication.LoginUrl); return(false); }
public async Task <IActionResult> Login([FromBody] LoginModel body) { try { if (await _emailService.GetCaptchaNotPassed(body.Captcha)) { return(ErrorResponse($"Prvok Re-Captcha je zlý skúste znova.")); } if (!body.Email.Contains('@')) { return(ErrorResponse($"Zlý email.")); } body.Email = body.Email.ToLower(); User user = await _userService.GetUserByEmailAsync(body.Email); if (user == null) { _logger.LogInformation($"Invalid login attemp. User {body.Email} doesn't exist."); return(ErrorResponse($"E-mailová adresa a heslo nie sú správne.")); } if (user.IsLdapUser) { _logger.LogInformation($"User {body.Email} is ldap user no classic."); return(ErrorResponse($"Musite sa prihlásiť cez Ldap prihlásenie, pretože email je študentský.")); } if (!user.EmailConfirmed) { _logger.LogInformation($"Invalid login attemp. User {body.Email} didn't confirm email address."); return(StatusCode((int)HttpStatusCode.Forbidden, "Pre prihlásenie prosím potvrď svoju emailovú adresu.")); } var token = await _userService.Authenticate(body.Email, body.Password); if (token == null) { _logger.LogWarning($"Invalid login attemp. User {body.Email} entered wrong password."); return(ErrorResponse($"E-mailová adresa a heslo nie sú správne.")); } if (user.Email != "*****@*****.**") { _userService.TryAddStudent(user); } token = await _userService.Authenticate(body.Email, body.Password); AuthenticatedUserModel authUser = new AuthenticatedUserModel(user, token); return(Ok(authUser)); } catch (Exception ex) { return(ErrorResponse("Error HERE: " + ex)); } }
public ActionResult Report(MedicineReportModel model) { if (ModelState.IsValid) { var newId = model.Add(); return(RedirectToAction("ReportSuccess")); } model.Complainant = AuthenticatedUserModel.GetUserFromIdentity(); model.MedicineInfo = model.GetMedicineInfo(model.MedicineInfoId); model.Pharmacies = model.GetAllPharmacies(); return(View(model)); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated) { var authenticatedUserModal = AuthenticatedUserModel.GetFromJSON(httpContext.User.Identity.Name); if (authenticatedUserModal.AccessGroups.Any(g => this.GroupName.Any(n => n.ToLowerInvariant() == g.ToLowerInvariant()))) { return(true); } } httpContext.Response.Redirect(FormsAuthentication.LoginUrl); return(false); }
private ActionResult Autenticar(Usuario usuario) { var authenticatedUserModel = new AuthenticatedUserModel() { ID = usuario.ID, Name = usuario.Nome, ExpiresIn = DateTime.Now.AddMinutes(60) }; authenticatedUserModel.AccessGroups.Add(usuario.Tipo.ToString()); FormsAuthentication.SetAuthCookie(authenticatedUserModel.ToJSON(), true); return(RedirectToAction("Index", "Home")); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } if (_userService.Authenticate(model.Email, model.Password)) { AuthenticatedUserModel authenticatedUser = _userService.GetUserDetails(model.Email); CookieManager.SetAuthCookie(model.Email, authenticatedUser, model.RememberMe); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { if (!_userService.IsEmailRegistered(model.Email)) { _userService.Register(model); AuthenticatedUserModel authenticatedUser = _userService.GetUserDetails(model.Email); CookieManager.SetAuthCookie(model.Email, authenticatedUser); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("Email", "Email address is already taken."); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> SignIn([FromBody] AuthenticatedUserModel user) { // Authenticate user var authenticatedUser = await _userService.Authenticate(user.UserNameOrEmail, user.UserPassword); if (authenticatedUser == null) { // User isn't registered return(Unauthorized(new { errors = new { Authentication = new string[] { "Invalid username, email and/or password" } }, status = 401 })); } // Return 200 OK with token in cookie var existingUser = await _context.Users.SingleOrDefaultAsync(u => u.Id == authenticatedUser.Id); var mappedExistingUser = await MapFeaturesToUsers(existingUser); authenticatedUser.BaseUser = mappedExistingUser; _authorizationService.SetAuthCookie(Request, Response, authenticatedUser.Token); return(Ok()); }
public async Task <IActionResult> SignIn([FromBody] AuthenticatedUserModel user) { if (string.IsNullOrWhiteSpace(Request.Headers["Origin"])) { var response = new JsonResponse { Message = "Invalid request", Status = 401, Errors = new Dictionary <string, string[]> { { "Origin", new string[] { "Invalid request origin" } } } }; return(Unauthorized(response.FormatResponse())); } // Authenticate user var authenticatedUser = await _authenticationService.Authenticate(user.UserNameOrEmail, user.UserPassword); if (authenticatedUser == null) { // User isn't registered Response.Headers.Append("Access-Control-Allow-Origin", Request.Headers["Origin"]); return(Unauthorized(new { errors = new { Authentication = new string[] { "Invalid username, email and/or password" } }, status = 401 })); } // Return 200 OK with token in cookie var existingUser = await _context.Users.Where(u => u.Id == authenticatedUser.Id).FirstOrDefaultAsync(); authenticatedUser.BaseUser = existingUser; _authorizationService.SetAuthCookie(Request, Response, authenticatedUser.Token); Response.Headers.Append("X-Authorization-Token", authenticatedUser.Token); return(Ok(authenticatedUser.BaseUser.WithoutPassword())); }
public async Task <IActionResult> Post([FromBody] ExternalAuthenticationModel model) { try { var tuple = await this.externalAuthenticationService.TryAuthenticate(model.SocialNetwork, model.Token, model.Token2); var user = tuple.Item2; var userExisted = tuple.Item1; IList <Claim> claims; var identity = AuthenticationTokenGeneratorJWT.GetIdentity(user, out claims); var configParams = new Dictionary <string, string>(); configParams.Add("secretkey", this.securitySettings.AuthenticationSecretKey); configParams.Add("expirationMinutes", this.securitySettings.ExpirationTokenMinutes.ToString()); configParams.Add("issuer", this.securitySettings.AuthenticationIssuer); configParams.Add("audience", this.securitySettings.AuthenticationAudience); var token = this.authenticationTokenGenerator.GenerateToken(identity, claims, DateTimeOffset.Now, configParams); var userModel = new AuthenticatedUserModel() { Email = user.Email, Name = user.Name, Id = user.Id, Token = token, FacebookId = user.FacebookId, Role = user.Role, Location = user.Location != null?user.Location.ToModel() : null }; return(this.Ok(userModel)); } catch (AdoptersException e) { return(this.BadRequest(e)); } }
public IEnumerable <MedicineReport> GetAllForPharmacy() { return(_medicineReportService.GetAllForPharmacy(AuthenticatedUserModel.GetUserFromIdentity().Id)); }
public Task SignIn(AuthenticatedUserModel user) { throw new NotImplementedException(); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { string authenticationTokenHeaderIndex = "authenticationToken"; string deviceUUIDHeaderIndex = "deviceUUID"; string environmentHeaderIndex = "environment"; bool isAjax = true; if (!isAjax) { } else { string authenticationToken = ""; string deviceUUID = ""; string urlBit = ""; string environment = "MobileApp"; if (HttpContext.Current.Request.HttpMethod == "GET") { environment = "WebApp"; } string declarationsCycleMode = "current"; string feedBackMessage = "Invalid User Access."; bool isValid = true; string usercode = "Unknown"; string username = "******"; try { urlBit = (filterContext.RouteData.Route as System.Web.Routing.Route).Url; if (HttpContext.Current.Request.Headers[authenticationTokenHeaderIndex] != null) { authenticationToken = HttpContext.Current.Request.Headers[authenticationTokenHeaderIndex].ToString(); } if (HttpContext.Current.Request.Headers[deviceUUIDHeaderIndex] != null) { deviceUUID = HttpContext.Current.Request.Headers[deviceUUIDHeaderIndex].ToString(); } if (HttpContext.Current.Request.Headers[environmentHeaderIndex] != null) { environment = HttpContext.Current.Request.Headers[environmentHeaderIndex].ToString(); } if ((authenticationToken.Trim() == "" || deviceUUID.Trim() == "") && (environment == "MobileApp")) { isValid = false; feedBackMessage = "Invalid User Access."; } if (isValid) { AuthenticatedUserModel user = null; if (user == null) { isValid = true; } else { var prmList = filterContext.ActionParameters; foreach (var prm in prmList) { var prmObj = prm.Value as GenericRequestModel; if (prmObj != null) { usercode = user.LoginUserName; username = user.FullName; prmObj.SessionUserName = user.FullName; prmObj.SessionUserId = user.UserId; prmObj.DeviceIdentifier = deviceUUID; prmObj.RootWebFolder = HttpContext.Current.Server.MapPath("~"); prmObj.RootAPIURL = HttpContext.Current.Request.Url.AbsoluteUri.Replace( HttpContext.Current.Request.RawUrl, ""); if (!prmObj.RootAPIURL.EndsWith("/")) { prmObj.RootAPIURL += "/"; } if (prmObj.RootAPIURL.Contains("localhost")) { } else if (prmObj.RootAPIURL.Contains("testza")) { } else { prmObj.RootAPIURL += "api"; } prmObj.Environment = environment; } } if (IsOpenMethod) { isValid = IsOpenMethod; } else { isValid = SystemUserLogic.UserHasAccessToLocation(user, Roles); } } } } catch (Exception error) { isValid = false; feedBackMessage = error.ToString(); } if (!isValid) { GenericResultModel result = new GenericResultModel() { HasError = true, Feedback = feedBackMessage, IsValidationError = false, IsAuthenticationError = true, FullName = username, WindowsUser = usercode }; filterContext.Result = new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { base.OnActionExecuting(filterContext); } } }
public string Add() { this.ImageUrl = CustomFile.SaveImageFile(this.ImageFileBase, this.Name, this.Id, "Medicine"); this.ContributorId = AuthenticatedUserModel.GetUserFromIdentity().Id; return(_medicineService.AddByAdmin(this)); }
public IEnumerable <ReportFeedback> GetAllFeedbackForPharmacy() { return(_medicineReportService.GetAllFeedback().Where(x => x.MedicineReport.PharmacyId == AuthenticatedUserModel.GetUserFromIdentity().Id)); }
//public IEnumerable<ReportFeedback> GetAllFeedbackForNormalUser() //{ // return _medicineReportService.GetAllFeedback().Where(x => x.MedicineReport.ComplainantId == AuthenticatedUserModel.GetUserFromIdentity().Id); //} public IEnumerable <MedicineReport> GetAllPendingForCompany() { return(_medicineReportService.GetAllPendingForCompany(AuthenticatedUserModel.GetUserFromIdentity().Id)); }