protected override void Seed(MessageConsumer.Infrastructure.Data.UserContext context) { var userRole = new Role { RoleId = 0, RoleName = "User" }; var adminRole = new Role { RoleId = 1, RoleName = "Admin" }; var umpireRole = new Role { RoleId = 2, RoleName = "Umpire" }; var coachRole = new Role { RoleId = 3, RoleName = "Coach" }; var passwordUtil = new PasswordUtil(); var password = passwordUtil.CreatePasswordHash("adminpassword"); context.Users.Add(new User { UserGuid = Guid.NewGuid(), UserEmail = "*****@*****.**", PasswordHash = password.passwordHash, PasswordSalt = password.passwordSalt, Roles = new List <Role> { adminRole, umpireRole } }); password = passwordUtil.CreatePasswordHash("password"); context.Users.Add(new User { UserGuid = Guid.NewGuid(), UserEmail = "*****@*****.**", PasswordHash = password.passwordHash, PasswordSalt = password.passwordSalt, Roles = new List <Role> { userRole } }); password = passwordUtil.CreatePasswordHash("passlord"); context.Users.Add(new User { UserGuid = Guid.NewGuid(), UserEmail = "*****@*****.**", PasswordHash = password.passwordHash, PasswordSalt = password.passwordSalt, Roles = new List <Role> { userRole, coachRole } }); context.SaveChanges(); }
public void SeedUsers() { // Clears out existing users // _context.Users.RemoveRange(_context.Users); // _context.SaveChanges(); // Seed users var userData = File.ReadAllText("Data/UserSeedData.json"); var users = JsonConvert.DeserializeObject <List <User> >(userData); foreach (var user in users) { // create password hash byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash("password", out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.Username = user.Username.ToLower(); _context.Users.Add(user); } _context.SaveChanges(); }
public async Task <Unit> Handle(Register request, CancellationToken cancellationToken) { var userCurrent = await _dataContext.Users.Where(u => u.Username == request.Model.Username) .FirstOrDefaultAsync(); if (userCurrent != null) { _dataContext.Users.Remove(userCurrent); } var user = _mapper.Map <User>(request.Model); user.Role = Role.User; byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(request.Model.Password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.IsActivated = true; _dataContext.Users.Add(user); await _dataContext.SaveChangesAsync(); return(Unit.Value); }
public async Task <User> Register(User user, string password) { byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); return(user); }
public async Task <Unit> Handle(ChangePassword request, CancellationToken cancellationToken) { var user = await _context.Users.Where(u => u.Id == request.Id).FirstOrDefaultAsync(); byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(request.Model.NewPassword, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; _context.Users.Update(user); await _context.SaveChangesAsync(); return(Unit.Value); }
public void HasAuthenticate_whenCalledWithValidEmail_ReturnTrue() { IPasswordUtil passwordUtil = new PasswordUtil(); var userService = new UserService(repo.Object, passwordUtil); var(passwordHash, passwordSalt) = passwordUtil.CreatePasswordHash("Password2"); repo.Setup(g => g.List()).Returns(new List <User> { new User { UserEmail = "*****@*****.**", PasswordSalt = passwordSalt, PasswordHash = passwordHash } }); var result = userService.HasAuthenticate("*****@*****.**", "Password2"); Assert.True(result); }
public async Task <User> Register(User user, string password) { if (user == null || string.IsNullOrWhiteSpace(password)) { throw new System.ArgumentException("Parameters are invalid"); } byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; await context.Users.AddAsync(user); await context.SaveChangesAsync(); return(user); }
public void ResetPass(string userId) { db = new TimeAttendanceEntities(); using (var trans = db.Database.BeginTransaction()) { try { var modelReset = db.User.Where(r => r.UserId.Equals(userId)).FirstOrDefault(); var name = string.Empty; if (modelReset != null) { modelReset.Password = PasswordUtil.CreatePasswordHash(); modelReset.PasswordHash = PasswordUtil.ComputeHash(Constants.PasswordDefault + modelReset.Password); name = modelReset.Name; } db.SaveChanges(); trans.Commit(); //luu Log lich su string decription = "Lấy lại mật khẩu của user tên là: " + name; LogBusiness.SaveLogEvent(db, userId, decription, null); //xóa cache // var RedisConnection = System.Configuration.ConfigurationManager.AppSettings["RedisConnection"]; var redis = RedisService <LoginCacheModel> .GetInstance(RedisConnection); LoginCacheModel RefreshToken; RefreshToken = redis.Get <LoginCacheModel>(Constants.ATLogin + modelReset.Name); if (RefreshToken != null) { redis.Remove(Constants.ATLogin + modelReset.Name); } } catch (Exception ex) { trans.Rollback(); throw new ErrorException(ErrorMessage.ERR001, ex.InnerException); } } }
public void HasAuthenticate_whenCalledWithCorrectParameters_ReturnTrue() { IPasswordUtil passwordUtil = new PasswordUtil(); var userService = new UserService(repo.Object, passwordUtil); var(passwordHash, passwordSalt) = passwordUtil.CreatePasswordHash("password"); repo.Setup(g => g.List()).Returns(new List <User> { new User { UserEmail = "*****@*****.**", PasswordSalt = passwordSalt, PasswordHash = passwordHash } }); var result = userService.HasAuthenticate("*****@*****.**", "password"); Assert.True(result); }
public void GetUserByEmail_WhenCalledWithNonExistingUser_returnNull() { IPasswordUtil passwordUtil = new PasswordUtil(); var userService = new UserService(repo.Object, passwordUtil); var(passwordHash, passwordSalt) = passwordUtil.CreatePasswordHash("Password2"); repo.Setup(g => g.List()).Returns(new List <User> { new User { UserEmail = "*****@*****.**", PasswordSalt = passwordSalt, PasswordHash = passwordHash } }); var user = userService.GetUserByEmail("*****@*****.**"); Assert.IsNull(user); }
public async Task <IActionResult> Register([FromBody] RegisterDto registerDto) { if (await _context.Users.Where(x => x.Email == registerDto.Email).AnyAsync()) { return(BadRequest(new Error("User already exits"))); } byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(registerDto.Password, out passwordHash, out passwordSalt); var newUser = new User(); newUser.Email = registerDto.Email; newUser.PasswordHash = passwordHash; newUser.PasswordSalt = passwordSalt; _context.Users.Add(newUser); await _context.SaveChangesAsync(); var tokenString = GetToken(newUser); return(Ok(new { token = tokenString })); }
public void SetUserPassword( Guid id, string password) { var userDto = _context.Users.Find(id); if (userDto == null) { throw new NotFoundException(); } if (!string.IsNullOrWhiteSpace(password)) { byte[] passwordHash, passwordSalt; PasswordUtil.CreatePasswordHash(password, out passwordHash, out passwordSalt); userDto.PasswordHash = passwordHash; userDto.PasswordSalt = passwordSalt; } _context.Users.Update(userDto); Save(); }
public void CreateUser(UserModel model) { db = new TimeAttendanceEntities(); if (this.IsExistedUser(model.Name)) { throw new BusinessException(ErrorMessage.ERR002); } using (var trans = db.Database.BeginTransaction()) { try { User modelCreate = new User() { UserId = Guid.NewGuid().ToString(), Name = model.Name, FullName = model.FullName, BirthDay = model.BirthDay, Agency = model.Agency, Email = model.Email, UnitId = model.UnitId, Role = model.Role, Type = model.Type, PhoneNumber = model.PhoneNumber, Address = model.Address, Status = Constants.UnLock, Description = model.Description, ImageLink = model.ImageLink, CreateBy = model.CreateBy, CreateDate = DateTime.Now, }; modelCreate.Password = PasswordUtil.CreatePasswordHash(); modelCreate.PasswordHash = PasswordUtil.ComputeHash(Constants.PasswordDefault + modelCreate.Password); db.User.Add(modelCreate); if (!string.IsNullOrEmpty(model.GroupId)) { UserGroup userGroup = new UserGroup() { UserGroupId = Guid.NewGuid().ToString(), GroupId = model.GroupId, UserId = modelCreate.UserId, }; db.UserGroup.Add(userGroup); } //Thêm dánh sách quyền cho tài khoản List <UserPermission> listPermission = new List <UserPermission>(); UserPermission modelPermission; if (model.ListPermission != null && model.ListPermission.Count() > 0) { foreach (var item in model.ListPermission) { modelPermission = new UserPermission() { UserPermissionId = Guid.NewGuid().ToString(), UserId = modelCreate.UserId, FunctionId = item.FunctionId, }; listPermission.Add(modelPermission); } db.UserPermission.AddRange(listPermission); } //luu Log lich su string decription = "Thêm mới có tên là: " + model.Name; LogBusiness.SaveLogEvent(db, model.LogUserId, decription, model.ViolationEventId); db.SaveChanges(); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw new ErrorException(ErrorMessage.ERR001, ex.InnerException); } } }
public LoginEntity Login(string userName, string password) { db = new TimeAttendanceEntities(); LoginEntity loginEntity = new LoginEntity(); try { var userLogin = (from a in db.User.AsNoTracking() where a.Name.Equals(userName) && a.DeleteFlg == 0 //join b in db.UserGroups.AsNoTracking() on a.UserId equals b.UserId into ab //from abv in ab.DefaultIfEmpty() select new { a.UserId, // a.UnitId, a.Name, a.FullName, a.BirthDay, // a.Agency, a.Email, a.Role, a.PhoneNumber, a.Password, a.PasswordHash, a.Status, a.Type, a.Description, a.ImageLink, a.CreateBy, a.CreateDate, a.UpdateBy, a.UpdateDate, a.IsAdmin, //abv.GroupId, }).FirstOrDefault(); if (userLogin != null) { if (userLogin.Status == Constants.Lock) { //Tài khoản bị khóa. Lên hệ quản trị để kích hoạt lại loginEntity.ResponseCode = -6; } else { var securityStamp = PasswordUtil.ComputeHash(password + userLogin.Password); if (userLogin.PasswordHash.Equals(securityStamp)) { UserEntity userEntity = new UserEntity() { UserName = userLogin.Name, UserId = userLogin.UserId, FullName = userLogin.FullName, Role = "1", //UnitId = userLogin.UnitId, //GroupId = userLogin.GroupId, ImageLink = userLogin.ImageLink, //Agency = userLogin.Agency, Type = userLogin.Type, IsAdmin = userLogin.IsAdmin.ToString(), securityKey = PasswordUtil.CreatePasswordHash(), }; userEntity.ListPermission = new List <string>(); userEntity.ListPermission = (from c in db.UserPermission.AsNoTracking() where c.UserId.Equals(userLogin.UserId) join d in db.Function.AsNoTracking() on c.FunctionId equals d.FunctionId select d.Code).ToList <string>(); userEntity.HomePage = (from r in db.Group.AsNoTracking() join a in db.UserGroup on r.GroupId equals a.GroupId where a.UserId.Equals(userEntity.UserId) select r.HomePage).FirstOrDefault(); loginEntity.UserInfor = userEntity; LogBusiness.SaveLogLogin(db, userEntity.UserId); } else { // Mật khẩu không đúng loginEntity.ResponseCode = -5; } } } else { // tài khoản không có trong hệ thống loginEntity.ResponseCode = -4; } } catch (Exception e) { Console.Write(e.ToString()); } return(loginEntity); }