Hash() public static method

Creates a hash from a password with 10000 iterations
public static Hash ( string password ) : string
password string the password
return string
Example #1
0
        public async Task SecurePasswordHasher_test()
        {
            var hash = SecurePasswordHasher.Hash("2324");
            var v    = SecurePasswordHasher.Verify("2324", hash);

            v.ShouldBeTrue();
        }
        public ActionResult RegisterUser(User user)
        {
            user = new User();
            var hash = SecurePasswordHasher.Hash(Request["Password"]);

            // user.ConfirmPassword = hash;
            user.Email       = Request["Email"];
            user.HouseNo     = Request["HouseNo"];
            user.DateOfBirth = Request["DateOfBirth"].AsDateTime();
            user.ZipCode     = Request["ZipCode"];
            user.Name        = Request["Name"];
            user.Surname     = Request["SurName"];
            user.Password    = hash;
            user.UserRole    = "User";
            user.JoinDate    = DateTime.Today;

            //  bool test = Equals(user.Password, user.ConfirmPassword);
            if (ModelState.IsValid)
            {
                db.Configuration.ValidateOnSaveEnabled = false;
                //       user.ConfirmPassword = user.Password;
                db.Users.Add(user);
                db.SaveChanges();
                db.Configuration.ValidateOnSaveEnabled = true;
                Session["isAdmin"]  = "0";
                Session["UserName"] = "******" + user.Name;
                Session["UserId"]   = user.UserId.ToString();
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
        public void ToUserToDbDtov1_Test()
        {
            var user = new User
            {
                Id        = 1,
                FirstName = "John",
                LastName  = "Wick",
                Email     = "*****@*****.**",
                Password  = SecurePasswordHasher.Hash("Moynahan"),
                Token     = null,
                Role      = UserRole.MANAGER
            };

            var userToDbDto = user.ToUserToDbDto();

            Assert.Equal(user.Id, userToDbDto.Id);
            Assert.Equal(user.FirstName, AesService.DecryptStringFromBytes_Aes(userToDbDto.FirstName));
            Assert.Equal(user.LastName, AesService.DecryptStringFromBytes_Aes(userToDbDto.LastName));
            Assert.Equal(user.Email, AesService.DecryptStringFromBytes_Aes(userToDbDto.Email));
            Assert.Equal(user.Password, AesService.DecryptStringFromBytes_Aes(userToDbDto.Password));
            if (user.Token != null)
            {
                Assert.Equal(user.Token, AesService.DecryptStringFromBytes_Aes(userToDbDto.Token));
            }
            Assert.Equal(user.Role, userToDbDto.Role);
        }
        // Method that add Admin to database
        public void AddAdmin(vwAdmin admin)
        {
            try
            {
                using (CompanyDBEntities context = new CompanyDBEntities())
                {
                    tblUser  newUser  = new tblUser();
                    tblAdmin newAdmin = new tblAdmin();
                    newUser.FirstName      = admin.FirstName;
                    newUser.LastName       = admin.LastName;
                    newUser.JMBG           = admin.JMBG;
                    newUser.Gender         = admin.Gender;
                    newUser.Residence      = admin.Residence;
                    newUser.MarriageStatus = admin.MarriageStatus;
                    newUser.Username       = admin.Username;
                    newUser.UserPassword   = SecurePasswordHasher.Hash(admin.UserPassword);

                    context.tblUsers.Add(newUser);
                    context.SaveChanges();
                    admin.UserID = newUser.UserID;

                    newAdmin.UserID         = admin.UserID;
                    newAdmin.ExpirationDate = DateTime.Now.AddDays(7);
                    newAdmin.AdminType      = admin.AdminType;

                    context.tblAdmins.Add(newAdmin);
                    context.SaveChanges();
                    admin.AdminID = newAdmin.AdminID;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception" + ex.Message.ToString());
            }
        }
Example #5
0
        public bool CreateUser(string username, string password)
        {
            var             hash   = SecurePasswordHasher.Hash(password);
            OperationResult result = accountRepository.CreateUser(username, hash);

            return(result.Succeded);
        }
        public void Post([FromBody] JObject data)
        {
            string apiKeyData       = Request.Headers["Authorization"];
            string sessionData      = Request.Headers["User-Authentication"];
            string timeStamp        = Request.Headers["Timestamp"];
            int    gradeRestriction = 0;

            if (security.IsAuthorised(timeStamp, apiKeyData, sessionData, gradeRestriction))
            {
                User user = data["User"].ToObject <User>();

                if (user == null)
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
                user.Password = SecurePasswordHasher.Hash(user.Password);

                try
                {
                    TicketDb.UserAdd(user.Username, user.Password, user.Email, user.FirstName, user.LastName, user.City, user.ZipCode, user.Address, user.Grade);
                }
                catch
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
            }
            else
            {
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
        }
Example #7
0
//        public IEnumerable<User> GetUser()
//        {
//            return _context.Users;
//        }
        /// <summary>
        /// create user
        /// </summary>
        /// <param name="user">UserViewsModels</param>
        /// <returns>true || false</returns>
        public async Task <bool> AddUserAsync(UserViewsModels user)
        {
            try
            {
                var users = new User()
                {
                    Name      = user.Name,
                    Email     = user.Email,
                    PassWord  = SecurePasswordHasher.Hash(user.PassWord),
                    Phone     = user.Phone,
                    StoreId   = user.StoreId,
                    Role      = Convert.ToInt32(user.Role),
                    IsActiver = user.IsActiver
                };

                await _context.Users.AddAsync(users);

                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Log.Error("Add User Async Error: {0}", e.Message);
                return(false);
            }
        }
Example #8
0
        public bool RegisterPlayer(string username, string password, PlayerConnection connection)
        {
            password = SecurePasswordHasher.Hash(password);

            if (_playerDataManager.Exists(new PlayerDataArguments(username)))
            {
                var packet = new Packet(PacketType.LOGIN_FAIL, ChannelType.UNASSIGNED);
                packet.Message.Write("Account already exists!");
                connection.SendPacket(packet, NetDeliveryMethod.Unreliable);
                connection.Disconnect("byeFelicia");

                return(false);
            }

            // Create their player.
            var descriptor = PlayerDescriptor.Create(username, password);

            descriptor.MapID = Settings.StartingMap;
            descriptor.Role  = Settings.DefaultRole;
            var player = new Player(descriptor, connection);

            _playerDataManager.Save(player.Descriptor, null);

            this.AddPlayer(player);

            // Notify them that they successfully registered.
            var successPacket = new Packet(PacketType.REGISTER_SUCCESS, ChannelType.UNASSIGNED);

            player.NetworkComponent.SendPacket(successPacket, NetDeliveryMethod.Unreliable);

            return(true);
        }
Example #9
0
        public void Update(User userParam, string password = null, string passwordOld = null)
        {
            var user = _context.Users.Find(userParam.Iduser);

            if (user == null)
            {
                throw new ApplicationException("User not found");
            }

            // update mail if it has changed
            if (!string.IsNullOrWhiteSpace(userParam.Email) && userParam.Email != user.Email)
            {
                // throw error if the new mail is already taken
                if (_context.Users.Any(x => x.Email == userParam.Email))
                {
                    throw new ApplicationException("Email " + userParam.Email + " is already taken");
                }

                user.Email = userParam.Email;
            }

            // update user properties if provided
            if (!string.IsNullOrWhiteSpace(userParam.FirstName))
            {
                user.FirstName = userParam.FirstName;
            }

            if (!string.IsNullOrWhiteSpace(userParam.LastName))
            {
                user.LastName = userParam.LastName;
            }

            if (userParam.GetType().GetProperty("CityId") != null)
            {
                user.CityId = userParam.CityId;
            }

            if (userParam.GenderId == 1 || userParam.GenderId == 2)
            {
                user.GenderId = userParam.GenderId;
            }

            // update password if provided
            if (!string.IsNullOrWhiteSpace(password) && !string.IsNullOrEmpty(passwordOld))
            {
                if (SecurePasswordHasher.Verify(password, System.Text.Encoding.UTF8.GetString(user.PasswordHash)))
                {
                    byte[] passwordHash = System.Text.Encoding.UTF8.GetBytes(SecurePasswordHasher.Hash(password));
                    user.PasswordHash = passwordHash;
                }
                else
                {
                    throw new ApplicationException("Incorrect old password");
                }
            }

            _context.Users.Update(user);
            _context.SaveChanges();
        }
        public ActionResult Login(User user)
        {
            using (var context = new LibraryContext())
            {
                User user1 = new User();

                //int x = context.Users.Count();
                string email = Request["Email"];

                string password = Request["Password"];
                // db.Configuration.ValidateOnSaveEnabled = false;
                // user1.ConfirmPassword = password;
                if (email == "" || password == "")
                {
                    return(View("Error"));
                }

                if (context.Users.Where(a => a.Email == email).Count() > 0)
                {
                    user1 = context.Users.Where(a => a.Email == email).Single();
                }
                else
                {
                    return(View("Error"));
                }
                ;//error because confirm password doesn't match
                 //db.Configuration.ValidateOnSaveEnabled = true;

                string hash = SecurePasswordHasher.Hash(password);

                bool result = SecurePasswordHasher.Verify(password, user1.Password);
                if (context.Users.Where(a => a.Email == email).Count() > 0 && result == true)
                {
                    user = context.Users.Find(1);

                    user1 = context.Users.Where(a => a.Email == email).Single();
                    if (user1.UserRole == "Admin")
                    {
                        Session["isAdmin"]  = "1";
                        Session["UserId"]   = user1.UserId.ToString();
                        Session["UserName"] = "******" + user.Name;
                    }
                    else
                    {
                        Session["isAdmin"]  = "0";
                        Session["UserName"] = "******" + user.Name;
                        Session["UserId"]   = user1.UserId.ToString();
                    }
                    return(Redirect("/Home/Index"));
                }
                else
                {
                    Response.Redirect("/home/login", true);
                    Response.End();
                }

                return(View("Error"));
            }
        }
 public User(string name, string email, string password, EUserProfile profile = EUserProfile.User, bool active = true)
 {
     Name     = name;
     Email    = email;
     Password = !SecurePasswordHasher.IsHashSupported(password) ? SecurePasswordHasher.Hash(password) : password;
     Profile  = profile;
     Active   = active;
 }
Example #12
0
 public async Task <CustomerModel> EditProfile(CustomerModel data)
 {
     if (!SecurePasswordHasher.IsHashSupported(data.Password = SecurePasswordHasher.Hash(data.Password)))
     {
         data.Password = SecurePasswordHasher.Hash(data.Password);
     }
     return(await _api.PutAsync($"/customers/{data.ID}", data));
 }
Example #13
0
        public async Task <UserModel> SignUp(UserModel data)
        {
            data.Password = SecurePasswordHasher.Hash(data.Password);
            var newUser = await _mediator.Send(new CreateUserCommand(data));

            HttpContext.Session.Set(SessionHelper.CLAIM_ID, newUser.ID);
            return(newUser);
        }
Example #14
0
 /// <summary>
 /// Default profile constructor
 /// </summary>
 /// <param name="name">Profile name</param>
 /// <param name="password">Profile password</param>
 /// <param name="recoveryCode">Generated recovery code</param>
 public Profile(string name, string password, string recoveryCode)
 {
     Id                    = Guid.NewGuid();
     Name                  = name;
     PasswordHash          = SecurePasswordHasher.Hash(password);
     RecoveryCodeHash      = SecurePasswordHasher.Hash(recoveryCode);
     EncryptedRecoveryCode = Convert.ToBase64String(Cryptography.Encrypt(Encoding.UTF8.GetBytes(password), recoveryCode));
 }
Example #15
0
        public ActionResult ResetPassword(FormCollection collection)
        {
            foreach (string element in collection)
            {
                if (collection[element] == "")
                {
                    return(RedirectToAction("ResetPassword", "Home", new { message = "FillAll" }));//If one form is empty
                }
            }
            MongoHelper.ConnectToMongo();
            MongoHelper.recovery_collection =
                MongoHelper.database.GetCollection <AccountRecovery>("AccountRecovery");
            MongoHelper.users_collection =
                MongoHelper.database.GetCollection <User>("Users");
            var filter = Builders <AccountRecovery> .Filter.Eq("_id", collection["ID"]);//Finds the Account Recovery Info and the account related to it

            var result = MongoHelper.recovery_collection.Find(filter).FirstOrDefault();

            if (result != null)
            {
                if (SecurePasswordHasher.Verify(collection["Token"], result.token))
                {
                    if (result.expirationDateTime < DateTime.UtcNow)//MongoDB stores in UTC Time, therefore using DateTime.UtcNow will compare it in real time
                    {
                        return(RedirectToAction("ResetPassword", "Home", new { message = "TokenExpiration" }));
                    }
                    else
                    {
                        if (string.Equals(collection["Password"], collection["ConfirmPassword"]))//Passwords Match
                        {
                            var userFilter = Builders <User> .Filter.Eq("_id", result.accountID);

                            var userResult = MongoHelper.users_collection.Find(userFilter).FirstOrDefault();
                            if (userResult != null)
                            {
                                var update = Builders <User> .Update.Set("Password", SecurePasswordHasher.Hash(collection["Password"]));//Replaces password with a new one

                                MongoHelper.users_collection.UpdateOne(userFilter, update);
                            }
                            MongoHelper.recovery_collection.DeleteOneAsync(filter);//Delete Token
                            return(RedirectToAction("ResetPassword", "Home", new { message = "Success" }));
                        }
                        else
                        {
                            return(RedirectToAction("ResetPassword", "Home", new { message = "PasswordMismatch" }));
                        }
                    }
                }
                else
                {
                    return(RedirectToAction("ResetPassword", "Home", new { message = "TokenMismatch" }));
                }
            }
            else
            {
                return(RedirectToAction("ResetPassword", "Home", new { message = "Error" }));
            }
        }
Example #16
0
        private void SaveButton_Click1(object sender, RoutedEventArgs e)
        {
            dbman = new DBConnectionManager();

            string uid          = Application.Current.Resources["uid"].ToString();
            string old_pass_key = CurrentPassword.Password;
            string pass_key     = SecurePasswordHasher.Hash(NewPassword1.Password);

            if (NewPassword1.Password == NewPassword2.Password)
            {
                if (dbman.DBConnect().State == ConnectionState.Open)
                {
                    MySqlCommand cmd = dbman.DBConnect().CreateCommand();
                    cmd.CommandText = "SELECT * FROM accounts WHERE account_id = @uid LIMIT 1;";
                    cmd.Parameters.AddWithValue("@uid", uid);
                    MySqlDataReader db_reader = cmd.ExecuteReader();
                    while (db_reader.Read())
                    {
                        if (SecurePasswordHasher.Verify(old_pass_key, db_reader.GetString("pass_key")) == true)
                        {
                            //TODO
                            try
                            {
                                MySqlCommand cmd2 = dbman.DBConnect().CreateCommand();
                                cmd2.CommandText =
                                    "UPDATE accounts SET pass_key = @pass_key WHERE account_id = @account_id;";
                                cmd2.Prepare();
                                cmd2.Parameters.AddWithValue("@account_id", uid);
                                cmd2.Parameters.AddWithValue("@pass_key", pass_key);
                                int stat_code = cmd2.ExecuteNonQuery();
                                //string tmp = pmsutil.LogRecord(recordID, "LOGC-02");
                                InfoArea1.Foreground = new SolidColorBrush(Colors.Green);
                                InfoArea1.Content    = "Password successfully changed!";
                            }
                            catch (MySqlException ex)
                            {
                                Console.WriteLine("Error: {0}", ex.ToString());
                            }
                        }
                        else
                        {
                            InfoArea1.Foreground = new SolidColorBrush(Colors.Red);
                            InfoArea1.Content    = "Password does not match! Please check your inputs and try again.";
                        }
                    }
                    //close Connection
                    dbman.DBClose();
                }
                else
                {
                }
            }
            else
            {
                InfoArea1.Foreground = new SolidColorBrush(Colors.Red);
                InfoArea1.Content    = "Password does not match! Please check your inputs and try again.";
            }
        }
Example #17
0
 public void CreateAdmin()
 {
     UnitOfWorkRepository UnitOfWork = new UnitOfWorkRepository();
     var   hash  = SecurePasswordHasher.Hash("Pieter123");
     Admin admin = new Admin {
         Id = Guid.NewGuid(), Name = "Pieter", EmailAddress = "*****@*****.**", Password = hash
     };
     //UnitOfWork.AdminRepository.Add(admin);
 }
        private void OnOk(object parameter)
        {
            if (EditPersonalDetails.Password1 != EditPersonalDetails.Password2)
            {
                OneButtonScreen.ShowMessage("פרט שגוי", "הססמאות אינן זהות");
                return;
            }

            if (!(EditPersonalDetails.Address.Length > 0 &&
                  EditPersonalDetails.Phone.Length > 0 &&
                  EditPersonalDetails.FirstName.Length > 0 &&
                  EditPersonalDetails.LastName.Length > 0))
            {
                OneButtonScreen.ShowMessage("פרט שגוי", "אחד או יותר מהפרטים שגויים");
                return;
            }

            m_User.address   = EditPersonalDetails.Address;
            m_User.phone     = EditPersonalDetails.Phone;
            m_User.name      = EditPersonalDetails.FirstName;
            m_User.last_name = EditPersonalDetails.LastName;
            if (EditPersonalDetails.Password1.Length > 0)
            {
                m_User.password = SecurePasswordHasher.Hash(EditPersonalDetails.Password1);
            }
            m_User = DataBaseManager.UpdateUser(m_User);

            foreach (var item in EditPersonalDetails.LimitationsList)
            {
                try
                {
                    if (item.HasChanged())
                    {
                        user_ref_limit ul = new user_ref_limit();
                        ul.user_id  = m_User.user_id;
                        ul.limit_id = item.LimitID;
                        ul.Partial  = item.LimitValue == 1;

                        if (item.LimitValue > 0)
                        {
                            DataBaseManager.UpdateUserPreference(ul);
                        }
                        else
                        {
                            DataBaseManager.RemoveUserPreference(ul);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                }
            }

            m_MainWindow.GoToPrevPage();
        }
Example #19
0
 public void Execute(CreateMasterPasswordCommand command)
 {
     using (var db = new PasswordManagerContext()) {
         var mp = db.Settings.Single(x => x.Name == AppSettings.MASTER_PASSWORD_KEY);
         mp.Value = SecurePasswordHasher.Hash(command.Password);
         db.Update(mp);
         db.SaveChanges();
         AppSettings.MasterPassword = command.Password;
     }
 }
Example #20
0
 public bool AddUser(UserModel user)
 {
     if (user.Password == user.ConfirmPassword && user.Password != null)
     {
         user.Password = SecurePasswordHasher.Hash(user.Password);
         Repository.AddUser(user);
         return(true);
     }
     return(false);
 }
Example #21
0
        public bool IsPasswordCorrect(string password)
        {
            return(password == "mega");

            Console.WriteLine("\n\n\n\n\n\n");
            Console.WriteLine("hash");
            Console.WriteLine(SecurePasswordHasher.Hash(password));
            Console.WriteLine("\n\n\n\n\n\n");
            return(SecurePasswordHasher.Verify(password, Hash));
        }
Example #22
0
        /// <summary>
        /// Attempts to create a user account, to check it will update the registerSuccess attribute if it was successful
        /// if not the registerErrorMessage will contain what the problem was.
        /// </summary>
        public void AttemptRegister()
        {
            SanitizeAttributes();

            try
            {
                DatabaseContext context    = HttpContext.RequestServices.GetService(typeof(PastPapers.Models.DatabaseContext)) as DatabaseContext;
                MySqlConnection connection = context.GetConnection();
                connection.Open();
                string       sql = "INSERT INTO users (id, username, password, email) VALUES (DEFAULT, @username, @password, @email)";
                MySqlCommand cmd = new MySqlCommand(sql, connection);
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@username", NewUsername);
                cmd.Parameters.AddWithValue("@password", SecurePasswordHasher.Hash(NewPassword));
                cmd.Parameters.AddWithValue("@email", NewEmail);

                if (cmd.ExecuteNonQuery() == 0)
                {
                    System.Diagnostics.Debug.WriteLine("Account failed to create!");
                    RegisterSuccess = false;
                }
                else
                {
                    /*
                     * var message = new MimeMessage();
                     * message.From.Add(new MailboxAddress("Past Papers", "*****@*****.**"));
                     * message.To.Add(new MailboxAddress(NewUsername, NewEmail));
                     * message.Subject = "Past Papers account verification";
                     *
                     * message.Body = new TextPart("plain")
                     * {
                     *  Text = @"Hey " + NewUsername + ", To activate your new account please click the link below"
                     * };
                     *
                     * using (var client = new SmtpClient())
                     * {
                     *  client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                     *
                     *  client.Connect("smpt", 587, false);
                     *
                     *  client.Send(message);
                     *  client.Disconnect(true);
                     * }
                     */

                    RegisterSuccess = true;
                }

                connection.Close();
            } catch (Exception ex)
            {
                RegisterErrorMessage = "Error connecting to server";
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Example #23
0
        private ReturnData <string> AddToNewMembership(List <Membership> oldMembers, Role bunchRole)
        {         //willy
            try
            {
                var result = _unisolApiProxy.GetEmployees().Result;

                var employees = JsonConvert.DeserializeObject <ReturnData <List <HrpEmployee> > >(result);
                var userGroup = _context.UserGroups.FirstOrDefault(g => g.Role == bunchRole && g.IsDefault && g.Status);
                foreach (var user in oldMembers)
                {
                    if (!_context.Users.Any(u => u.UserName.ToLower().Equals(user.UserName.ToLower())))
                    {
                        var password = user.UserName;
                        if (bunchRole == Role.Staff)
                        {
                            password = employees.Data.FirstOrDefault(e => e.EmpNo.ToLower().Equals(user.UserName.ToLower()))?.Idno ?? "";
                        }

                        _context.Users.Add(new User
                        {
                            AccessFailedCount    = 0,
                            AccountType          = 0,
                            DateCreated          = DateTime.UtcNow,
                            Email                = user.Email,
                            EmailConfirmed       = true,
                            LockoutEnabled       = false,
                            PasswordHash         = SecurePasswordHasher.Hash(password),
                            PhoneNumberConfirmed = false,
                            TwoFactorEnabled     = false,
                            UserName             = user.UserName,
                            Code         = "8a5ef81b-abf8-4f72-9969-6f46f5d441e3",
                            UserGroupsId = userGroup.Id,
                            Status       = true,
                            Role         = bunchRole
                        });

                        _context.SaveChanges();
                    }
                }

                return(new ReturnData <string>
                {
                    Success = true,
                    Message = "Users Imported successfully"
                });
            }
            catch (Exception ex)
            {
                return(new ReturnData <string>
                {
                    Success = false,
                    Message = "Sorry, An error occurred"
                });
            }
        }
        public void SecurePasswordHasherHashShouldReturnHashedPassword()
        {
            // arrange
            var expected = "$MYHASH$";

            // act
            var actual = SecurePasswordHasher.Hash("rob");

            // assert
            actual.Substring(0, 8).Should().BeEquivalentTo(expected);
        }
Example #25
0
        public async Task <IActionResult> PutStaff(int id, [FromForm] Staff staff, IFormFile image)
        {
            if (id != staff.id)
            {
                return(BadRequest());
            }
            staff.password              = SecurePasswordHasher.Hash(staff.password);
            staff.updated_at            = DateTime.Now;
            _context.Entry(staff).State = EntityState.Modified;

            if (image != null)
            {
                string image_name;

                var pImage = _context.images.Where(i => (i.imageable_id == staff.id && i.imageable_type == "Staff")).FirstOrDefault();

                ImagesHelper.delete(pImage.name);

                image_name = ImagesHelper.save(image);

                var local = _context.Set <Image>().Local.FirstOrDefault(i => i.id == pImage.id);

                if (local != null)
                {
                    _context.Entry(local).State = EntityState.Detached;
                }

                _context.Entry(new Image
                {
                    id             = pImage.id,
                    name           = image_name,
                    imageable_id   = staff.id,
                    imageable_type = "Staff"
                }).State = EntityState.Modified;
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StaffExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public DTOResponse <DTOUser> AdminCreate(DTOCreateUser createUserInfo)
        {
            if (string.IsNullOrWhiteSpace(createUserInfo.Email) || string.IsNullOrWhiteSpace(createUserInfo.Password) || string.IsNullOrWhiteSpace(createUserInfo.ConfirmPassword))
            {
                return(new DTOResponse <DTOUser>()
                {
                    Code = 400,
                    Message = "Email, Password and Confirm Password are required!"
                });
            }

            var getUserResponse = GetUserByEmail(createUserInfo.Email);

            if (getUserResponse.Code == 200)
            {
                return(new DTOResponse <DTOUser>()
                {
                    Code = 400,
                    Message = "This user email is already registered!"
                });
            }

            if (createUserInfo.Password != createUserInfo.ConfirmPassword)
            {
                return(new DTOResponse <DTOUser>()
                {
                    Code = 400,
                    Message = "The password and confirm password dont match!"
                });
            }

            createUserInfo.User.Email       = createUserInfo.Email;
            createUserInfo.User.AccessLevel = UserAccessLevel.Admin;

            var userModel = createUserInfo.User.ToModel();

            var passwordHash = SecurePasswordHasher.Hash(createUserInfo.Password);

            userModel.PasswordHash = passwordHash;

            _userCollection.InsertOne(userModel);

            getUserResponse = GetUserByEmail(createUserInfo.Email);

            var existingUser = getUserResponse.Data;

            LoadUserInfo(existingUser);

            return(new DTOResponse <DTOUser>()
            {
                Code = 200,
                Data = existingUser
            });
        }
Example #27
0
        public ActionResult Register(FormCollection collection)
        {
            try
            {
                foreach (string element in collection)
                {
                    if (collection[element] == "")
                    {
                        return(RedirectToAction("Register", "Home", new { message = "FillAll" }));//If a field is empty, return
                    }
                }
                if (string.Equals(collection["Password"], collection["ConfirmPassword"]))//Checks if both given passwords are the same
                {
                    //https://stackoverflow.com/questions/4181198/how-to-hash-a-password/10402129#10402129
                    MongoHelper.ConnectToMongo();
                    MongoHelper.users_collection =
                        MongoHelper.database.GetCollection <User>("Users");

                    //Create Id
                    Object id     = GenerateRandomId(24);
                    var    filter = Builders <User> .Filter.Eq("Email", collection["Email"]);

                    var result = MongoHelper.users_collection.Find(filter).FirstOrDefault();

                    if (result == null)//If no matching email address in db
                    {
                        //Create a hash password
                        var hash = SecurePasswordHasher.Hash(collection["Password"]);
                        //Creates a new User Object
                        MongoHelper.users_collection.InsertOneAsync(new User
                        {
                            _id         = id,
                            Email       = collection["Email"],
                            Username    = collection["Username"],
                            Password    = hash,
                            AdminStatus = new List <Privilege>()
                        });
                        return(RedirectToAction("Register", "Home", new { message = "success" }));
                    }
                    else
                    {
                        return(RedirectToAction("Register", "Home", new { message = "registered" }));
                    }
                }
                else
                {
                    return(RedirectToAction("Register", "Home", new { message = "nonmatch" }));
                }
            }
            catch
            {
                return(RedirectToAction("Register", "Home"));
            }
        }
Example #28
0
        public bool CreateUser(string username, string password)
        {
            //Here must be test if user with the same name in DB already exists.

            var             hash   = SecurePasswordHasher.Hash(password);
            OperationResult result = userRepository.CreateUser(username, hash, roleId: 2);

            userRepository.Dispose();

            return(result.Succeded);
        }
Example #29
0
        public async Task <bool> PasswordRehashAsync(Users entity, string password, bool isNewCreadential = false)
        {
            entity.Password = SecurePasswordHasher.Hash(password);
            if (isNewCreadential)
            {
                entity.AuthUpdatedAt = DateTime.Now;
            }
            _context.Users.Update(entity);
            await _context.SaveChangesAsync();

            return(true);
        }
Example #30
0
 public void Create([FromBody] User userParam)
 {
     Console.WriteLine("check");
     if (!_db.Users.Any(a => a.Username == userParam.Username))
     {
         Console.WriteLine("Check");
         userParam.PasswordHash = SecurePasswordHasher.Hash(userParam.Password, 1000);
         userParam.Password     = null;
         _db.Users.Add(userParam);
         _db.SaveChanges();
     }
 }