Esempio n. 1
0
        public async Task <IActionResult> OnPostLoginUserAsync(LoginUser loginUser)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToPage(new { loginError = "Fill all fields" }));
            }
            User user = new User
            {
                Password = loginUser.Password,
                Username = loginUser.Username,
            };
            string responseString = await _usersApi.AuthentificationToken(user);

            try
            {
                var    handler = new JwtSecurityTokenHandler();
                var    claims  = handler.ReadJwtToken(responseString).Claims;
                string id      = claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier).Value;
                if (!string.IsNullOrEmpty(id))
                {
                    HttpContext.Session.SetString("id", id);
                }
                string username = claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name).Value;
                if (!string.IsNullOrEmpty(username))
                {
                    HttpContext.Session.SetString("username", username);
                }
                string role = claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Role).Value;
                if (!string.IsNullOrEmpty(role))
                {
                    HttpContext.Session.SetString("role", role);
                }
            }
            catch (Exception e)
            {
                if (responseString.Length < 50)
                {
                    var errorResponse = new { loginError = responseString };
                    return(RedirectToPage(errorResponse));
                }
                else
                {
                    throw;
                }
            }
            return(RedirectToPage("Product", new { pageNumber = 1 }));
        }