Esempio n. 1
0
        public async Task <IActionResult> Login(LoginViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _userService.FindUserByCredentialsAsync(loginViewModel.Username, loginViewModel.Password);

                if (user != null)
                {
                    int sessionId = await _userSessionService.AddSession(user.Username);

                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, user.Username),
                        new Claim(ClaimTypes.Sid, sessionId.ToString()),
                        new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
                    };
                    ClaimsIdentity  userIdentity = new ClaimsIdentity(claims, "login");
                    ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(principal);

                    return(Redirect("/"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password");
                    return(View(loginViewModel));
                }
            }

            return(View());
        }