示例#1
0
        public async Task <IActionResult> SignInAsync(UserLogin user, string returnUrl = "")
        {
            if (ModelState.IsValid)
            {
                using (var db = await _db.OpenAsync())
                {
                    var q = await db.SingleAsync <User>(x => x.Username == user.Username.Trim());

                    if (q == null || !BCrypt.Net.BCrypt.Verify(user.Password, q.PasswordHash))
                    {
                        ModelState.AddModelError("", "User not found!");
                        return(View());
                    }
                    else
                    {
                        var Claims = new Claim[2];
                        Claims[0] = new Claim(ClaimTypes.Name, user.Username);
                        Claims[1] = new Claim(ClaimTypes.NameIdentifier, q.Id.ToString());

                        var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                        Identity.AddClaims(Claims.AsList());

                        var principal = new ClaimsPrincipal(Identity);
                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                        if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                }
            }
            return(View());
        }