コード例 #1
0
        public async Task <IActionResult> Login([FromBody] LoginFormResource credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.Users.Include(u => u.Role).SingleOrDefaultAsync(u => u.NormalizedEmail == credentials.Email.ToUpper());

            if (!await _userManager.CheckPasswordAsync(user, credentials.Password))
            {
                return(Unauthorized());
            }

            var identity = await GetClaimsIdentity(user);

            if (identity == null)
            {
                return(BadRequest(ModelState));
            }

            var existingRefreshToken = await _refreshTokenRepository.GetByUserId(user.Id);

            if (existingRefreshToken == null)
            {
                var refreshToken = await _refreshTokenRepository.CreateToken(user.Id, "");

                await _unitOfWork.CompleteAsync();

                // TO DO: Create a response class with appropriate constructor
                var response = new
                {
                    token        = await _jwtFactory.GenerateEncodedToken(user.Id, credentials.Email, user.Role.Name),
                    refreshToken = refreshToken,
                    expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                };
                return(Ok(response));
            }
            else
            {
                _refreshTokenRepository.Delete(existingRefreshToken);
                var token = await _refreshTokenRepository.CreateToken(user.Id, "");

                await _unitOfWork.CompleteAsync();

                // TO DO: Create a response class with appropriate constructor
                var response = new
                {
                    token        = await _jwtFactory.GenerateEncodedToken(user.Id, credentials.Email, user.Role.Name),
                    refreshToken = token,
                    expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                };
                return(Ok(response));
            }
        }