Beispiel #1
0
        public async Task <AccessTokenResponse> AuthenticateAsync(LoginViewModel model)
        {
            if (model.Login is null)
            {
                return(null);
            }

            var regex = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");

            var user = regex.IsMatch(model.Login)
                ? await _userManager.FindByEmailAsync(model.Login)
                : await _userManager.FindByNameAsync(model.Login);


            if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
            {
                return(null);
            }

            var session = await _sessionContext.FirstOrDefaultAsync(s =>
                                                                    (s.UserId == user.Id) && (s.Fingerprint == model.Fingerprint)
                                                                    );

            var accessToken = await GenerateAccessWithClaims(user);


            if (session != null)
            {
                _sessionContext.Remove(session);
                await _context.SaveChangesAsync();
            }

            if (model.RememberMe)
            {
                var refreshToken = await _tokenHandler.GenerateRefreshTokenAsync(user);

                _sessionContext.Add(new Session
                {
                    User         = user,
                    RefreshToken = refreshToken,
                    Fingerprint  = model.Fingerprint,
                    CreatedAt    = DateTime.Now,
                    UpdatedAt    = DateTime.Now,
                    ExpiresAt    = DateTime.Now.AddSeconds(_jwtConfig.RefreshExpirationTime)
                });

                if (await _context.SaveChangesAsync() > 0)
                {
                    return(new DefaultResponse(accessToken, refreshToken, _jwtConfig.AccessExpirationTime));
                }
            }
            else
            {
                return(new AccessTokenResponse(accessToken, _jwtConfig.AccessExpirationTime));
            }

            return(null);
        }