Ejemplo n.º 1
0
        /// <inheritdoc />
        /// <summary>
        /// LoginAsync
        /// </summary>
        /// <param name="email">User Email</param>
        /// <param name="password">User Password</param>
        /// <returns>LoginViewModel</returns>
        public async Task <bool> LoginAsync(string email, string password)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                return(false);
            }
            var user = await _context.User.FirstOrDefaultAsync(u =>
                                                               u.Email == email && SecurePasswordHasher.Verify(password, u.Password));

            return(user != null);
        }
Ejemplo n.º 2
0
 public UserDto GetUser(string name, string password)
 {
     foreach (var user in users)
     {
         if (user.Name == name && SecurePasswordHasher.Verify(password, user.Password) == true)
         {
             return(user);
         }
     }
     return(null);
 }
Ejemplo n.º 3
0
        public async Task <UserModel> SignIn(UserModel data)
        {
            var user = await _mediator.Send(new GetUserByUsernameQuery(data.Username));

            if (!string.IsNullOrEmpty(user?.Password) && SecurePasswordHasher.Verify(data.Password, user.Password))
            {
                HttpContext.Session.Set(SessionHelper.CLAIM_ID, user.ID);
                return(user);
            }
            return(data);
        }
        public void SecurePasswordHasherHashShouldReturnHashedPassword()
        {
            // arrange
            var expected = "$MYHASH$";

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

            // assert
            actual.Substring(0, 8).Should().BeEquivalentTo(expected);
        }
Ejemplo n.º 5
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"));
            }
        }
Ejemplo n.º 6
0
        public async Task <CustomerModel> SignIn(CustomerModel data)
        {
            var customer = await _mediator.Send(new GetCustomerByEmailQuery(data.Email));

            if (!string.IsNullOrEmpty(customer?.Password) && SecurePasswordHasher.Verify(data.Password, customer.Password))
            {
                HttpContext.Session.Set(SessionHelper.CLAIM_ID, customer.ID);
                return(customer);
            }
            return(data);
        }
Ejemplo n.º 7
0
        public Login(string username, string password)
        {
            verified     = false;
            errorMessage = "Unknown error";
            string          connectionString = ConfigurationManager.ConnectionStrings["MySQLConnection-altislife"].ConnectionString;
            MySqlConnection connection       = new MySqlConnection(connectionString);

            try
            {
                connection.Open();

                string       sql = "SELECT * FROM users_panel WHERE username=@username";
                MySqlCommand cmd = new MySqlCommand(sql, connection);
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@username", username);
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    //Get username and password from the database
                    string dbUsername    = reader.GetString(1);
                    string dbPassword    = reader.GetString(2);
                    string dbAccessLevel = reader.GetString(3);
                    int    dbBanned      = reader.GetInt32(4);

                    //Check if the password is correct
                    if (SecurePasswordHasher.Verify(password, dbPassword) && dbBanned == 0)
                    {
                        verified = true;
                        HttpContext.Current.Session["username"]    = dbUsername;
                        HttpContext.Current.Session["accessLevel"] = dbAccessLevel;
                    }
                    else
                    {
                        verified     = false;
                        errorMessage = "Incorrect password";
                    }
                }
                else
                {
                    verified     = false;
                    errorMessage = "Unknown username";
                }

                reader.Close();
            } catch (Exception e)
            {
                errorMessage = "Error connecting to database";
                System.Diagnostics.Debug.WriteLine(e.Message);
            }

            connection.Close();
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        private bool RightEmailPass(string email, string password)
        {
            passwordKey = _configuration.GetSection("Keys:PasswordDecrypter").Value.ToString();
            User   user = _context.Users.FirstOrDefault(x => x.Email.ToLower().Trim().Equals(email.ToLower().Trim()));
            string decryptedUserPass = SecurePasswordHasher.Decrypt(user.Password, passwordKey);

            if (decryptedUserPass.Equals(password))
            {
                return(true);
            }
            return(false);
        }
        public ActionResult ResetPassword(ChangePasswordInfo info)
        {
            var    user        = _context.Users.SingleOrDefault(x => x.ID == guid);
            var    userChanges = user;
            string hash        = SecurePasswordHasher.Hash(info.Password);

            userChanges.PasswordHash = hash;
            _context.Entry(user).CurrentValues.SetValues(userChanges);
            _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
            _context.SaveChanges();
            return(View("PasswordChanged"));
        }
 public Users GetUser(string login, string password)
 {
     using (var db = CreateDbContext())
     {
         var user = db.Users.FirstOrDefault(x => x.Login == login);
         if (user != null && SecurePasswordHasher.Verify(password, user.Password))
         {
             return(user);
         }
         return(null);
     }
 }
Ejemplo n.º 12
0
        public string Login([FromBody] User userF)
        {
            var login    = userF.Login;
            var password = userF.Password;
            var user     = _dbContext.Users.FirstOrDefault(u => u.Login == login);

            if (user == null || !SecurePasswordHasher.Verify(password, user.Password))
            {
                return("No");
            }
            return(user.Token);
        }
        public async Task <AuthTokenModel> Login(AuthModel credentials)
        {
            var user = await dbContext.Users
                       .FirstOrDefaultAsync(x => x.Email.ToUpper() == credentials.Login.ToUpper() && x.IsActive);

            if (user == null || !SecurePasswordHasher.Verify(credentials.Password, user.Password))
            {
                throw new AppUnauthorizedException();
            }

            return(await GenerateToken(user));
        }
        public void SaveUser(UserPM userPM)
        {
            var password = userPM.Password;

            userPM.Password = SecurePasswordHasher.Hash(userPM.Password);
            userPM.RoleId   = 3;

            var userDTO = _mapper.Map <UserDTO>(userPM);

            _serviceManager.UsersService.Save(userDTO);
            HttpContext.SetCurrentUserIdToCookie(userPM.Id, (int)userDTO.RoleId);
        }
Ejemplo n.º 15
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();
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Sign up button click
        /// </summary>
        private void SignUpClick(object sender, EventArgs e)
        {
            // Validation
            if (!FormValidation())
            {
                return;
            }

            // Values
            string name     = tbName.Text;
            string lastname = tbLastname.Text;
            string email    = tbEmail.Text;
            string country  = cbCountry.SelectedItem.PrimaryText;
            string password = tbPasswordOne.Text;

            // Values modified
            string passwordHash = SecurePasswordHasher.Hash(password);

            // Save hashed password to registry
            // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Polar", email, passwordHash);

            // AES
            AES aes = new AES(AES.GetKey(passwordHash), AES.GetInitVec(passwordHash));

            // Document path
            string path = Path.Combine(Environment.CurrentDirectory, "Data", "users.xml");

            // Save user in XML storage file
            // Load document
            XDocument doc = XDocument.Load(path);

            // Create user element
            XElement user = new XElement("User");

            user.Add(new XAttribute("name", aes.Encrypt(name)));
            user.Add(new XAttribute("lastname", aes.Encrypt(lastname)));
            user.Add(new XAttribute("email", email));
            user.Add(new XAttribute("country", aes.Encrypt(country)));
            user.Add(new XAttribute("password", passwordHash));

            // Add user element to .xml root
            doc.Root.Add(user);

            // Save document
            doc.Save(path);

            // Login user
            registeredUser = User.Login(email, password);

            // Redirect
            tabMain.SelectedTab = tabSetup;
        }
Ejemplo n.º 17
0
        public IActionResult Add(User obj)
        {
            return(Json(obj));

            string error = "";

            if (string.IsNullOrEmpty(obj.name) || string.IsNullOrEmpty(obj.surname) ||
                string.IsNullOrEmpty(obj.login) || string.IsNullOrEmpty(obj.password
                                                                        ))
            {
                error = "Please fill all the fields";
            }
            else if (obj.password.Length < 6)
            {
                error = "password is too short";
            }
            foreach (char elm in obj.password)
            {
                if (char.IsUpper(elm) == true)
                {
                    error = "";
                }
                else
                {
                    error = "password should contains Appercase";
                }
            }

            string log = obj.login;


            var q = (from item in baza.Users where item.login == log select item).Count();

            if (q > 0)
            {
                error = "chexav aper";
            }

            if (error == "")
            {
                obj.password = SecurePasswordHasher.Hash(obj.password);
                baza.Users.Add(obj);
                baza.SaveChanges();
            }
            else
            {
                TempData["Namak"] = error;
            }

            return(Redirect("/User/Signup"));
            // return Json(obj);
        }
Ejemplo n.º 18
0
 private User CreateUserFromInputs()
 {
     return(new User
     {
         Username = InputUsername.Text,
         Email = InputEmail.Text,
         PassHash = SecurePasswordHasher.Hash(InputPassword.Password),
         FirstName = InputFirstName.Text,
         LastName = InputLastName.Text,
         Address = InputAddress.Text,
         ZipCode = InputZipCode.Text,
     });
 }
Ejemplo n.º 19
0
        public void RegisterUser(string email, string username, string password)
        {
            User user = new User()
            {
                ID           = Guid.NewGuid(),
                Username     = username,
                Email        = email,
                PasswordHash = SecurePasswordHasher.Hash(password)
            };

            _context.Users.Add(user);
            _context.SaveChangesAsync();
        }
        public ActionResult Edit([Bind(Include = "email,name,password,role,occupation")]
                                 Person person)
        {
            if (ModelState.IsValid)
            {
                person.password        = SecurePasswordHasher.Hash(person.password);
                db.Entry(person).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(person));
        }
Ejemplo n.º 21
0
        public UserDBModel AddUserToDatabase(UserDBModel user)
        {
            string PasswordHash = SecurePasswordHasher.Hash(user.Pass);

            user.Pass              = PasswordHash;
            user.Created           = DateTime.Now;
            user.IsVerify          = false;
            user.VeryficationToken = TokenManager.RandomTokenString();
            _context.userDBModels.Add(user);
            _context.SaveChanges();

            return(user);
        }
Ejemplo n.º 22
0
 public void Create([FromBody] User userParam)
 {
     //if username is not in the database
     //use .Any( a => a.Username == userParam.UserName)
     Console.WriteLine("check");
     if (!_db.Users.Any(a => a.Username == userParam.Username))
     {
         userParam.PasswordHash = SecurePasswordHasher.Hash(userParam.Password, 1000);
         userParam.Password     = null;
         _db.Users.Add(userParam);
         _db.SaveChanges();
     }
 }
Ejemplo n.º 23
0
        public void Create_ShouldReturnOK_IfCalledWithCorrectModel()
        {
            var request = TestDataRepository.BuildCreateNewUserRequest();

            var result = (OkObjectResult)_usersController.Create(request);

            var res = result.Value as CreateNewUserResponse;

            Assert.AreEqual(request.FirstName, res.User.FirstName);
            Assert.AreEqual(request.LastName, res.User.LastName);
            Assert.AreEqual(request.UserName, res.User.UserName);
            Assert.IsTrue(SecurePasswordHasher.Verify(request.Password, res.User.Password));
        }
        public Task <bool> ValidateUser(string userName, string password)
        {
            var res = repo.Users.FirstOrDefault(e => e.Email == userName && SecurePasswordHasher.Verify(password, e.Password));

            if (res == null)
            {
                return(Task.FromResult(false));
            }
            else
            {
                return(Task.FromResult(true));
            }
        }
Ejemplo n.º 25
0
 internal DBUser InverseMap(User user)
 {
     if (user == null)
     {
         return(null);
     }
     return(new DBUser()
     {
         Id = user.Id,
         Email = user.Email,
         PassHash = SecurePasswordHasher.Hash(user.Password)
     });
 }
Ejemplo n.º 26
0
        public bool CheckIfThisLoginIsCorrect(string name, string password)
        {
            var users = Repository.GetUsers();

            foreach (var user in users)
            {
                if (name == user.Name && SecurePasswordHasher.Verify(password, user.Password) == true)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 27
0
        public async Task <Account> GetAccount(string userName, string password)
        {
            // Fetch account based on username which has a unique index
            var acc = await _context.Accounts.FirstOrDefaultAsync(a => a.UserName == userName);

            // Return null if no account or unable to verify the user
            if (acc == null || !SecurePasswordHasher.Verify(password, acc.Password))
            {
                return(null);
            }

            return(acc);
        }
Ejemplo n.º 28
0
        public UserModel GetUser(string name, string password)
        {
            var users = Repository.GetUsers();

            foreach (var user in users)
            {
                if (name == user.Name && SecurePasswordHasher.Verify(password, user.Password) == true)
                {
                    return(_mapper.Map <UserModel>(user));
                }
            }
            return(null);
        }
Ejemplo n.º 29
0
        static void DefaultUsersAndRoles()
        {
            using (ActivosEntities db = new ActivosEntities())
            {
                // If Admin user doesn't exist, then this block hasn't been run before
                if (db.Usuarios.FirstOrDefault(u => u.Usuario == "admin") == null)
                {
                    var RoleAdmin = db.Roles.Add(new Roles {
                        Nombre = "Admin"
                    });
                    var RoleRRHH = db.Roles.Add(new Roles {
                        Nombre = "RRHH"
                    });
                    var RoleLogis = db.Roles.Add(new Roles {
                        Nombre = "Logistica"
                    });
                    var RoleCont = db.Roles.Add(new Roles {
                        Nombre = "Contable"
                    });

                    db.Usuarios.Add(new Usuarios
                    {
                        Usuario    = "admin",
                        Nombre     = "Miguel",
                        Apellido   = "Araujo",
                        Contrasena = SecurePasswordHasher.Hash("asdf1234"),
                        Roles      = { RoleAdmin, RoleRRHH, RoleLogis }
                    });

                    db.Usuarios.Add(new Usuarios
                    {
                        Usuario    = "wcruz",
                        Nombre     = "Winston",
                        Apellido   = "Cruz",
                        Contrasena = SecurePasswordHasher.Hash("asdf1234"),
                        Roles      = { RoleRRHH }
                    });

                    db.Usuarios.Add(new Usuarios
                    {
                        Usuario    = "ldavid",
                        Nombre     = "Luis",
                        Apellido   = "Laureano",
                        Contrasena = SecurePasswordHasher.Hash("asdf1234"),
                        Roles      = { RoleLogis }
                    });

                    db.SaveChanges();
                }
            }
        }
        public DTOResponse <bool> ForgetPassword(DTOInfo forgetPasswordInfo)
        {
            if (string.IsNullOrWhiteSpace(forgetPasswordInfo.Email) || string.IsNullOrWhiteSpace(forgetPasswordInfo.Code) || string.IsNullOrWhiteSpace(forgetPasswordInfo.Password) || string.IsNullOrWhiteSpace(forgetPasswordInfo.ConfirmPassword))
            {
                return(new DTOResponse <bool>()
                {
                    Code = 400,
                    Message = "Email, Code, Password and ConfirmPassword are required!"
                });
            }

            var getUserResponse = GetUserByEmail(forgetPasswordInfo.Email);

            if (getUserResponse.Code != 200)
            {
                return(new DTOResponse <bool>()
                {
                    Code = 400,
                    Message = "This user email incorrect or not registered!"
                });
            }

            var existingUser = getUserResponse.Data;

            if (string.IsNullOrWhiteSpace(existingUser.VerificationCode) || existingUser.VerificationCode != forgetPasswordInfo.Code)
            {
                return(new DTOResponse <bool>()
                {
                    Code = 400,
                    Message = "This verification code is not valid!"
                });
            }

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

            var newUserPasswordHash = SecurePasswordHasher.Hash(forgetPasswordInfo.ConfirmPassword);

            _userCollection.UpdateOne <UserModel>(user => user.Id == existingUser.Id, Builders <UserModel> .Update.Set("VerificationCode", "").Set("PasswordHash", newUserPasswordHash));

            return(new DTOResponse <bool>()
            {
                Code = 200
            });
        }