Example #1
0
        public async Task <ActionResult> RegisterUser(UserPostDto dto)
        {
            var user = await _userRepository.GetByEmail(dto.Email);

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

            user = await _userRepository.GetByUsername(dto.Username);

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

            var id      = Guid.NewGuid();
            var addedAt = DateTime.UtcNow;
            var salt    = _encrypter.GetSalt(dto.Password);
            var hash    = _encrypter.GetHash(dto.Password, salt);

            user = new User(id, dto.Username, dto.Email, hash, salt, addedAt);

            await _userRepository.Add(user);

            return(CreatedAtRoute("GetActiveUser", user));
        }
Example #2
0
        /// <inheritdoc />
        /// <summary>
        /// Register an user for given email, password and name
        /// </summary>
        /// <param name="code">Users university code id</param>
        /// <param name="email">Users email</param>
        /// <param name="passw">Users password</param>
        /// <param name="name">Users name</param>
        /// <param name="surname">Users surname</param>
        /// <param name="phone">Users phone number</param>
        /// <returns></returns>
        public async Task <JsonWebToken> RegisterAsync(int code, string email, string passw, string name, string surname,
                                                       string phone)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmptyEmail);
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmptyName);
            }
            if (string.IsNullOrWhiteSpace(surname))
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmptySurname);
            }
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmptyPhone);
            }
            if (string.IsNullOrWhiteSpace(passw))
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmptyPassword);
            }

            if (!email.IsValidEmail())
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.NotEmail);
            }
            if (!passw.IsValidPassword())
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.NotPassword);
            }

            var user = await _userRepository.GetAsync(email);

            if (user != null)
            {
                throw new KarolinkaException(KarolinkaException.ExceptionType.EmailAlreadyUsed);
            }

            var salt     = _encrypter.GetSalt();
            var password = _encrypter.GetHash(passw, salt);

            user = new UserDbModel(
                Guid.NewGuid(),
                code,
                email,
                name,
                surname,
                phone,
                password,
                salt,
                DateTime.UtcNow
                );

            await _userRepository.AddAsync(user);

            return(await LoginAsync(email, passw));
        }
Example #3
0
        public async Task ChangeUserPasswordAsync(string email, string newPassword)
        {
            var user = await _userRepository.GetAsync(email);

            var salt = _encrypter.GetSalt(newPassword);
            var hash = _encrypter.GetHash(newPassword, salt);

            user.SetPassword(hash);
            await _userRepository.UpdateAsync(user);
        }
Example #4
0
        public void hashing_string_should_return_hashed()
        {
            var pass1 = "secret";
            var salt1 = _encrypter.GetSalt();

            var hash1 = _encrypter.GetHash(pass1, salt1);

            hash1.Should().BeOfType <string>();
            hash1.Should().NotBe(pass1);
            hash1.Should().NotBe(salt1);
        }
Example #5
0
        public async Task RegisterAsync(string email, string userName, string password, string role)
        {
            var user = await _userRepository.GetAsync(email);
            if (user != null)
            {
                throw new Exception($"User with email: '{email}' already exists.");
            }

            var salt = _encrypter.GetSalt(password);
            var hash = _encrypter.GetHash(password, salt);
            user = new User(email, userName, hash, salt, role);
            await _userRepository.AddAsync(user);
        }
Example #6
0
        public async Task RegisterAsync(Guid id, string email, string password, string username, string role)
        {
            var user = await _userRepository.GetAsync(email);

            if (user != null)
            {
                throw new ServiceException(ServiceErrorCodes.EmailInUse, $"User with this email: '{email}' already exists.");
            }

            string salt = _encrypter.GetSalt();
            string hash = _encrypter.GetHash(password, salt);
            await _userRepository.AddAsync(new User(id, email, hash, salt, username, role));
        }
        public async Task RegisterUserAsync(string firstName, string lastName, string login, string password,
                                            string email)
        {
            if (_userRepository.IsUserExist(login))
            {
                throw new ServiceExceptions(ServiceErrorCodes.UserExist,
                                            $"User with this login: {login} already exist");
            }

            var salt = _encrypter.GetSalt(password);
            var hash = _encrypter.GetHash(password, salt);
            await _userRepository.AddAsync(new User(firstName, lastName, login, hash, salt, email));
        }
Example #8
0
        public async Task RegisterAsync(string username, string password, string role)
        {
            var user = await _userRepository.GetAsync(username);

            if (user != null)
            {
                throw new ServiceException(Exceptions.ErrorCodes.UsernameInUse);
            }
            var salt = _encrypter.GetSalt(password);
            var hash = _encrypter.GetHash(password, salt);

            user = new User(username, hash, salt, role);
            await _userRepository.AddAsync(user);
        }
Example #9
0
        public async Task RegisterAsync(Guid id, string nickname, string password)
        {
            var player = await _playerRepository.GetAsync(nickname);

            if (player != null)
            {
                throw new ServiceException(ErrorCodes.UserExist, "User with this nickname already exists.");
            }

            var salt = _encrypter.GetSalt(password);
            var hash = _encrypter.GetHash(password, salt);

            player = new Player(id, nickname, hash, salt);
            await _playerRepository.AddAsync(player);
        }
        public async Task ChangePassword(ChangePasswordCommand command)
        {
            var user = await _identityRepository.GetAsync(command.UserId);

            if (user is null)
            {
                throw new IdentityExceptions("User not found");
            }

            var salt = _encrypter.GetSalt(command.NewPassword);
            var hash = _encrypter.GetHash(command.NewPassword, salt);

            user.SetPassword(hash, salt);
            await _identityRepository.EditPasswordAsync(user);
        }
Example #11
0
        public void SetPassword(string password, IEncrypter encrypter)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new NewException(NewCodes.NullPassword);
            }
            if (password.Length < 8)
            {
                throw new NewException(NewCodes.ShortPassword);
            }
            if (password.Length >= 32)
            {
                throw new NewException(NewCodes.LongPassword);
            }
            if (password == Password)
            {
                throw new Exception();
            }

            string salt = encrypter.GetSalt(password);
            string hash = encrypter.GetHash(password, salt);

            Password = hash;
            Salt     = salt;
        }
Example #12
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegistrationRequest user)
        {
            if (user.Username.IsEmail())
            {
                return(Json(new Exception("Username cannot be of email format")));
            }

            if (!user.Email.IsEmail())
            {
                return(Json(new Exception("Email must be of email format")));
            }

            var usernameQuery = new GetUserByIdentifiersQuery(user.Username);

            if (queryBus.Execute(usernameQuery) != null)
            {
                return(Json(new Exception($"Username : {user.Username} already exists")));
            }

            var emailQuery = new GetUserByIdentifiersQuery(user.Email);

            if (queryBus.Execute(emailQuery) != null)
            {
                return(Json(new Exception($"User with email : {user.Email} already exists")));
            }


            var salt     = _encrypter.GetSalt();
            var passHash = _encrypter.GetHash(user.Password, salt);

            var command = new RegisterUserCommand(user.Username, user.Email, passHash, salt);
            await commandBus.ExecuteAsync(command);

            return(StatusCode(201));
        }
Example #13
0
        public async Task RegisterAsync(Guid userId, string email,
                                        string username, string password, string role)
        {
            var user = await _userRepository.GetAsync(email);

            if (user != null)
            {
                throw new ServiceException(ErrorCodes.EmailInUse, $"User with email '{email}' already exists.");
            }

            var salt = _encrypter.GetSalt(password);
            var hash = _encrypter.GetHash(password, salt);

            user = new User(userId, email, username, hash, salt, role);
            await _userRepository.AddAsync(user);
        }
Example #14
0
 //Create
 public async Task RegisterAsync(string email, string username, string password)
 {
     email.EmailValidation();
     username.UsernameValidation();
     password.PasswordValidation();
     try
     {
         await _userRepository.GetAsync(email);
     }
     catch
     {
         throw new Exception($"User with email: {email} is exists");
     }
     try
     {
         await _userRepository.GetAsync(null, username);
     }
     catch
     {
         throw new Exception($"User with username: {username} is exists");
     }
     var salt = _encrypter.GetSalt(password);
     var hash = _encrypter.GetHash(password, salt);
     var user = new User(email, username, hash, salt);
     await _userRepository.AddAsync(user);
 }
Example #15
0
        public string GetHash(string value)
        {
            var salt = _encrypter.GetSalt(value);
            var hash = _encrypter.GetHash(value, salt);

            return(hash);
        }
Example #16
0
        public async Task RegisterAsync(UserDto user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (user.Password == null)
            {
                throw new ArgumentNullException(nameof(user.Password));
            }

            var domainUser = await _userRepository.GetAsync(user.Email);

            if (domainUser != null)
            {
                throw new Exception($"User with email: {user.Email} already exists.");
            }

            var salt = _encrypter.GetSalt(user.Password);
            var hash = _encrypter.GetHash(user.Password, salt);

            user.Password = hash;
            user.Salt     = salt;

            if (String.IsNullOrEmpty(user.Role))
            {
                user.Role = "user";
            }
            var newUser = _mapper.Map <UserDto, User>(user);
            await _userRepository.RegisterAsync(newUser);
        }
        public void SetPassword(string password, IEncrypter encrypter)
        {
            if (password.Empty())
            {
                throw new DomainException(OperationCodes.InvalidPassword,
                                          "Password can not be empty.");
            }
            if (password.Length < 4)
            {
                throw new DomainException(OperationCodes.InvalidPassword,
                                          "Password must contain at least 4 characters.");
            }
            if (password.Length > 100)
            {
                throw new DomainException(OperationCodes.InvalidPassword,
                                          "Password can not contain more than 100 characters.");
            }

            var salt = encrypter.GetSalt(password);
            var hash = encrypter.GetHash(password, salt);

            Password  = hash;
            Salt      = salt;
            UpdatedAt = DateTime.UtcNow;
        }
        private void ChangePassword(string newPassword)
        {
            var salt = encrypter.GetSalt(newPassword);
            var hash = encrypter.GetHash(newPassword, salt);

            user.ChangePassword(hash, salt);
        }
Example #19
0
        public IAccessToken Create(int userId)
        {
            // create the token
            var    token        = container.GetInstance <IAccessToken>();
            var    passwordHash = container.GetInstance <IPasswordHash>();
            string tokenHash;
            string encryptedUserId;

            byte[]   userIdSalt;
            DateTime issuedAt, refreshed;

            // check whether there is a token existing for this userId
            bool tokenExists = tokenStorage.VerifyTokenExistence(userId, out tokenHash, out issuedAt, out refreshed);

            if (tokenExists)
            {
                if (dateHelper.IsWithinTimeOutLimit(refreshed))
                {
                    // token is still valid, refresh the token to extend the timeout
                    if (!tokenStorage.RefreshToken(userId, tokenHash, dateHelper.Now))
                    {
                        throw new Exception("Failed to refresh existing the token");
                    }

                    token.IssuedAt  = issuedAt;
                    token.Token     = tokenHash;
                    encryptedUserId = null;
                    issuedAt        = new DateTime();
                    refreshed       = new DateTime();
                    return(token);
                }
            }

            // Create the token identifier
            Guid tokenId     = openGuid.New();
            var  hashedToken = passwordHash.CreateHash(tokenId.ToString());

            userIdSalt      = encrypter.GetSalt();
            encryptedUserId = encrypter.Encrypt(userId.ToString(), userIdSalt);
            issuedAt        = dateHelper.Now;

            //store the hashInfo
            if (!tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt))
            {
                throw new Exception("Failed to store the session token");
            }

            // set the token for the user
            token.Token    = hashedToken.Hash;
            token.IssuedAt = issuedAt;

            //reset all information
            hashedToken.Dispose();
            userIdSalt      = null;
            encryptedUserId = null;
            passwordHash.Dispose();
            passwordHash = null;

            return(token);
        }
Example #20
0
        public async Task ChangePasswordAsync(string currentPassword, string newPassword, string email)
        {
            var user = await _user.GetAsyncByEmail(email);

            if (user == null)
            {
                throw new ArgumentNullException($"User with {email} not exist");
            }
            if (currentPassword == newPassword)
            {
                throw new ArgumentException("Password are the same");
            }
            var salt = _encrypter.GetSalt(newPassword);

            user.Password = _encrypter.GetHash(salt, newPassword);
        }
Example #21
0
        public async Task <UserDto> RegisterAsync(string email, string firstName, string lastName, string password)
        {
            var user = await _unitOfWork.Users.GetByEmailAsync(email);

            if (user != null)
            {
                throw new Exception($"User with email: {email} already exists.");
            }

            string passwordSalt = _encrypter.GetSalt();

            user = new User()
            {
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                Salt         = passwordSalt,
                PasswordHash = _encrypter.GetHash(password, passwordSalt),
                CreateDate   = DateTime.Now,
            };

            await _unitOfWork.Users.AddAsync(user);

            await _unitOfWork.CompleteAsync();

            return(_mapper.Map <User, UserDto>(user));
        }
Example #22
0
        public void SetSenha(string senha, IEncrypter encrypter)
        {
            AddNotifications(new Contract()
                             .IsNotNullOrEmpty(senha, "usuario.senha", "Senha deve ser preenchida"));

            Salt  = encrypter.GetSalt();
            Senha = encrypter.GetHash(senha, Salt);
        }
        public async Task RegisterAsync(CustomerOnCreateDto customerDto)
        {
            var customer = await _customerRepository.GetAsync(customerDto.Login);

            if (customer != null)
            {
                throw new ServiceException(ErrorCodes.OwnerAlreadyExists, "Login is already in use.");
            }

            var salt = _encrypter.GetSalt(customerDto.Password);
            var hash = _encrypter.GetHash(customerDto.Password, salt);

            var customerToRegister = new Customer(customerDto.Login, customerDto.FirstName, customerDto.LastName,
                                                  customerDto.Email, customerDto.Phone, hash, salt);

            await _customerRepository.AddAsync(customerToRegister);
        }
Example #24
0
        public async Task LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null)
            {
                throw new Exception("invalid credentials");
            }
            var salt       = _encrypter.GetSalt(password);
            var hashedPass = _encrypter.GetHash(password, salt);

            if (user.Password == hashedPass)
            {
                return;
            }
            throw new Exception("invalid credentials");
        }
Example #25
0
        public async Task RegisterUserAsync(RegisterViewModel model)
        {
            var user = await _userRepo.GetUserByEmailAsync(model.Email);

            if (user != null)
            {
                throw new Exception("Użytkownik już istnieje w bazie");
            }

            var salt = _encrypter.GetSalt(model.Password);
            var hash = _encrypter.GetHash(model.Password, salt);

            user = new User(Guid.NewGuid(), model.Email, hash, salt);
            await _userRepo.AddUserAsync(user);

            user.UserInRoles.Add(new UserInRole(user.UserId, model.Role.RoleId));
            await _userInRoleRepo.SaveUserInRoles(user.UserInRoles);
        }
Example #26
0
 public void SetPassword(string password, IEncrypter encrypter)
 {
     if (string.IsNullOrWhiteSpace(password))
     {
         throw new ActioException("Invalid_Password", "Password can not be empty");
     }
     Salt     = encrypter.GetSalt(password);
     Password = encrypter.GetHash(password, Salt);
 }
Example #27
0
 public void SetPassword(string password, IEncrypter encrypter)
 {
     if (string.IsNullOrWhiteSpace(password))
     {
         throw new MyCommunityExceptions("empty_user_password", "user password cannot be empty");
     }
     Salt     = encrypter.GetSalt();
     Password = encrypter.GetHash(password, Salt);
 }
        private void PrepareUser(AddUserCommand request)
        {
            userPassword = PasswordHelpers.GeneratePassword();
            var      salt    = encrypter.GetSalt(userPassword);
            var      hash    = encrypter.GetHash(userPassword, salt);
            DateTime addedAt = DateTimeHelpers.GetCurrenTime();

            user = new User(request.Email, request.Firstname, request.Lastname, hash, salt, UserRole.Writer, addedAt);
        }
Example #29
0
 public void SetPassword(string password, IEncrypter encrypter)
 {
     if (string.IsNullOrEmpty(password))
     {
         throw new ActioException("empty_password", $"Password can not be empty.");
     }
     Salt     = encrypter.GetSalt();
     Password = encrypter.GetHash(password, Salt);
 }
Example #30
0
 public void SetPassword(string password, IEncrypter encrypter)
 {
     if (string.IsNullOrWhiteSpace(password))
     {
         throw new MushroomCloudException("empty_user_password", "User password can not be empty.");
     }
     Salt     = encrypter.GetSalt();
     Password = encrypter.GetHash(password, Salt);
 }