Exemple #1
0
        public async Task <ActionResult <ApiUser> > Login(
            string email,
            string password)
        {
            var user = await _userManager.FindByEmailAsync(email);

            if (user is null)
            {
                return(NotFound($"Could not find user with email {email}!"));
            }

            var result = await _signInManager.PasswordSignInAsync(
                user,
                password,
                true,
                true);

            if (!result.Succeeded)
            {
                return(Unauthorized("Invalid email or password!"));
            }

            var roles = await _userManager.GetRolesAsync(user);

            var userRoles = new List <ApiRole>();

            foreach (var r in roles)
            {
                userRoles.Add(new ApiRole
                {
                    RoleName = r
                });
            }

            var apiUser = new ApiUser
            {
                Id       = user.Id,
                Email    = user.Email,
                Fullname = user.Fullname,
                Phone    = user.PhoneNumber,
                Username = user.UserName,
                Roles    = userRoles,
                Token    = string.Empty
            };
            var token = _jwtGenerator.Generator(apiUser);

            apiUser.Token = token;
            return(apiUser);
        }