Ejemplo n.º 1
0
        public async Task <int> Handle(PostRegisterCommand request, CancellationToken cancellationToken)
        {
            var passwordSalt = Salt.Create();
            var passwordHash = Hash.Create(request.Password, passwordSalt);

            var user = new User
            {
                UserAccountStatusId = UserAccountStatusEnum.Active,
                FirstName           = request.FirstName,
                LastName            = request.LastName,
                Email        = request.Email,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                CreatedDate  = DateTime.Now,
                UserRoles    = new List <UserRoles>
                {
                    new UserRoles
                    {
                        UserRoleId = UserRoleEnum.Standard
                    }
                }
            };

            _context.User.Add(user);
            await _context.SaveChangesAsync(cancellationToken);

            return(user.Id);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Create([Bind("Id,AdminEmail,AdminPassword,CreatedDate,LastLogin,IPAddress,UserAgent")] AdminAuth adminAuth)
        {
            if (string.IsNullOrEmpty(HttpContext.Session.GetString("_logged")))
            {
                HttpContext.Session.SetString("_logged", "masuk");
            }
            if (ModelState.IsValid)
            {
                var insertdb = new AdminAuth();

                var message = adminAuth.AdminPassword;
                var salt    = Salt.Create();
                var hash    = Hash.Create(message, salt);

                insertdb.AdminEmail    = adminAuth.AdminEmail;
                insertdb.Salt          = salt;
                insertdb.AdminPassword = hash;
                insertdb.CreatedDate   = DateTime.Now;
                insertdb.IPAddress     = adminAuth.IPAddress;
                insertdb.IsActive      = 1;
                insertdb.UserAgent     = Request.Headers["User-Agent"];

                _context.Add(insertdb);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(adminAuth));
        }
Ejemplo n.º 3
0
        private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            var strSalt = Salt.Create();

            passwordSalt = Encoding.UTF8.GetBytes(strSalt);
            passwordHash = Encoding.UTF8.GetBytes(Hash.Create(password, strSalt));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> ForgotMyPassword(string email)
        {
            var userManager = _context.ManagerFactory.CreateUserManager();
            var user        = await userManager.GetUserModel(email);

            if (user != null)
            {
                var randomString = Path.GetRandomFileName();
                randomString = randomString.Replace(".", "");

                var salt = Salt.Create();
                var hash = Hash.Create(randomString, salt);

                var credentials = new UserCredentials()
                {
                    UserName = email, Hash = hash, Salt = salt
                };
                await userManager.UpdateUserCredentials(credentials);

                var mailHelper = new MailHelper();
                mailHelper.SendMail(email, "Forgotten Password",
                                    "You have asked to reset your password because it was forgotten.\n" +
                                    "Your new password is: " + randomString + "\n" +
                                    "Kind Regards\n" +
                                    "AU Dent MailBot");

                ViewBag.Message = "Your password has been reset. Your new password has been sent to: " + email;
                return(View("Login"));
            }

            ViewBag.Message = "No user found for email: " + email;
            return(View("Login"));
        }
Ejemplo n.º 5
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                if (await uow.Context.Users.SingleOrDefaultAsync(x => x.Username == request.obj.Username) != null)
                {
                    throw new StatusCodeException(HttpStatusCode.NotFound, $"User with this {request.obj.Username} already exists");
                }

                RegisterDtoValidation validator = new RegisterDtoValidation();
                ValidationResult      results   = validator.Validate(request.obj);

                if (!results.IsValid)
                {
                    validator.ValidateAndThrow(request.obj);
                }

                var salt = Salt.Create();

                request.obj.Password = Hash.Create(request.obj.Password, salt);
                var obj = uow.Mapper.Map <User>(request.obj);

                obj.Salt = salt;
                obj.Role = Role.User;
                await uow.User.RegisterAsync(obj);

                uow.Commit();
                return(Unit.Value);
            }
Ejemplo n.º 6
0
        public async Task <IActionResult> ChangePassword(ChangePasswordModel model)
        {
            IActionResult response = Unauthorized();

            var userManager = _context.ManagerFactory.CreateUserManager();
            var email       = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email).Value;

            var user = await userManager.Authenticate(new LoginModel { Username = email, Password = model.OldPassword });

            if (user == null)
            {
                var userModel = await userManager.GetUserModel(email);

                ViewBag.Message = "Old password was incorrect. No changes were made";
                return(View("Profile", userModel));
            }


            var salt = Salt.Create();
            var hash = Hash.Create(model.NewPassword, salt);

            var credentials = new UserCredentials()
            {
                UserName = email, Hash = hash, Salt = salt
            };


            await userManager.UpdateUserCredentials(credentials);

            return(RedirectToAction("Profile"));
        }
Ejemplo n.º 7
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            using (var db = new LiteDatabase(@"movieReservation.db")) {
                var col = db.GetCollection <Models.User>("users");

                // Hash the password
                var salt = Salt.Create();
                var hash = Hash.Create(RegisterRequest.Password, salt);

                // Give the first user in the database the Owner role
                var userCount = col.Count();
                var role      = userCount > 0 ? UserRole.Customer : UserRole.Owner;

                // Insert a user with our values
                col.Insert(new Models.User {
                    Email        = RegisterRequest.Email,
                    HashSalt     = salt,
                    HashPassword = hash,
                    Role         = role,
                });
            }

            Success = "Je bent geregistreerd!";
            return(Page());
        }
        public FakeUserAuthRepository()
        {
            List = new List <UserAuth>();

            // Usuario Admin:
            var user = new UserAuth("admin", "123456", "Admin", true);
            var salt = Salt.Create();
            var hash = Hash.Create(user.Password, salt);

            user.AddHash(hash, Convert.ToBase64String(salt));
            List.Add(user);

            // Usuario comum ativo:
            user = new UserAuth("userActive", "123456", "User", true);
            salt = Salt.Create();
            hash = Hash.Create(user.Password, salt);
            user.AddHash(hash, Convert.ToBase64String(salt));
            List.Add(user);

            // Usuario comum inativo:
            user = new UserAuth("userInactive", "123456", "User", false);
            salt = Salt.Create();
            hash = Hash.Create(user.Password, salt);
            user.AddHash(hash, Convert.ToBase64String(salt));
            List.Add(user);

            // Usuario cadastrado, aguardando liberação de acesso (feito pelo Admin):
            user = new UserAuth("userNew", "123456");
            salt = Salt.Create();
            hash = Hash.Create(user.Password, salt);
            user.AddHash(hash, Convert.ToBase64String(salt));
            List.Add(user);
        }
Ejemplo n.º 9
0
        public async Task <ActionResult <User> > PostUser(User user)
        {
            // check if the user already exists
            if (_context.Users.FirstOrDefault(u => u.Email == user.Email) != null)
            {
                return(BadRequest("User with that email address already exists!"));
            }

            // hash password
            if (user.Password != null)
            {
                user.Salt     = Salt.Create();
                user.Password = Hash.Create(user.Password, user.Salt);
            }

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            // do not include these values in the response.
            // We should create a custom Response class for this, but this gets the job done for now.
            user.Password = null;
            user.Token    = null;
            user.Salt     = null;

            return(CreatedAtAction("GetUser", new { id = user.UserID }, user));
        }
Ejemplo n.º 10
0
        public void CheckAndInitialize()
        {
            if (!db.Users.Any() || db.Users.FirstOrDefault(u => u.UserName.Equals("Admin")) == null)
            {
                var salt  = Salt.Create();
                var Admin = new User
                {
                    UserName = "******", FirstName = "Andrii", SecondName = "Hordiienko", Email = "*****@*****.**",
                    Password = Hash.Create("Admin" + _config.GetValue <string>("GlobalParameter"), salt), Salt = salt, Position = "Admin", CurrencyId = 1
                };

                db.Users.AddRange(Admin);
            }
            db.SaveChanges();

            /*if (!db.Currencies.Any())
             * {
             *  db.Currencies.Add(new Currency() { Name = "USD" });
             *  db.Currencies.Add(new Currency() { Name = "UAH" });
             *
             * }*/
            /*if (!db.Items.Any())
             * {
             *  db.Items.Add(new Item { Name = "Food",CurrencyId = 1});
             *  db.Items.Add(new Item { Name = "Games",CurrencyId = 1,});
             *
             * }*/
        }
Ejemplo n.º 11
0
        public async Task SeedUsers()
        {
            // // apply all migrations if they haven't been yet
            _context.Database.Migrate();

            // Seed Admin user
            // Find if admin has been seeded already
            AppUser adminUser = await _context.Users.FirstOrDefaultAsync(u => u.Email == "*****@*****.**");

            if (adminUser == null)
            {
                string  passwordSalt = Salt.Create();
                AppUser newAdminUser = new AppUser {
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    PasswordSalt = passwordSalt,
                    PasswordHash = Hash.Create("test123", passwordSalt)
                };

                IdentityResult result = await _userManager.CreateAsync(newAdminUser);

                // TODO: Apply check to see if the "admin" role even exists
                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(newAdminUser, "admin");
                }
            }
        }
Ejemplo n.º 12
0
        public async Task Post([FromBody] User user)
        {
            try
            {
                try
                {
                    user.Salt     = Salt.Create();
                    user.Password = Hash.Create(user.Password + _config.GetValue <string>("GlobalParameter"), user.Salt);
                    Worker.AddEntity(user);
                    Response.StatusCode  = 200;
                    Response.ContentType = "application/json";
                    await Response.WriteAsync(JsonResponseFactory.CreateJson(
                                                  Worker.GetEntities().Cast <User>().LastOrDefault()));

                    return;
                }
                catch (NullReferenceException)
                {
                    Response.ContentType = "application/json";
                    Response.StatusCode  = 400;
                    await Response.WriteAsync(JsonResponseFactory.CreateJson(null,
                                                                             new List <object> {
                        "Email | UserName"
                    }, new List <string> {
                        "email or username are not unique"
                    }));
                }
            }
            catch
            {
                Response.StatusCode  = 400;
                Response.ContentType = "application/json";
                await Response.WriteAsync(JsonResponseFactory.CreateJson(null));
            }
        }
Ejemplo n.º 13
0
 public User(string name, string password, Role role)
 {
     Name         = name;
     Sault        = Salt.Create();
     HashPassword = Hash.Create(password, Sault);
     Role         = role;
 }
Ejemplo n.º 14
0
        public IActionResult ResetPassword(UserAuth usr)
        {
            var getsalt   = _context.UserAuth.FirstOrDefault(x => x.Email == usr.Email);
            var userAgent = Request.Headers["User-Agent"];
            var salt      = Salt.Create();
            var hash      = Hash.Create(usr.Password, salt);

            getsalt.Salt     = salt;
            getsalt.Password = hash;



            if (string.IsNullOrEmpty(HttpContext.Session.GetString("_email")))
            {
                HttpContext.Session.SetString("_email", getsalt.Email);
                HttpContext.Session.SetString("_idunique", getsalt.UniqueKey);
            }
            var routeValues = new RouteValueDictionary
            {
                { "id", getsalt.UniqueKey }
            };


            getsalt.LastLogin = DateTime.Now;
            getsalt.UserAgent = userAgent;
            getsalt.Ipaddress = usr.Ipaddress;
            _context.SaveChanges();
            return(RedirectToAction(nameof(VideoUpload), routeValues));
        }
Ejemplo n.º 15
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Установка значение свойства Name как уникальное
            modelBuilder.Entity <User>().HasIndex(u => u.Name).IsUnique();

            //// настройка связи один ко многим
            //modelBuilder.Entity<User>()
            //    .HasOne(u => u.Role)
            //    .WithMany(r => r.Users);

            // Добавление ролей
            Role adminRole = new Role {
                Id = 1, Name = "admin"
            };
            Role userRole = new Role {
                Id = 2, Name = "user"
            };

            modelBuilder.Entity <Role>().HasData(new Role[] { adminRole, userRole });

            // Добавление админа
            byte[] sault     = Salt.Create();
            User   adminUser = new User {
                Id           = 1,
                Name         = "admin",
                Sault        = sault,
                HashPassword = Hash.Create("admin", sault),
                RoleId       = adminRole.Id
            };

            modelBuilder.Entity <User>().HasData(new User[] { adminUser });

            base.OnModelCreating(modelBuilder);
        }
Ejemplo n.º 16
0
        private void CreateUser(RegisterModel registerModel)
        {
            var salt = Salt.Create();
            var hash = Hash.Create(registerModel.Password, salt);

            var credentials = new UserCredentials()
            {
                Email = registerModel.Email, Hash = hash, Salt = salt
            };


            var newUser = new UserModel()
            {
                FirstName       = registerModel.FirstName,
                LastName        = registerModel.LastName,
                AUId            = registerModel.AUId,
                PhoneNumber     = registerModel.PhoneNumber,
                StaffInitials   = registerModel.StaffInitials,
                Email           = registerModel.Email,
                Role            = Role.Admin,
                UserCredentials = credentials
            };


            _context.User.Add(newUser);
            _context.SaveChanges();
        }
Ejemplo n.º 17
0
        public void LoginFail(string username, string password)
        {
            //Arrange
            string salt = Salt.Create();
            IQueryable <DummyModel> mockData = new List <DummyModel> {
                new DummyModel {
                    Id = 1, FirstName = "mpinane", LastName = "mohale", Username = "******", Password = Hash.Create("nane", salt), Salt = salt
                }
            }.AsQueryable();

            var mockSet = new Moq.Mock <DbSet <DummyModel> >();

            mockSet.Setup(m => m.Find(username)).Returns((mockData.Where(x => x.Username == username)).First);

            var mockContext = new Moq.Mock <DummyContext>();

            mockContext.Setup(c => c.DummyModel).Returns(mockSet.Object);

            var controller = new DummyModelsController(mockContext.Object);


            //Act
            var login = controller.Login(username, password).Result;


            //Assert
            Assert.IsInstanceOf <UnauthorizedResult>(login);
        }
Ejemplo n.º 18
0
 private static User GivenUser(Guid userId, string name, string email, string password)
 {
     return(new(
                new UserId(userId),
                new Name(name),
                new Email(email),
                new Password(password),
                new PasswordSalt(Salt.Create())));
 }
Ejemplo n.º 19
0
        public void ValidateHash_Should_Validate_Matching_Password_With_Salt_Theory(string password)
        {
            string salt = Salt.Create();
            string hash = Hash.Create(password, salt);

            bool match = Hash.Authenticate(password, salt, hash);

            Assert.True(match);
        }
Ejemplo n.º 20
0
        public void Hasher()
        {
            var pwd    = "any-string";
            var salt   = Salt.Create();
            var hash   = Hash.Create(pwd, salt);
            var result = Hash.Validate(pwd, salt, hash);

            Assert.True(result);
        }
Ejemplo n.º 21
0
        public void Hash_CreateTwiceWithSamePassword_ReturnsIdenticalHash()
        {
            var salt = Salt.Create();

            var hash1 = Hash.Create("password", salt);
            var hash2 = Hash.Create("password", salt);

            Assert.Equal(hash1, hash2);
        }
Ejemplo n.º 22
0
        public void Hash_CreateTwiceWithDifferentPassword_ReturnsNonIdenticalHash()
        {
            var salt = Salt.Create();

            var hash1 = Hash.Create("Password", salt);
            var hash2 = Hash.Create("password", salt);

            Assert.NotEqual(hash1, hash2);
        }
        public void Not_Verify_Password_When_Hash_Does_Not_Match_Password()
        {
            const string password     = "******";
            var          expectedSalt = Salt.Create();
            const string expectedHash = "unmatched_hash";

            var actualResult = Hash.Verify(password, expectedSalt, expectedHash);

            actualResult.Should().BeFalse();
        }
        public void Verify_Password_When_Hash_Matches_Password()
        {
            const string password     = "******";
            var          expectedSalt = Salt.Create();
            var          expectedHash = Hash.Create(password, expectedSalt);

            var actualResult = Hash.Verify(password, expectedSalt, expectedHash);

            actualResult.Should().BeTrue();
        }
Ejemplo n.º 25
0
        public async Task <Customer> AddCustomer(Customer customer)
        {
            var salt = Salt.Create();

            customer.Auth.Password = Hash.Create(customer.Auth.Password, salt);
            customer.Auth.Salt     = salt;
            await Add(customer);

            return(customer);
        }
Ejemplo n.º 26
0
        public void Insert(Users obj)
        {
            string salt = Salt.Create();
            string hash = Hash.Create(obj.Password, salt);

            obj.Salt     = salt;
            obj.Password = hash;
            _context.Users.Add(obj);
            _context.SaveChanges();
        }
Ejemplo n.º 27
0
        public void ValidateHash_Should_Not_Validate_Same_Password_With_Different_Salt()
        {
            string password = "******";
            string salt1    = Salt.Create();
            string hash     = Hash.Create(password, salt1);

            string salt2 = Salt.Create();
            bool   match = Hash.Authenticate(password, salt2, hash);

            Assert.False(match);
        }
Ejemplo n.º 28
0
        public User Register(User user)
        {
            var passwordSalt = Salt.Create();
            var hashPassword = Hash.Create(user.Password, passwordSalt);

            user.Password = hashPassword;
            user.Salt     = passwordSalt;


            return(user);
        }
Ejemplo n.º 29
0
        public void GenerateHashCodePasswordValid()
        {
            var expectedDay      = DateTime.Now.AddDays(1);
            var hashCodePassword = Salt.Create();
            var user             = new User()
            {
                HashCodePassword           = hashCodePassword,
                HashCodePasswordExpiryDate = expectedDay
            };

            Assert.Equal(user.HashCodePasswordExpiryDate.Date, expectedDay.Date);
        }
Ejemplo n.º 30
0
        public void HashCodeInValid()
        {
            var expectedDay      = DateTime.Now.AddDays(1);
            var hashCodePassword = Salt.Create();
            var user             = new User()
            {
                HashCodePassword           = hashCodePassword,
                HashCodePasswordExpiryDate = expectedDay
            };

            Assert.False(user.HashCodePasswordIsValid("HASHCODEINVALID"));
        }