public async Task <ActionResult <ClientAuthUser> > Login(LoginVM model) { if (model == null || !dbs.Keys.Contains(model.Province)) { return(Unauthorized()); } //check captcha: await HttpContext.Session.LoadAsync(); var captchaCode = HttpContext.Session.GetString(CAPTCHA); HttpContext.Session.Remove(CAPTCHA); if (captchaCode == null || !captchaCode.Equals(model.Captcha, StringComparison.InvariantCultureIgnoreCase)) { return(Unauthorized("کد امنیتی صحیح نمی باشد!")); } var db = dbs[model.Province]; var user = AuthUserX.CheckAuthentication(db, model.Username, model.Password); if (user != null) { var claims = new List <Claim> { new Claim("Id", user.Id.ToString()), new Claim(ClaimTypes.NameIdentifier, model.Username), new Claim(ClaimTypes.Name, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(nameof(Province), model.Province) }; if (user.IsAdmin) { claims.Add(new Claim("IsAdmin", "true")); } if (user.IsSuperAdmin) { claims.Add(new Claim("IsSuperAdmin", "true")); } var perms = new StringBuilder(); foreach (var perm in user.Permissions) { perms.Append(perm).Append(','); } claims.Add(new Claim(nameof(Permission), perms.ToString())); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); var clientUser = Mapper.Map <ClientAuthUser>(user); clientUser.ProvincePrefix = model.Province; return(clientUser); } return(Unauthorized("نام کاربری یا رمز عبور صحیح نمی باشد!")); }
public IActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { AuthUserX user = db.CheckAuthentication(model.Username, model.Password); if (user != null) { List <Claim> claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.GivenName, user.DisplayName) }; StringBuilder permsStr = new StringBuilder(); if (user.IsAdmin) { foreach (string p in Enum.GetNames(typeof(Permission))) { permsStr.Append(p).Append(","); } claims.Add(new Claim("IsAdmin", "true")); } else { foreach (Permission p in user.Permissions) { permsStr.Append(p).Append(","); } } claims.Add(new Claim(nameof(Permission), permsStr.ToString())); ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal principal = new ClaimsPrincipal(identity); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal).Wait(); return(RedirectToLocal(model.ReturnUrl)); } } ModelState.AddModelError("", "نام کاربری یا رمز عبور صحیح نیست!"); return(View(nameof(Login))); }