Example #1
0
        public bool Authorize(string email, string password)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                MessageBox.Show("User email cannot be empty");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("User password cannot be empty");
                return(false);
            }
            password = PasswordHelpers.GetHash(password);
            var user = context.Users.FirstOrDefault(u => u.Email == email && u.Password == password);

            if (user != null)
            {
                AuthorizedUser = user;
                if (AuthorizedUser.Favourites == null)
                {
                    AuthorizedUser.Favourites = new List <Favourite>();
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #2
0
        public async Task <JsonResult> Get()
        {
            var dbUser = await _dbContext.GetUserAsync(User.Identity.Name)
                         .ConfigureAwait(false);

            var IV = dbUser.IV;

            var firstName  = PasswordHelpers.DecryptData(dbUser.FirstName, IV);
            var surName    = PasswordHelpers.DecryptData(dbUser.Surname, IV);
            var middleName = string.IsNullOrEmpty(dbUser.MiddleName) ? string.Empty : PasswordHelpers.DecryptData(dbUser.MiddleName, IV);
            var birthDate  = string.IsNullOrEmpty(dbUser.BirthDate) ? string.Empty : PasswordHelpers.DecryptData(dbUser.BirthDate, IV);
            var city       = string.IsNullOrEmpty(dbUser.City) ? string.Empty : PasswordHelpers.DecryptData(dbUser.City, IV);
            var email      = PasswordHelpers.DecryptData(dbUser.Email, IV);

            var user = new
            {
                dbUser.Id,
                dbUser.Login,
                FirstName  = firstName,
                Surname    = surName,
                MiddleName = middleName,
                BirthDate  = birthDate,
                City       = city,
                Email      = email
            };

            return(new JsonResult(new MypageGetResponse
            {
                user = user
            }, _jsonOptions));
        }
Example #3
0
        public bool ValidateUsernameAndPassword(string username, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return(false);
            }

            var user = FindUserByUsername(username);

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

            var currentPassword = PasswordHelpers.DerivePasswordFromPasswordHash(user.Password);
            var currentSalt     = PasswordHelpers.DeriveSaltFromPasswordHash(user.Password);

            if (currentPassword == null || currentSalt == null)
            {
                return(false);
            }

            var providedPasswordHash = PasswordHelpers.HashPassword(password, currentSalt);

            if (user.Password.Length != providedPasswordHash.Length)
            {
                return(false);
            }

            return(providedPasswordHash.SequenceEqual(user.Password));
        }
Example #4
0
        public User Create(User user, string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ApplicationException(Properties.resultMessages.PasswordNull);
            }

            if (string.IsNullOrWhiteSpace(user.Username))
            {
                throw new ApplicationException(Properties.resultMessages.UsernameNull);
            }

            if (_context.Users.Any(x => x.Username == user.Username))
            {
                throw new ApplicationException(Properties.resultMessages.UsernameExists);
            }

            user.Id = 0;

            byte[] passwordHash, passwordSalt;
            PasswordHelpers.CreatePasswordHash(password, out passwordHash, out passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            _context.Users.Add(user);
            _context.SaveChanges();

            return(user);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var account = await ServiceLocator.Current.Get <IAccountManager>().GetByEmail(context.UserName);

                if (account == null || !account.IsActive || !PasswordHelpers.VerifyPassword(account.Password, context.Password))
                {
                    context.Response.Headers.Add("BadRequestHeader", new[] { "Incorrect username or password." });
                    return;
                }

                if (account.IsBlocked)
                {
                    context.Response.Headers.Add("BadRequestHeader", new[] { "User blocked" });
                    return;
                }
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, account.Id.ToString(CultureInfo.InvariantCulture)));

                var properties = new AuthenticationProperties(GenerateClaims(account));

                context.Validated(new AuthenticationTicket(identity, properties));
                context.Request.Context.Authentication.SignIn(properties, identity);
            }
            catch (Exception ex)
            {
                context.SetError(ex.Message);
            }
        }
Example #6
0
        public async Task Update(User userParam, string password = null)
        {
            var user = await _context.Users.SingleOrDefaultAsync(x => x.Id == userParam.Id);

            if (user == null)
            {
                throw new ApplicationException(Properties.resultMessages.UserNotFound);
            }

            if (userParam.Username != user.Username)
            {
                if (await _context.Users.AnyAsync(x => x.Username == userParam.Username))
                {
                    throw new ApplicationException(Properties.resultMessages.UsernameExists);
                }
            }

            user.Username = userParam.Username;

            if (!string.IsNullOrWhiteSpace(password))
            {
                PasswordHelpers.CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);

                user.PasswordHash = passwordHash;
                user.PasswordSalt = passwordSalt;
            }

            _context.Users.Update(user);
            await _context.SaveChangesAsync();
        }
Example #7
0
        public Room Create(Room room, string password)
        {
            if (string.IsNullOrWhiteSpace(room.Title))
            {
                throw new ApplicationException(Properties.resultMessages.TitleNull);
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ApplicationException(Properties.resultMessages.PasswordNull);
            }

            room.Id = 0;

            byte[] passwordHash, passwordSalt;
            PasswordHelpers.CreatePasswordHash(password, out passwordHash, out passwordSalt);

            room.PasswordHash = passwordHash;
            room.PasswordSalt = passwordSalt;

            _context.Rooms.Add(room);
            _context.SaveChanges();

            return(room);
        }
Example #8
0
        public async Task <bool> SendEmailAsync(int id, int clientId, int userId)
        {
            if (!await _permissionManager.HasPermission(clientId, userId, Permission.CanDeleteUser))
            {
                throw new Exception("User has not permission to perform this operation");
            }

            var user = await _usersRepository.GetUserByIdAsync(id);

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

            var newPassword = Guid.NewGuid().ToString().Substring(1, 6);

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(newPassword, out salt, out passwordHash);

            await _usersRepository.ChangePasswordAsync(user.Id, passwordHash, salt);

            var message = "Hi " + user.FirstName + " " + user.LastName + ",<br><br>" +
                          "Your username is <b>" + user.Email + "</b> and new password is <b>" + newPassword + "</b>." +
                          "<br><br><br>Thanks<br>COH Team";

            EmailService.SendEmail("*****@*****.**", user.Email, "COH Credential Info", message);

            return(true);
        }
Example #9
0
        public async Task <bool> ForgotPasswordAsync(string email)
        {
            var user = _usersRepository.GetUserByEmail(email);

            if (user == null || !user.IsActive)
            {
                throw new Exception("User does not exists");
            }

            var newPassword = Guid.NewGuid().ToString().Substring(1, 6);

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(newPassword, out salt, out passwordHash);

            await _usersRepository.ChangePasswordAsync(user.Id, passwordHash, salt);

            var message = "Hi " + user.FirstName + " " + user.LastName + ",<br><br>" +
                          "Your username is <b>" + user.Email + "</b> and new password is <b>" + newPassword + "</b>." +
                          "<br><br><br>Thanks<br>COH Team";

            EmailService.SendEmail("*****@*****.**", user.Email, "Reset password for COH", message);

            return(true);
        }
Example #10
0
        public async Task <bool> ChangePasswordAsync(string oldPassword, string newPassword, int userId)
        {
            var existing = await _usersRepository.GetUserByIdAsync(userId);

            if (existing == null)
            {
                throw new Exception("User does not exists");
            }

            if (PasswordHelpers.GenerateHashForSaltAndPassword(existing.Salt, oldPassword) != existing.PasswordHash)
            {
                throw new Exception("Old password is not valid");
            }

            if (!PasswordHelpers.IsValidPassword(newPassword, new PasswordRequirements()))
            {
                throw new Exception("Password doesn't meet requirements");
            }

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(newPassword, out salt, out passwordHash);

            return(await _usersRepository.ChangePasswordAsync(userId, passwordHash, salt));
        }
        public override Task <int> AddAsync(UserModel model)
        {
            model.Password = PasswordHelpers.HashPassword(model.Password);
            var resultId = base.AddAsync(model);

            model.Password = string.Empty;
            return(resultId);
        }
Example #12
0
        internal async Task <bool> VerifyPassword(COHUserStore store, COHApplicationUser user, string password)
        {
            var hash = await store.GetPasswordHashAsync(user);

            var verify = PasswordHelpers.GenerateHashForSaltAndPassword(user.Salt, password);

            return(hash == verify);
        }
        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 #14
0
        public static AppUser New(string password)
        {
            string salt;
            string hash = PasswordHelpers.HashPassword(password, out salt);

            return(new AppUser()
            {
                PasswordHash = hash,
                PasswordSalt = salt,
                Id = Guid.NewGuid().ToString()
            });
        }
Example #15
0
        public async Task Update_ValidParams_DataUpdated()
        {
            CreateEntities(out List <User> users);
            var    userService = CreateService(users);
            var    user        = users.SingleOrDefault(x => x.Id == 101);
            string newPassword = "******";

            await userService.Update(user, newPassword);

            var result = users.SingleOrDefault(x => x.Id == 101);

            Assert.True(PasswordHelpers.VerifyPasswordHash("newPassword101", result.PasswordHash, result.PasswordSalt));
        }
        public void VerifyPasswordHash_Test(string inputPassword, bool expectedResult)
        {
            // Arrange
            const string rightPassword = "******";
            var          rightSalt     = UTF8.GetBytes("SomePasswordSalt");
            var          passwordHash  = new HMACSHA512(rightSalt).ComputeHash(UTF8.GetBytes(rightPassword));

            // Act
            var result = PasswordHelpers.VerifyPasswordHash(inputPassword, passwordHash, rightSalt);

            // Assert
            Assert.Equal(expectedResult, result);
        }
        public void CreatePasswordHash_Test()
        {
            // Arrange
            const string password = "******";

            // Act
            var(passwordHashResult, passwordSaltResult) = PasswordHelpers.CreatePasswordHash(password);

            // Assert
            var expectedPasswordHash = new HMACSHA512(passwordSaltResult).ComputeHash(UTF8.GetBytes(password));

            Assert.Equal(expectedPasswordHash, passwordHashResult);
        }
Example #18
0
        public async Task <JsonResult> SignUp([FromBody] SignUpModel model)
        {
            var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.Login)
                         .ConfigureAwait(false);

            if (dbUser != null)
            {
                throw new Exception("Пользователь с таким логином уже существует");
            }

            // Хешируем пароли
            var salt = PasswordHelpers.GenerateSalt();
            var hash = PasswordHelpers.EncryptPassword(model.Pass, salt);

            // Шифруем личные данные
            var IV         = PasswordHelpers.GetIV();
            var firstName  = PasswordHelpers.EncryptData(model.FirstName, IV);
            var surName    = PasswordHelpers.EncryptData(model.Surname, IV);
            var email      = PasswordHelpers.EncryptData(model.Email, IV);
            var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : PasswordHelpers.EncryptData(model.MiddleName, IV);
            var birthdate  = string.IsNullOrEmpty(model.BirthDate) ? null : PasswordHelpers.EncryptData(model.BirthDate, IV);
            var city       = string.IsNullOrEmpty(model.City) ? null : PasswordHelpers.EncryptData(model.City, IV);

            var user = new User
            {
                Login = model.Login,
                Pass  = new Pass
                {
                    Password = hash,
                    Salt     = salt
                },
                IV         = IV,
                FirstName  = firstName,
                Surname    = surName,
                MiddleName = middleName,
                City       = city,
                BirthDate  = birthdate,
                Email      = email
            };

            await _dbContext.AddAsync(user)
            .ConfigureAwait(false);

            await _dbContext.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new OkResponse
            {
                message = "Регистрация пройдена успешно"
            }));
        }
Example #19
0
        public async Task <ClientModel> AddAsync(ClientModel model, int userId)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }

            var client = _clientMapper.ConvertToDataModel(model);

            client.IsActive  = true;
            client.CreatedOn = DateTime.UtcNow;
            client.UpdatedOn = DateTime.UtcNow;

            client.Application = new Application()
            {
                Name         = client.OrganizationName + "Mobile App",
                ClientId     = Guid.NewGuid(),
                ClientSecret = Guid.NewGuid(),
                Scope        = "mobile",
                CreatedOn    = DateTime.UtcNow,
                UpdatedOn    = DateTime.UtcNow
            };

            var clientAdmin = new User()
            {
                FirstName = "Client",
                LastName  = "Admin",
                Email     = client.Email,
                Role      = (int)UserRoles.ClientAdmin,
                IsActive  = true,
                CreatedOn = DateTime.UtcNow,
                UpdatedOn = DateTime.UtcNow
            };

            var password = Guid.NewGuid().ToString().Substring(1, 6);

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(password, out salt, out passwordHash);

            clientAdmin.Salt         = salt;
            clientAdmin.PasswordHash = passwordHash;

            client.Users.Add(clientAdmin);

            client = await _clientRepository.AddAsync(client);

            return(_clientMapper.ConvertToModel(client));
        }
Example #20
0
        public async Task <UserModel> AddAsync(UserModel model, string password, int clientId, int userId)
        {
            if (!await _permissionManager.HasPermission(clientId, userId, Permission.CanAddUser))
            {
                throw new Exception("User has not permission to perform this operation");
            }

            var existing = _usersRepository.GetUserByEmail(model.Email);

            if (existing != null)
            {
                throw new Exception("Email already exists");
                //errors = "Email already exists";
                //return new EnumerableQuery<MonsciergeDataModel.User>(new MonsciergeDataModel.User[0]);
            }

            if (!PasswordHelpers.IsValidPassword(password, new PasswordRequirements()))
            {
                throw new Exception("Password doesn't meet requirements");
                //errors = "Password doesn't meet requirements";
                //return new EnumerableQuery<MonsciergeDataModel.User>(new MonsciergeDataModel.User[0]);
            }

            var user = new User()
            {
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Email     = model.Email,
                ClientId  = clientId,
                Role      = (int)UserRoles.HRUser,
                IsActive  = true,
                CreatedOn = DateTime.UtcNow,
                UpdatedOn = DateTime.UtcNow
            };

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(password, out salt, out passwordHash);

            user.Salt         = salt;
            user.PasswordHash = passwordHash;

            user = await _usersRepository.AddAsync(user);

            return(_usersMapper.ConvertToModel(user));
        }
Example #21
0
        public bool RegisterUser(string name, string lastname, string email, string password)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                MessageBox.Show("User name cannot be empty");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(lastname))
            {
                MessageBox.Show("User lastname cannot be empty");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(email))
            {
                MessageBox.Show("User email cannot be empty");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(PasswordHelpers.GetHash(password)))
            {
                MessageBox.Show("User password cannot be empty");
                return(false);
            }


            if (context.Users.FirstOrDefault(u => u.Email == email) == null)
            {
                var user = new User()
                {
                    Name       = name,
                    LastName   = lastname,
                    Email      = email,
                    Password   = PasswordHelpers.GetHash(password),
                    Favourites = new List <Favourite>()
                };
                Users.Add(user);
                context.Users.Add(user);
                context.SaveChanges();
                _repo = GetJsRepository();
                _repo.Users.Add(user);
                _repo.Save();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #22
0
        public Room Authenticate(int id, string password)
        {
            var room = _context.Rooms
                       .Include(x => x.RoomUsers)
                       .SingleOrDefault(x => x.Id == id);

            if (room == null)
            {
                throw new ApplicationException(Properties.resultMessages.RoomNotFound);
            }

            if (!PasswordHelpers.VerifyPasswordHash(password, room.PasswordHash, room.PasswordSalt))
            {
                throw new ApplicationException(Properties.resultMessages.CredentialsInvalid);
            }

            return(room);
        }
        private void ButtonRegister_Click(object sender, RoutedEventArgs e)
        {
            var user = new User {
                Name     = textBoxName.Text,
                Email    = textBoxEmail.Text,
                Login    = textBoxLogin.Text,
                Password = PasswordHelpers.GetHash(passwordBox.Password)
            };

            try {
                _repo.RegisterUser(user);
                RegistrationFinished?.Invoke();
                Close();
            }
            catch {
                MessageBox.Show("An error occured trying to save new user");
            }
        }
        public User AuthenticateUser(UserLoginDto userLoginDto)
        {
            var user = _context.Users.SingleOrDefault(x => x.Username == userLoginDto.Username);

            // check if the username exists
            if (user == null)
            {
                return(null);
            }

            // check if the password is correct
            if (!PasswordHelpers.VerifyPasswordHash(userLoginDto.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(null);
            }

            return(user);
        }
Example #25
0
        public void Authenticate_NullOrWhiteSpacesCredentials_ThrowsCredentialsInvalidError(string username, string password)
        {
            PasswordHelpers.CreatePasswordHash("password123", out byte[] passwordHash, out byte[] passwordSalt);
            var users = new List <User> {
                new User()
                {
                    Id           = 1,
                    Username     = "******",
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt
                }
            };
            var userService = CreateService(users);

            var exception = Assert.Throws <ApplicationException>(
                () => userService.Authenticate(username, password));

            Assert.Equal(DiceApi.Properties.resultMessages.CredentialsInvalid, exception.Message);
        }
Example #26
0
        public void Authenticate_ValidObject_ReturnsUser()
        {
            PasswordHelpers.CreatePasswordHash("password123", out byte[] passwordHash, out byte[] passwordSalt);
            var users = new List <User> {
                new User()
                {
                    Id           = 1,
                    Username     = "******",
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt
                }
            };
            var    userService = CreateService(users);
            string username    = "******";
            string password    = "******";

            var result = userService.Authenticate(username, password);

            Assert.IsType <User>(result);
        }
        public void Authenticate_NullOrWhiteSpacesPassoword_ThrowsCredentialsInvalidError(string password)
        {
            PasswordHelpers.CreatePasswordHash("password123", out byte[] passwordHash, out byte[] passwordSalt);
            var rooms = new List <Room> {
                new Room()
                {
                    Id           = 1,
                    Title        = "Room123",
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt
                }
            };
            var roomService = CreateService(rooms);
            int id          = 1;

            var exception = Assert.Throws <ApplicationException>(
                () => roomService.Authenticate(id, password));

            Assert.Equal(DiceApi.Properties.resultMessages.CredentialsInvalid, exception.Message);
        }
        public void Authenticate_ValidObjectPassed_ReturnsRoom()
        {
            PasswordHelpers.CreatePasswordHash("password123", out byte[] passwordHash, out byte[] passwordSalt);
            var rooms = new List <Room> {
                new Room()
                {
                    Id           = 1,
                    Title        = "Room123",
                    PasswordHash = passwordHash,
                    PasswordSalt = passwordSalt
                }
            };
            var    roomService = CreateService(rooms);
            int    id          = 1;
            string password    = "******";

            var result = roomService.Authenticate(id, password);

            Assert.IsType <Room>(result);
        }
Example #29
0
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            try
            {
                User user = service.GetUserByID(Guid.Parse(model.UserID));
                user.Password           = PasswordHelpers.EncryptPassword(model.NewPassword);
                user.ForgotPasswordHash = null;

                service.Save(user);

                //this.StoreSuccess("Your password has been updated, you can now login!");

                return(RedirectToAction("login"));
            }
            catch (Exception ex)
            {
                //this.StoreError("There was a problem updating your password");
                return(View());
            }
        }
        public User RegisterUser(UserRegisterDto userRegisterDto)
        {
            if (_context.Users.Any(x => x.Username == userRegisterDto.Username))
            {
                throw new AppException("Username \"" + userRegisterDto.Username + "\" is already taken");
            }

            byte[] passwordHash, passwordSalt;
            PasswordHelpers.CreatePasswordHash(userRegisterDto.Password, out passwordHash, out passwordSalt);

            var user = _mapper.Map <User>(userRegisterDto);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            _context.Users.Add(user);
            _context.SaveChanges();

            return(user);
        }