Ejemplo n.º 1
0
        public async Task <ActionResult <AuthenticatedUserDTO> > LoginAsync([FromBody] LoginDTO dto)
        {
            var user = await _appUsers.LoginAsync(dto.UserName, dto.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var loggedInUserDTO = new AuthenticatedUserDTO();

            loggedInUserDTO.User = Mappers.GetAppUserDTO(user);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email)
            };

            foreach (var role in user.GetRoles())
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            if (!string.IsNullOrEmpty(user.FirstName))
            {
                claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
            }

            if (!string.IsNullOrEmpty(user.LastName))
            {
                claims.Add(new Claim(ClaimTypes.Surname, user.LastName));
            }

            loggedInUserDTO.Token = BuildToken(claims);

            return(Ok(loggedInUserDTO));
        }