Пример #1
0
        public async Task <AuthDto> AuthenticateAsync(AuthLoginDto loginInfo)
        {
            var user = await _unitOfWork.UserRepository.FirstOrDefaultAsync(x => x.Username == loginInfo.Username && x.Password == loginInfo.Password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.TokenEncryptionPassword);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var result = new AuthDto();

            result.Token = tokenHandler.WriteToken(token);
            return(result);
        }
Пример #2
0
        public async Task <IActionResult> Login([FromBody] AuthLoginDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ApplicationUser user         = null;
            bool            userNotFound = false;

            try
            {
                user = await userService.GetUserByEmail(dto.Email);
            }
            catch (CurrentEntryNotFoundException)
            {
                userNotFound = true;
            }

            if (userNotFound || !await userService.CheckPassword(user, dto.Password))
            {
                ModelState.AddModelError("loginFailure", "Пароль або пошта не відповідає критеріям");
                return(BadRequest(ModelState));
            }

            if (!(user.ApprovalStatus ?? false))
            {
                ModelState.AddModelError("loginFailure", "Аккаунт не підтвердежний");
                return(BadRequest(ModelState));
            }

            if (user.IsBlocked ?? false)
            {
                ModelState.AddModelError("loginFailure", "Аккаунт заблокований");
                return(BadRequest(ModelState));
            }

            var userClaims = await jwtService.GetClaimsAsync(user);

            var accessToken  = jwtService.GenerateJwtAccessToken(userClaims);
            var refreshToken = jwtService.GenerateJwtRefreshToken();
            await jwtService.LoginByRefreshTokenAsync(user.Id, refreshToken);

            var tokens = new AuthTokensDto
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken,
                ExpireOn     = jwtService.ExpirationTime
            };

            return(Ok(tokens));
        }
Пример #3
0
        public async Task <IActionResult> Login([FromBody] AuthLoginDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ApplicationUser user         = null;
            bool            userNotFound = false;

            try
            {
                user = await userService.GetUserByEmail(dto.Email);
            }
            catch (CurrentEntryNotFoundException)
            {
                userNotFound = true;
            }

            if (userNotFound || !await userService.CheckPassword(user, dto.Password))
            {
                ModelState.AddModelError("loginFailure", "Invalid email or password");
                return(BadRequest(ModelState));
            }

            if (!(user.ApprovalStatus ?? false))
            {
                ModelState.AddModelError("loginFailure", "Not approved yet");
                return(BadRequest(ModelState));
            }

            if (user.IsBlocked ?? false)
            {
                ModelState.AddModelError("loginFailure", "Account has been blocked");
                return(BadRequest(ModelState));
            }

            var userClaims = await jwtService.GetClaimsAsync(user);

            var accessToken  = jwtService.GenerateJwtAccessToken(userClaims);
            var refreshToken = jwtService.GenerateJwtRefreshToken();
            await jwtService.LoginByRefreshTokenAsync(user.Id, refreshToken);

            var tokens = new AuthTokensDto
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken,
                ExpireOn     = jwtService.ExpirationTime
            };

            return(Ok(tokens));
        }
Пример #4
0
        public AuthStatusDto Login(AuthLoginDto payload)
        {
            var entity = accountsRepository.FindByEmail(payload.Email);

            if (entity == null)
            {
                return(AuthenticationFailure("Username or password is wrong"));
            }

            if (!(HashPassword(payload.Password, Convert.FromBase64String(entity.PasswordSalt)) == entity.PasswordHash))
            {
                return(AuthenticationFailure("Username or password is wrong"));
            }

            var token = GenerateJwtToken(entity.Id);

            return(AuthenticationSucceeded("Successfully authenticated", token));
        }
        public IActionResult Login([FromBody] AuthLoginDto payload)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { Status = "Please complete all the fields" }));
            }

            var status = authManager.Login(payload);

            if (status.IsSuccessful)
            {
                return(Ok(status));
            }
            else
            {
                return(Unauthorized(status));
            }
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="demo.httpclient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authLoginDto"></param>
        /// <returns>Task of ApiResponse (AuthUserDto)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <AuthUserDto> > AuthControllerRegisterAsyncWithHttpInfo(AuthLoginDto authLoginDto)
        {
            // verify the required parameter 'authLoginDto' is set
            if (authLoginDto == null)
            {
                throw new ApiException(400, "Missing required parameter 'authLoginDto' when calling AuthApi->AuthControllerRegister");
            }

            var    localVarPath         = "/api/auth/register";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (authLoginDto != null && authLoginDto.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(authLoginDto); // http body (model) parameter
            }
            else
            {
                localVarPostBody = authLoginDto; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("AuthControllerRegister", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <AuthUserDto>(localVarStatusCode,
                                                 localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value), StringComparer.OrdinalIgnoreCase),
                                                 (AuthUserDto)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(AuthUserDto))));
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="demo.httpclient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authLoginDto"></param>
        /// <returns>Task of AuthUserDto</returns>
        public async System.Threading.Tasks.Task <AuthUserDto> AuthControllerRegisterAsync(AuthLoginDto authLoginDto)
        {
            ApiResponse <AuthUserDto> localVarResponse = await AuthControllerRegisterAsyncWithHttpInfo(authLoginDto);

            return(localVarResponse.Data);
        }
Пример #8
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="demo.httpclient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authLoginDto"></param>
        /// <returns>AuthUserDto</returns>
        public AuthUserDto AuthControllerRegister(AuthLoginDto authLoginDto)
        {
            ApiResponse <AuthUserDto> localVarResponse = AuthControllerRegisterWithHttpInfo(authLoginDto);

            return(localVarResponse.Data);
        }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="demo.httpclient.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authLoginDto"></param>
        /// <returns>AuthJwtLoginResponseDto</returns>
        public AuthJwtLoginResponseDto AuthControllerJwtLogin(AuthLoginDto authLoginDto)
        {
            ApiResponse <AuthJwtLoginResponseDto> localVarResponse = AuthControllerJwtLoginWithHttpInfo(authLoginDto);

            return(localVarResponse.Data);
        }