Ejemplo n.º 1
0
        public async Task <Result <AuthenticationToken> > GenerateAuthenticationTokenAsync(Entity.User user, string loginProvider, AuthenticationFlow authenticationFlow)
        {
            try
            {
                var accessToken = await GenerateAccessToken(user, authenticationFlow);

                if (accessToken is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not generate access token"));
                }

                var refreshToken = GenerateRefreshToken();

                if (refreshToken is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not generate access token"));
                }

                var refreshTokenExpiration = DateTime.Now.AddDays(Convert.ToDouble(tokenSettings.RefreshTokenExpirationInDays));
                var accessTokenExpiration  = DateTime.Now.AddDays(Convert.ToDouble(tokenSettings.AccessTokenExpirationInDays));

                var token = await repository.AddUserTokenAsync(new UserToken()
                {
                    UserId                 = user.Id,
                    User                   = user,
                    LoginProvider          = loginProvider,
                    AccessToken            = accessToken,
                    RefreshToken           = refreshToken,
                    RefreshTokenExpiration = refreshTokenExpiration,
                    AccessTokenExpiration  = accessTokenExpiration,
                    AuthenticationFlow     = (int)authenticationFlow,
                });

                if (token is null)
                {
                    return(new InvalidResult <AuthenticationToken>("Could not save new authentication token"));
                }

                var result = mapper.Map <UserToken, AuthenticationToken>(token);

                return(new SuccessResult <AuthenticationToken>(result));
            }
            catch (Exception ex)
            {
                return(new UnexpectedResult <AuthenticationToken>(ex.Message));
            }
        }