public async Task <User> RegisterAccountAsync(RegisterDto registerDto) { Log.Information($"Trying to register new user. Name: {registerDto.Name} Email: {registerDto.Email}"); if (_context.Users.Any(x => x.Email == registerDto.Email)) { Log.Information( $"Could not register user Name: {registerDto.Name}. Email:{registerDto.Email} already exists"); throw new ApiException($"The email {registerDto.Email} is already being used by another user", StatusCodes.Status409Conflict); } var salt = _hashService.GenerateSalt(); var hashedPassword = _hashService.Hash(registerDto.Password + salt); //This can potentially be implemented again, but is just sat to 1 for now var programme = _context.Programmes.FirstOrDefault(x => x.Id == 1); if (programme == null) { throw new ApiException("No programme found with the id: 0", StatusCodes.Status400BadRequest); } var user = new User { Name = EscapeName(registerDto.Name), Email = registerDto.Email, Password = hashedPassword, Salt = salt, Programme = programme, UserGroup = UserGroup.Customer }; _context.Users.Add(user); if (_context.SaveChanges() == 0) { throw new ApiException("The user could not be created - try again in a minute"); } var claims = new[] { new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.Name), new Claim(ClaimTypes.Role, "verification_token") }; var verificationToken = _tokenService.GenerateToken(claims); await _emailService.SendRegistrationVerificationEmailAsync(user, verificationToken); return(user); }
public CommandResult <Domain.User> Register(Domain.User user) { var errors = _AddValidator.ValidateAdd(user); if (errors.Any()) { return(new CommandResult <Domain.User> { Entity = null, RowsAffected = 0, ValidationErrors = errors }); } user.Salt = _HashService.GenerateSalt(); user.Password = _HashService.HashString(user.Password, user.Salt); _DbContext.Users.Add(user); _DbContext.SaveChanges(); return(new CommandResult <Domain.User> { Entity = user, RowsAffected = 1, ValidationErrors = new List <string>() }); }
public async Task Consume(ConsumeContext <ToolBox.Contracts.Auth.UpdateAuthUser> context) { _logger.LogInformation("UpdateAuthUserConsumer Called"); var userToUpdate = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == context.Message.Id); var salt = _hashService.GenerateSalt(); if (context.Message.Username != null) { userToUpdate.UserName = context.Message.Username; } if (context.Message.Email != null) { userToUpdate.Email = context.Message.Email; } if (context.Message.Password != null) { userToUpdate.PasswordSalt = salt; userToUpdate.PasswordHash = _hashService.GenerateHash(context.Message.Password, salt); } await _dbContext.SaveChangesAsync(CancellationToken.None); await context.Publish <AuthUserUpdated>(new { userToUpdate.Id }); }
public async Task Consume(ConsumeContext <ToolBox.Contracts.Auth.CreateAuthUser> context) { _logger.LogInformation("CreateAuthUserConsumer Called"); #if DEBUG //Only add roles to debug seeded data var rolesList = new List <UserRole>(); switch (context.Message.Username) { case "Admin": rolesList.Add(new UserRole { UserId = context.Message.Id, Role = await _dbContext.Roles.FirstOrDefaultAsync(r => r.RoleName == "Admin") }); break; case "CustomerService": rolesList.Add(new UserRole { UserId = context.Message.Id, Role = await _dbContext.Roles.FirstOrDefaultAsync(r => r.RoleName == "CustomerService") }); break; } #endif var salt = _hashService.GenerateSalt(); var authUserToCreate = new Auth.Domain.Entities.AuthUser { Id = context.Message.Id, UserName = context.Message.Username, Email = context.Message.Email, PasswordSalt = salt, PasswordHash = _hashService.GenerateHash(context.Message.Password, salt), UserRoles = rolesList }; await _dbContext.Users.AddAsync(authUserToCreate); await _dbContext.SaveChangesAsync(CancellationToken.None); await context.Publish <AuthUserCreated>(new { authUserToCreate.Id }); }
public async Task <IActionResult> Register([FromBody] UserCredentials userCredentials) { byte[] salt = _hashService.GenerateSalt(); await _databaseContext.Users.AddAsync(new User { CreatedAt = DateTime.Now, Name = userCredentials.Username, Password = _hashService.HashPassword(userCredentials.Password, salt), Salt = Convert.ToBase64String(salt) }); await _databaseContext.SaveChangesAsync(); if (_authService.Authorize(userCredentials.Username, userCredentials.Password, out ClientSession clientSession)) { return(Ok(clientSession)); } return(Unauthorized()); }
private ClientSession GenerateSession(string username, IEnumerable <Claim> claims) { SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])); SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); JwtSecurityToken jwtToken = new JwtSecurityToken(Constants.HttpServerAddress, Constants.HttpServerAddress, claims, expires: DateTime.Now.AddMinutes(0.5), signingCredentials: credentials); ClientSession clientSesh = new ClientSession { ExpiresAt = DateTime.Now.AddMinutes(5.0), Session = new Session { ExpiresAt = DateTime.Now.AddDays(1), RefreshToken = Convert.ToBase64String(_hashService.GenerateSalt(256)) }, Token = new JwtSecurityTokenHandler().WriteToken(jwtToken) }; _authorizationCache.Add(username, clientSesh.Session); return(clientSesh); }
public void Hash_GenerateSalt_ReturnsValidSalt() { var result = hashService.GenerateSalt(); Assert.IsNotNull(result); }