public async Task <IActionResult> Login([FromBody]  LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _usersService.FindUserAsync(login.username, login.password);

            if (user == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure",
                                                              "Username or password is incorrect.", ModelState)));
            }

            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial,
                                                       result.AccessToken, null);

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);

            return(Ok(new
            {
                access_token = result.AccessToken,
                refresh_token = result.RefreshToken
            }));
        }
示例#2
0
        public async Task <LoginResponse> LoginAsync(LoginRequest request)
        {
            var response     = new LoginResponse();
            var passwordHash = _securityService.GetSha256Hash(request.Password);
            var user         = await _users
                               .Include(d => d.Group)
                               .ThenInclude(d => d.GroupRoles)
                               .ThenInclude(d => d.Role)
                               .FirstOrDefaultAsync(x => x.UserName == request.UserName && x.PasswordHash == passwordHash);

            if (user == null)
            {
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.InvalidUserNameOrPasswordForLogin.Value(), AuthenticationMessageHelper.ResponseMessages));
            }

            switch (user.UserStatus)
            {
            case UserStatus.Fired:
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.LoginFailedYouAreFired.Value(), AuthenticationMessageHelper.ResponseMessages));

            case UserStatus.Inactive:
                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.LoginFailedYouAreInactive.Value(), AuthenticationMessageHelper.ResponseMessages));

            case UserStatus.WaitingConfirmationEmail:
                var token = await SendAndGetVerificationEmailTokenAsync(user);
                await SetEmailTokenAsync(user.Id, token);

                await _unitOfWork.SaveChangesAsync();

                return(response.ReturnWithCode(AuthenticationMessageHelper.Code.LoginFailedYouAreWaitingVerificationEmail.Value(), AuthenticationMessageHelper.ResponseMessages));
            }

            user.LastLoginDateTimeOn = DateTimeOffset.UtcNow.IranStandardTimeNow();
            user.CleanEmailToken();
            var result = await _userTokenFactoryService.CreateJwtTokensAsync(user);

            await _userTokenStorageService.AddUserTokenStorageAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _unitOfWork.SaveChangesAsync();

            _antiForgeryCookieService.RegenerateAntiForgeryCookies(result.Claims);
            response.access_token  = result.AccessToken;
            response.refresh_token = result.RefreshToken;
            response.UserId        = user.Id;
            response.FullName      = user.FullName;
            response.UserName      = user.UserName;
            return(response.ReturnWithCode(AuthenticationMessageHelper.Code.LoginSuccess.Value(), AuthenticationMessageHelper.ResponseMessages));
        }
        public async Task <SignInResult> SignInAsync(string userName, string password)
        {
            var userMaybe = await _userManager.FindByNameAsync(userName);

            if (!userMaybe.HasValue)
            {
                return(SignInResult.Failed(_localizer["SignIn.Messages.Failure"]));
            }

            var user = userMaybe.Value;

            if (!_userManager.VerifyHashedPassword(user.PasswordHash, password))
            {
                return(SignInResult.Failed(_localizer["SignIn.Messages.Failure"]));
            }

            if (!user.IsActive)
            {
                return(SignInResult.Failed(_localizer["SignIn.Messages.IsNotActive"]));
            }

            var userId = user.Id;

            var claims = await GenerateClaimsAsync(userId);

            var token = await _tokenManager.BuildTokenAsync(userId, claims);

            _antiForgery.RegenerateAntiForgeryCookies(claims);

            return(SignInResult.Success(token));
        }
示例#4
0
        public async Task <IActionResult> Login([FromBody] CredentialsViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await GetUserIdentity(credentials.Email, credentials.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var(accessToken, refreshToken, claims) = await _tokenStoreService.CreateJwtTokens(user, refreshTokenSource : null);

            _antiForgery.RegenerateAntiForgeryCookies(claims);

            return(Ok(new { access_token = accessToken, refresh_token = refreshToken }));
        }
示例#5
0
        public async Task <JwtTokensData> CreateJwtTokens(User user)
        {
            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);
            return(result);
        }
示例#6
0
        public async Task <IActionResult> Login([FromBody]  User loginUser)
        {
            if (loginUser == null)
            {
                return(BadRequest("user is not set."));
            }

            var user = await _usersService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user == null || !user.IsActive)
            {
                return(Unauthorized());
            }

            var(accessToken, refreshToken, claims) = await _tokenStoreService.CreateJwtTokens(user, refreshTokenSource : null);

            _antiforgery.RegenerateAntiForgeryCookies(claims);

            return(Ok(new { access_token = accessToken, refresh_token = refreshToken }));
        }
示例#7
0
        public async Task <IActionResult> CreateToken([FromForm] User loginUser)
        {
            if (loginUser == null)
            {
                return(BadRequest("user is not set !!"));
            }

            var user = await _userService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user?.IsActive != null && ((bool)!user?.IsActive))
            {
                return(Unauthorized());
            }

            var(accessToken, refreshToken, claims) = await _tokenService.CreateJwtToken(user, refreshTokenSource : null);

            _antiForgeryCookieService.RegenerateAntiForgeryCookies(claims);

            return(Ok(new { access_token = accessToken, refresh_token = refreshToken }));
        }
        public async Task <IActionResult> Login([FromBody] User loginUser)
        {
            if (loginUser == null)
            {
                return(Ok(new { success = false, message = LoggingEvents.LOGIN_FAILED_MESSAGE }));
            }

            var user = await _userService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user == null || !user.IsActive)
            {
                return(Ok(new { success = false, message = LoggingEvents.LOGIN_FAILED_MESSAGE }));
            }

            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);

            return(Ok(new { access_token = result.AccessToken, refresh_token = result.RefreshToken, success = true }));
        }
示例#9
0
        public async Task <IActionResult> Login(UserLoginDto loginUser)
        {
            if (loginUser == null)
            {
                return(BadRequest("user is not set."));
            }

            var user = await _usersService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user == null || !user.IsActive)
            {
                return(Unauthorized());
            }

            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);
            return(Ok(new { access_token = result.AccessToken, refresh_token = result.RefreshToken }));
        }
        public async Task <ActionResult <ClientToken> > LoginAsync([FromBody] LoginViewModel loginUser)
        {
            LoginViewModelValidator loginViewModelValidator = new LoginViewModelValidator();
            var results = loginViewModelValidator.Validate(loginUser);

            if (!results.IsValid)
            {
                foreach (var failure in results.Errors)
                {
                    _logger.LogInformation("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
                }
            }

            if (loginUser == null || !ModelState.IsValid || !results.IsValid)
            {
                return(BadRequest("user is not set."));
            }

            var user = await _usersService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user == null || !user.IsActive)
            {
                return(Unauthorized());
            }

            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);

            return(Ok(new ClientToken {
                AccessToken = result.AccessToken, RefreshToken = result.RefreshToken
            }));
        }
示例#11
0
        public async Task <IActionResult> Login([FromBody]  LoginModel loginUser)
        {
            if (loginUser == null)
            {
                return(BadRequest("user is not set."));
            }
            var user = await _usersService.FindUserAsync(loginUser.Username, loginUser.Password);

            if (user?.F_IsActive != true)
            {
                return(Content(new AjaxResult
                {
                    state = ResultType.error.ToString(),
                    message = "登录失败!"
                }.ToJson()));
            }

            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);

            //return Ok(new { access_token = result.AccessToken, refresh_token = result.RefreshToken });
            return(Content(new AjaxResult
            {
                state = ResultType.success.ToString(),
                message = "登录成功。",
                data = new
                {
                    access_token = result.AccessToken,
                    refresh_token = result.RefreshToken
                }
            }.ToJson()));
        }
示例#12
0
        public async Task Login_In_Service()
        {
            var user = await _usersService.FindUserAsync(_rightUser.Username, _rightUser.Password);

            Assert.NotNull(user);
            Assert.True(user.IsActive);
            var result = await _tokenFactoryService.CreateJwtTokensAsync(user);

            await _tokenStoreService.AddUserTokenAsync(user, result.RefreshTokenSerial, result.AccessToken, null);

            await _uow.SaveChangesAsync();

            Assert.NotNull(result);
            result.AccessToken.Should().NotBeEmpty();
            result.Claims.Should().NotBeEmpty();
            result.RefreshToken.Should().NotBeEmpty();
            result.RefreshTokenSerial.Should().NotBeEmpty();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);
        }
        public async Task <IActionResult> Get(string t = "")
        {
            // _logger.LogError("Error Log");
            // throw new Exception("error");
            //await userService.RegisterTestUser();
            string xsrfToken   = "";
            string accessToken = "";

            if (User.Identity.IsAuthenticated)
            {
                var appUser = await userService.FindById(User.Identity.Name);

                var roles = await userService.GetUserRoles(appUser);

                var token = await _tokenService.createAccessTokenAsync(appUser, roles.ToList());

                accessToken = token.AccessToken;
                xsrfToken   = _antiforgery.RegenerateAntiForgeryCookies(new ClaimsPrincipal(new ClaimsIdentity(token.claims, JwtBearerDefaults.AuthenticationScheme)));
            }
            return(Json(new { Config = _apiSettingsConfig.Value, Xsrftoken = xsrfToken, AccessToken = accessToken }));
        }
示例#14
0
        public IActionResult Login([FromQuery] string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(BadRequest(new { messageCode = -100, message = "Dữ Liệu Sai" }));
            }
            var userResult = _lesterRegistration.Login(userName, password);

            if (userResult.MessageCode == MessgeCodeRegistration.PasswordWrong)
            {
                return(Unauthorized(new { messageCode = MessgeCodeRegistration.PasswordWrong, message = CommonHelper.DescriptionEnum(MessgeCodeRegistration.PasswordWrong) }));
            }
            if (userResult.MessageCode != MessgeCodeRegistration.Suscess)
            {
                return(Unauthorized(new { messageCode = userResult.MessageCode, message = CommonHelper.DescriptionEnum((MessgeCodeRegistration)userResult.MessageCode) }));
            }
            var result = _tokenFactoryService.CreateJwtTokensAsync(userResult.User);

            _tokenStoreService.AddUserToken(userResult.User, result.RefreshTokenSerial, result.AccessToken, null);
            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);
            AccessControl.User = userResult.User;
            return(Ok(new { access_token = result.AccessToken, refresh_token = result.RefreshToken }));
        }
示例#15
0
        public async Task <IActionResult> login([FromBody] LoginModel user)
        {
            try
            {
                await _userService.Logout();

                _antiforgery.DeleteAntiForgeryCookies();

                var result = await _userService.Authenticate(user.Username, user.Password, user.RememberMe);

                if (result.Succeeded)
                {
                    var appUser = await _userService.FindById(user.Username);

                    var roles = await _userService.GetUserRoles(appUser);

                    var token = await _tokenService.createAccessTokenAsync(appUser, roles.ToList());

                    var Menus = (await _userService.GetMenus(appUser)).ToList();
                    if (!Menus.Any())
                    {
                        Menus.Add(new Model.DbSets.Menu.Menu()
                        {
                            Id        = 1,
                            Name      = "خانه",
                            Route     = "",
                            IsVisible = true
                        });
                    }

                    string xsrfToken = _antiforgery.RegenerateAntiForgeryCookies(new ClaimsPrincipal(new ClaimsIdentity(token.claims, JwtBearerDefaults.AuthenticationScheme)));
                    return(Json(
                               new HttpResult()
                    {
                        Success = true,
                        Message = "",
                        Data = new UserViewMolel()
                        {
                            Menus = Menus,
                            Email = appUser.Email,
                            Roles = roles.ToList(),
                            ImageLink = appUser.ImageLink,
                            OrgId = appUser.OrgId,
                            XsrfToken = xsrfToken,
                            UserId = appUser.Id,
                            NationalCode = appUser.NationalCode,
                            Firstname = appUser.Firstname,
                            LastName = appUser.LastName,
                            UserName = appUser.UserName,
                            PhoneNumber = appUser.PhoneNumber,
                            Access_token = token.AccessToken     //GenerateJwtToken(user.username, appUser,claims.Claims.ToList())
                        }
                    }));
                }
                else if (result.IsLockedOut)
                {
                    return(Json(new HttpResult()
                    {
                        Success = false,
                        Message = "کاربری شما قفل شده"
                    }));
                }
                else
                {
                    return(Json(new HttpResult()
                    {
                        Success = false,
                        Message = "نام کاربری یا رمز عبور اشتباه است"
                    }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new HttpResult()
                {
                    Success = false,
                    Message = "مشکلی در انجام عملیات وجود دارد"
                }));
            }
        }