Esempio n. 1
0
        public async Task Login(LoginViewModel model)
        {
            var user = await _userRepo.GetUserByEmailAsync(model.Email);

            if (user == null)
            {
                throw new Exception($"Użytkownik o takim adresie {model.Email} nie istnieje");
            }

            var hash = _encrypter.GetHash(model.Password, user.Salt);

            model.Role = user.Role;

            if (user.Password == hash)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.Role, user.Role),
                    new Claim("user", user.ToString())
                };

                var identity = new ClaimsIdentity(claims, "ApplicationCoockie");
                var ctx      = HttpContext.Current.Request.GetOwinContext();

                var authManager = ctx.Authentication;

                authManager.SignIn(identity);
            }
        }
Esempio n. 2
0
        public async Task <IdentityToken> LoginAsync(string username, string password)
        {
            var account = await _accountRepository.GetAsync(username);

            if (account == null)
            {
                throw new Exception("Invalid credentials");
            }
            var hash = _encrypter.GetHash(password, account.Salt);

            if (account.Password != hash)
            {
                throw new Exception("Invalid credentials");
            }
            var token        = Guid.NewGuid().ToString("N");
            var refreshToken = new RefreshToken(account, token);
            var jwt          = _jwtHandler.Create(account.Username, account.Role, account.Id);

            await _refreshTokenRepository.CreateAsync(refreshToken);

            return(new IdentityToken
            {
                AccessToken = jwt.AccessToken,
                Expires = jwt.Expires,
                RefreshToken = token,
                Role = account.Role,
                UserId = account.Id
            });
        }
Esempio n. 3
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);
 }
Esempio n. 4
0
        public async Task <LoginResponseDto> Login(string email, string password, string totpCode)
        {
            var user = await _userRepository.GetUser(email);

            if (user == null)
            {
                throw new Exception("User does not exist");
            }

            var hash = _encrypter.GetHash(password, user.Salt);


            if (user.PasswordHash == hash && _totpService.VerifyTotpCode(user, totpCode))
            {
                var jwtToken = _tokenService.GenerateJwtToken(user);

                var token        = _encrypter.GetSecureSalt(32);
                var refreshToken = new RefreshToken(token, DateTime.UtcNow.AddDays(1).Ticks.ToString());

                return(new LoginResponseDto
                {
                    JwtToken = jwtToken,
                    RefreshToken = _mapper.Map <RefreshToken, RefreshTokenDto>(refreshToken),
                    UserDto = _mapper.Map <User, UserDto>(user)
                });
            }

            throw new Exception("Invalid credentials");
        }
Esempio n. 5
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));
        }
Esempio n. 6
0
        public async Task <Tuple <TokenDto, int> > LoginAsync(UserDto user)
        {
            if (user.Email == null || user.Password == null)
            {
                throw new ArgumentNullException($"{nameof(user.Email)},{nameof(user.Password)}");
            }
            var domainUser = await _userRepository.GetAsync(user.Email);

            if (domainUser == null)
            {
                throw new Exception($"User with email: {user.Email} doesn't exists.");
            }
            var hash = _encrypter.GetHash(user.Password, domainUser.Salt);

            if (domainUser.Password == hash)
            {
                var jwt = _jwtHandler.CreateToken(domainUser);
                return(Tuple.Create(new TokenDto
                {
                    Token = jwt.Token,
                    Expires = jwt.Expires,
                    Role = domainUser.Role
                }, domainUser.Id));
            }
            return(Tuple.Create(new TokenDto()
            {
            }, 0));

            //jwt
            //configuration
        }
Esempio n. 7
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));
        }
Esempio n. 8
0
        public async Task RegisterAsync(Guid userId, string password)
        {
            var passwordHash = encrypter.GetHash(password);
            var token        = encrypter.GetToken(userId, passwordHash);
            var user         = new User(userId, passwordHash, token);

            dbContext.Add(user);
            await dbContext.SaveChangesAsync();
        }
Esempio n. 9
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);
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
        public async Task LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetOrFailAsync(email);

            var hash = _encrypter.GetHash(password, user.Salt);

            if (hash == user.Password)
            {
                return;
            }
            throw new Exception("Invalid credentials.");
        }
        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));
        }
Esempio n. 13
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);
        }
        public async Task RegisterAsync(string email, string password, string username, int roleId)
        {
            if (await _userRepository.GetAsync(email) != null)
            {
                throw new ServiceException(ServiceErrorCodes.EmailInUse, $"Email '{email}' is already in use.");
            }

            var salt = _encrypter.GetSalt();
            var hash = _encrypter.GetHash(password, salt);
            var id   = await _userRepository.NextId();

            var user = User.Create(id, email, username, roleId, hash, salt);
            await _userRepository.AddAsync(user);
        }
Esempio n. 15
0
        public async Task UpdateAsync(string email, string firstName, string lastName, string password)
        {
            var user = await _userRepository.GetOrFailAsync(email);

            user.SetEmail(email);
            user.SetFirstName(firstName);
            user.SetLastName(lastName);

            var hash = _encrypter.GetHash(password, user.Salt);

            user.SetPassword(hash);

            await _userRepository.UpdateAsync(user);
        }
Esempio n. 16
0
        public async Task RegisterAsync(Guid id, string email, string username, string password, string role)
        {
            User user = await userRepository.GetAsync(username);

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

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

            user = new User(id, email, username, hash, salt, role);
            await userRepository.AddAsync(user);
        }
Esempio n. 17
0
        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);
        }
Esempio n. 18
0
        public async Task <UserDto> AuthenticateAsync(string email, string password)
        {
            User user = await _unitOfWork.Users.GetByEmailAsync(email);

            if (user != null)
            {
                string hash = _encrypter.GetHash(password, user.Salt);

                if (user.PasswordHash == hash)
                {
                    return(_mapper.Map <User, UserDto>(user));
                }
            }
            return(null);
        }
Esempio n. 19
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(Exceptions.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, role, hash, salt);
            await _userRepository.AddAsync(user);
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        public async Task LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null)
            {
                throw new ServiceException(Exceptions.ErrorCodes.InvalidCredentials, "Invalid credentials.");
            }
            var hash = _encrypter.GetHash(password, user.Salt);

            if (user.Password == hash)
            {
                return;
            }
            throw new ServiceException(Exceptions.ErrorCodes.InvalidCredentials, "Invalid credentials.");
        }
Esempio n. 22
0
        public string GetHash(string value)
        {
            var salt = _encrypter.GetSalt(value);
            var hash = _encrypter.GetHash(value, salt);

            return(hash);
        }
Esempio n. 23
0
        public async Task LoginAsync(string email, string password)
        {
            var user = await _userRepository.GetAsync(email);

            if (user == null)
            {
                throw new ServiceException(ServiceErrorCodes.InvalidCredentials, $"Invalid credentials.");
            }
            var salt       = user.Salt;
            var logingHash = _encrypter.GetHash(password, salt);

            if (user.Password != logingHash)
            {
                throw new ServiceException(ServiceErrorCodes.InvalidCredentials, $"Invalid credentials.");
            }
        }
Esempio n. 24
0
        public bool IdentityUser(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                return(false);
            }
            string sqlText = "SELECT * FROM users WHERE USER_PEOPLE_ID = @username;";
            Dictionary <string, string> param = new Dictionary <string, string>();

            param.Add("username", username);
            DbFetchOutData outdata = _da.FecthQuery(sqlText, param);

            //ViewData["CbPost"] = outdata;

            /*SetPassWord(password, _encrypter);
             * Console.WriteLine("Salt: " + Salt);
             * Console.WriteLine("Password: "******"PWD_SALT"];
                var dbPass = outdata.Data[0]["USER_PASSWORD"];
                if (dbPass.Equals(_encrypter.GetHash(password, dbSalt)))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Esempio n. 25
0
        public async Task RegisterAsync(Guid userId, string email, string password, string firstName, string lastName, string role)
        {
            var user = await userRepository.GetAsync(email);

            if (user != null)
            {
                throw new Exception($"User with e-mail '{email}' already exist!");
            }

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

            user = new User(userId, email, hash, salt, firstName, lastName, role);

            await userRepository.AddAsync(user);
        }
Esempio n. 26
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;
        }
        public async Task Login(LoginViewModel model)
        {
            var user = await _userRepo.GetUserByEmailAsync(model.Email);

            if (user == null)
            {
                throw new Exception("Użytkownik nie istnieje");
            }

            var userInRoles = user.UserInRoles;
            var roles       = new List <Role>();

            foreach (var item in userInRoles)
            {
                var role = await _roleRepo.GetRoleByIdAsync(item.RoleId);

                roles.Add(role);
            }

            var hash      = _encrypter.GetHash(model.Password, user.Salt);
            var tokenTemp = _jwtHandler.CreateToken(user.UserId.ToString(), roles);

            if (user.Password == hash)
            {
                _cache.SetJwt(model.TokenId, tokenTemp);
            }
        }
Esempio n. 28
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);
        }
Esempio n. 29
0
        public bool ValidatePassword(string password, IEncrypter encrypter)
        {
            var hashedPassword = encrypter.GetHash(password, Salt);
            var areEqual       = Password.Equals(hashedPassword);

            return(areEqual);
        }
Esempio n. 30
0
        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;
        }