public async Task <ActionResult <AuthToken> > AuthenticateUserAsync(UserValidateDto userValidateDto)
        {
            if (ModelState.IsValid)
            {
                var user = await _userService.ValidateUserAsync(userValidateDto);

                if (user != null)
                {
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);

                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject = new ClaimsIdentity(new Claim[]
                        {
                            new Claim(ClaimTypes.Name, user.UserId.ToString())
                        }),
                        Expires            = DateTime.UtcNow.AddDays(7),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };

                    var token       = tokenHandler.CreateToken(tokenDescriptor);
                    var tokenString = tokenHandler.WriteToken(token);

                    var userTokenDto = new AuthToken
                    {
                        AccessToken = tokenString
                    };
                    return(userTokenDto);
                }
                return(BadRequest(new { message = "Your email address or password is incorrect." }));
            }
            return(BadRequest());
        }
        public async Task ValidateUser(UserValidateDto model)
        {
            var user = (await _context.Users.FirstOrDefaultAsync(u => u.Id == model.Id));

            user.IsValidated = model.Validated;
            _context.Update(user);
            await Save();
        }
Example #3
0
        public static string CreateRefreshToken(JWTConfig jwtConfig, UserValidateDto user)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Account),
            };

            return(CreateToken(jwtConfig, claims, TokenType.RefreshToken));
        }
        public async Task <User> ValidateUserAsync(UserValidateDto userValidateDto)
        {
            var user = await _userRepository.GetUserByEmailAddressAsync(userValidateDto.EmailAddress);

            if (user != null && HashUtilities.VerifyHash(userValidateDto.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(user);
            }
            return(null);
        }
        public async Task ValidateUserAsync_WithUserValidateDto_ReturnsNull_IfPasswordDoesNotMatch()
        {
            var userValidateDto = new UserValidateDto
            {
                EmailAddress = _userEmailAddress,
                Password     = "******"
            };

            var user = await _userService.ValidateUserAsync(userValidateDto);

            Assert.Null(user);
        }
        public async Task ValidateUserAsync_WithUserValidateDto_ReturnsNull_IfEmailAddressDoesNotMatch()
        {
            var userValidateDto = new UserValidateDto
            {
                EmailAddress = "*****@*****.**",
                Password     = _userPassword
            };

            var user = await _userService.ValidateUserAsync(userValidateDto);

            Assert.Null(user);
        }
Example #7
0
        public static string CreateAccessToken(JWTConfig jwtConfig, UserValidateDto user)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Account),
                new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Name),
                //new Claim(ClaimTypes.Role, user.RoleIds??"0")
                //new Claim(JwtRegisteredClaimNames.Email, user.Email),
            };

            return(CreateToken(jwtConfig, claims, TokenType.AccessToken));
        }
Example #8
0
        public async Task <IActionResult> Validate([FromBody] UserValidateDto model)
        {
            var user = await _userManager.FindByIdAsync(model.Id.ToString());

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

            await _userService.ValidateUser(model);

            return(Ok());
        }
Example #9
0
        public static string CreateAccessToken(JWTConfig jwtConfig, UserValidateDto user, string refreshTokenTxt)
        {
            var token = new JwtSecurityTokenHandler().ReadJwtToken(refreshTokenTxt);

            if (token != null)
            {
                var claimAccount = token.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;

                if (user != null && user.Account == claimAccount)
                {
                    return(CreateAccessToken(jwtConfig, user));
                }
            }
            return(string.Empty);
        }
        public async Task ValidateUserAsync_WithUserValidateDto_CallsRepoGetUserByEmailAddressAsyncAndReturnsMatchingUser()
        {
            var userValidateDto = new UserValidateDto
            {
                EmailAddress = _userEmailAddress,
                Password     = _userPassword
            };

            var user = await _userService.ValidateUserAsync(userValidateDto);

            var hashVerification = user != null && HashUtilities.VerifyHash(_userPassword, user.PasswordHash, user.PasswordSalt);

            _userRepositoryMock.Verify(repo => repo.GetUserByEmailAddressAsync(userValidateDto.EmailAddress), Times.Once);
            user.EmailAddress.Should().Be(_userEmailAddress);
            Assert.True(hashVerification);
        }
Example #11
0
        public async Task <AppSrvResult <UserValidateDto> > LoginAsync(UserLoginDto input)
        {
            var bloomFilterAccount = _bloomFilterFactory.GetBloomFilter(nameof(BloomFilterAccount));
            var exists             = await bloomFilterAccount.ExistsAsync(input.Account.ToLower());

            if (!exists)
            {
                return(Problem(HttpStatusCode.BadRequest, "用户名或密码错误"));
            }

            var user = await _userRepository.FetchAsync(x => new
            {
                x.Id,
                x.Account,
                x.Password,
                x.Salt,
                x.Status,
                x.Email,
                x.Name,
                x.RoleIds
            }, x => x.Account == input.Account);

            if (user == null)
            {
                return(Problem(HttpStatusCode.BadRequest, "用户名或密码错误"));
            }

            var httpContext   = HttpContextUtility.GetCurrentHttpContext();
            var channelWriter = ChannelHelper <LoginLog> .Instance.Writer;
            var log           = new LoginLog
            {
                Account         = input.Account,
                Succeed         = false,
                UserId          = user.Id,
                UserName        = user.Name,
                CreateTime      = DateTime.Now,
                Device          = httpContext.Request.Headers["device"].FirstOrDefault() ?? "web",
                RemoteIpAddress = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
            };

            if (user.Status != 1)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            //var logins = await _loginLogRepository.SelectAsync(5, x => new { x.Id, x.Succeed,x.CreateTime }, x => x.UserId == user.Id, x => x.Id, false);
            //var failLoginCount = logins.Count(x => x.Succeed == false);
            var failLoginCount = 2;

            if (failLoginCount == 5)
            {
                var problem = Problem(HttpStatusCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                await _cacheService.RemoveCachesAsync(async (cancellToken) =>
                {
                    await _userRepository.UpdateAsync(new SysUser()
                    {
                        Id = user.Id, Status = 1
                    }, UpdatingProps <SysUser>(x => x.Status), cancellToken);
                }, _cacheService.ConcatCacheKey(CachingConsts.UserValidateInfoKeyPrefix, user.Id.ToString()));

                return(problem);
            }

            if (HashHelper.GetHashedString(HashType.MD5, input.Password, user.Salt) != user.Password)
            {
                var problem = Problem(HttpStatusCode.BadRequest, "用户名或密码错误");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            if (user.RoleIds.IsNullOrEmpty())
            {
                var problem = Problem(HttpStatusCode.Forbidden, "未分配任务角色,请联系管理员");
                log.Message    = problem.Detail;
                log.StatusCode = problem.Status.Value;
                await channelWriter.WriteAsync(log);

                return(problem);
            }

            log.Message    = "登录成功";
            log.StatusCode = (int)HttpStatusCode.Created;
            log.Succeed    = true;
            await channelWriter.WriteAsync(log);

            var userValidteInfo = new UserValidateDto
            {
                Id                = user.Id,
                Account           = user.Account,
                RoleIds           = user.RoleIds,
                Status            = user.Status,
                Name              = user.Name,
                ValidationVersion = HashHelper.GetHashedString(HashType.MD5, user.Account + user.Password)
            };

            return(userValidteInfo);
        }
Example #12
0
        public void Setup()
        {
            _context = ContextHelper.GetDatabaseContext();

            sut = new UserService(_context);

            userTeacher = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "John",
                HouseNumber  = 18,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            company = new Company
            {
                CompanyTitle = "Test inc."
            };

            dtoTeacher = new UserReadDto
            {
                FirstName = userTeacher.FirstName,
                LastName  = userTeacher.LastName,
                Id        = userTeacher.Id
            };

            userCompany = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "Johnnie",
                HouseNumber  = 19,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            dtoCompany = new UserReadDto
            {
                FirstName = userCompany.FirstName,
                LastName  = userCompany.LastName,
                Id        = userCompany.Id
            };

            userStudent = new User
            {
                Id           = Guid.NewGuid(),
                City         = "City",
                Email        = "*****@*****.**",
                FirstName    = "Henk",
                HouseNumber  = 17,
                LastName     = "Doe",
                PasswordHash = Guid.NewGuid().ToString(),
                PhoneNumber  = "+3259874896",
                ZipCode      = 7890,
                UserName     = "******",
                StreetName   = "Easy Street",
                IsValidated  = false
            };

            dtoStudent = new UserReadDto
            {
                FirstName = userStudent.FirstName,
                LastName  = userStudent.LastName,
                Id        = userStudent.Id
            };

            roleCompany = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Company",
                NormalizedName = "COMPANY"
            };

            roleStudent = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Student",
                NormalizedName = "STUDENT"
            };

            roleTeacher = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Teacher",
                NormalizedName = "TEACHER"
            };

            internship = new Internship
            {
                RequiredFieldsOfStudy  = new List <string>(),
                AssignedStudents       = new List <string>(),
                Environment            = new List <string>(),
                TechnicalDescription   = "TechnicalDescription",
                ExtraRequirements      = "ExtraRequirements",
                ResearchTheme          = "ResearchTheme",
                Activities             = new List <string>(),
                RequiredStudentsAmount = 2,
                AdditionalRemarks      = "AdditionalRemarks",
                Periods         = new List <string>(),
                Description     = "Description",
                DateCreated     = DateTime.UtcNow,
                DateOfState     = DateTime.UtcNow,
                Id              = Guid.NewGuid(),
                InternshipState = 0,
                Reviewers       = new List <ReviewerInternships> {
                    new ReviewerInternships
                    {
                        ReviewedInternship = internship,
                        Reviewer           = userTeacher
                    }
                }
            };

            updateUser = new UserUpdate
            {
                FieldOfStudy = "UpdatedFOS"
            };

            userValidateDto = new UserValidateDto
            {
                Id        = userCompany.Id,
                Validated = true
            };

            pwDto = new ChangePasswordDto
            {
                OldPassword = userStudent.PasswordHash,
                NewPassword = "******"
            };

            companyUpdate = new CompanyUpdate
            {
                CompanyName = "Updated"
            };

            _context.Add(company);

            _context.Add(userCompany);
            _context.Roles.Add(roleCompany);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleCompany.Id,
                UserId = userCompany.Id
            });
            _context.Add(userTeacher);
            _context.Roles.Add(roleTeacher);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleTeacher.Id,
                UserId = userTeacher.Id
            });
            _context.Add(userStudent);
            _context.Roles.Add(roleStudent);
            _context.UserRoles.Add(new Microsoft.AspNetCore.Identity.IdentityUserRole <Guid>
            {
                RoleId = roleStudent.Id,
                UserId = userStudent.Id
            });
            _context.Add(internship);
            _context.SaveChanges();
        }
Example #13
0
 internal async Task SetValidateInfoToCacheAsync(UserValidateDto value)
 {
     var cacheKey = ConcatCacheKey(CachingConsts.UserValidateInfoKeyPrefix, value.Id);
     await _cache.Value.SetAsync(cacheKey, value, TimeSpan.FromSeconds(CachingConsts.OneDay));
 }