Exemple #1
0
        public async Task <IActionResult> Register([FromBody] RegistrationModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetFirstError()));
            }

            var existingUser = await _userService.GetByEmail(model.Email);

            if (existingUser != null)
            {
                return(BadRequest(ValidationResultMessages.DuplicateEmail));
            }

            var user = new User()
            {
                Email    = model.Email,
                UserName = model.UserName,
                Password = PasswordHashHelper.HashPassword(model.Password),
                IsAdmin  = true,
            };

            if (!string.IsNullOrWhiteSpace(model.CompanyName))
            {
                user.CompanyId   = Guid.NewGuid();
                user.CompanyName = model.CompanyName;
            }

            user = await _userService.CreateNew(user);

            var tokens = GetJWTTokens(user);

            return(Ok(tokens));
        }
Exemple #2
0
        public void HashPassword_Verify_True()
        {
            var text    = Guid.NewGuid().ToString();
            var hashed  = PasswordHashHelper.HashPassword(text);
            var hashed2 = PasswordHashHelper.HashPassword(text);

            Assert.True(hashed == hashed2);
        }
 public bool Register(UserModel userModel)
 {
     userRepository.Add(new User
     {
         Email        = userModel.Email,
         PasswordHash = PasswordHashHelper.HashPassword(userModel.Password)
     });
     return(unitOfWork.Commit());
 }
Exemple #4
0
        public async Task Login_Success(LoginModel model, User user)
        {
            user.PasswordHash = PasswordHashHelper.HashPassword(model.Password);
            _userRepository.Setup(c => c.GetUserByEmail(model.Email)).ReturnsAsync(user);

            var result = await _manager.Login(model);

            Assert.True(result.Id == user.Id);
            Assert.True(result.Name == user.Name);
        }
        public async Task <int> AddUser(User user)
        {
            var context = _context.GetContext();

            user.PasswordHash = PasswordHashHelper.HashPassword(user.PasswordHash);
            user.CreationDate = DateTime.Now;
            context.Users.Add(user);

            await context.SaveChangesAsync();

            return(user.Id);
        }
Exemple #6
0
        public async Task <UserInfoModel> Login(LoginModel model)
        {
            var user = await _userRepository.GetUserByEmail(model.Email);

            if (user != null && user.PasswordHash == PasswordHashHelper.HashPassword(model.Password))
            {
                var result = new UserInfoModel()
                {
                    Name = user.Name,
                    Id   = user.Id
                };
                return(result);
            }
            else
            {
                return(null);
            }
        }
        public async Task <CreateUserResponse> Handle(CreateUserRequest request, CancellationToken cancellationToken)
        {
            var newUser = new User
            {
                UserName     = request.UserName,
                EmailAddress = request.EmailAddress,
                FirstName    = request.FirstName,
                LastName     = request.LastName,
            };

            var validationResult = await _createUserRequestValidator.ValidateAsync(newUser);

            if (!validationResult.IsValid)
            {
                return(new CreateUserResponse
                {
                    IsSuccessfull = false,
                    Errors = validationResult.Errors.Select(a => new PropertyErrorModel {
                        PropertyName = a.PropertyName.ToCamelCase(), ErrorMessage = a.ErrorMessage
                    }).ToArray()
                });
            }

            var salt = PasswordHashHelper.GetSaltValue();
            var hash = PasswordHashHelper.HashPassword(request.Password, salt);

            newUser.LoginData = new LoginData
            {
                PasswordSalt = salt,
                PasswordHash = hash
            };

            var databaseUser = await _databaseContext.Users.AddAsync(newUser);

            await _databaseContext.SaveChangesAsync();

            return(new CreateUserResponse {
                IsSuccessfull = true, CreatedUserId = databaseUser.Entity.Id
            });
        }
Exemple #8
0
        public async Task <LoginResponse> Handle(LoginRequest request, CancellationToken cancellationToken)
        {
            var user = await _databaseContext.Users
                       .Include(u => u.LoginData)
                       //.Include(u => u.Roles)
                       .Where(u => u.UserName == request.Login)
                       .FirstOrDefaultAsync();

            if (user == null || user.LoginData == null)
            {
                return(await Task.FromResult(LoginResponse.FailResponse));
            }

            var getHash = PasswordHashHelper.HashPassword(request.Password, user.LoginData.PasswordSalt);

            if (!getHash.SequenceEqual(user.LoginData.PasswordHash))
            {
                return(await Task.FromResult(LoginResponse.FailResponse));
            }

            return(await Task.FromResult(LoginResponse.SuccessResponse(CreateToken(user))));
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var salt = PasswordHashHelper.GetSaltValue();
            var hash = PasswordHashHelper.HashPassword("test123", salt);

            modelBuilder.Entity <LoginData>().HasData(new LoginData
            {
                Id           = 1,
                PasswordSalt = salt,
                PasswordHash = hash
            });

            modelBuilder.Entity <User>().HasData(new User
            {
                Id           = 1,
                UserName     = "******",
                EmailAddress = "*****@*****.**",
                FirstName    = "admin",
                LastName     = "admin",
                LoginDataId  = 1,
            });

            base.OnModelCreating(modelBuilder);
        }
Exemple #10
0
        public async Task <string> Login([FromBody] LoginModel user)
        {
            var userData = await this.userManager.FindByUserNameAndPassword(user.Login, PasswordHashHelper.HashPassword(user.Password));

            if (userData != null)
            {
                var token = new JwtSecurityToken(
                    issuer: jwtAuthentication.Value.ValidIssuer,
                    audience: jwtAuthentication.Value.ValidAudience,
                    claims: new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Login),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                },
                    expires: DateTime.UtcNow.AddMinutes(60),
                    signingCredentials: jwtAuthentication.Value.SigningCredentials);


                var authorizationModel = new AuthorizationModel()
                {
                    authorizedUserModel = new AuthorizationModel.AuthorizedUserModel(userData.Id, userData.UserName, userData.Email)
                };
                authorizationModel.token = new JwtSecurityTokenHandler().WriteToken(token);
                return(JsonConvert.SerializeObject(authorizationModel, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));
            }

            else
            {
                return(JsonConvert.SerializeObject(new AuthorizationModel {
                    errorMessage = "Wrong user name or password"
                }, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));
            }
        }
Exemple #11
0
        protected override void Seed(EmployeeContext context)
        {
            var listDepartment = new List <Department>
            {
                new Department {
                    Name = "IT"
                },
                new Department {
                    Name = "HR"
                },
                new Department {
                    Name = "Software Development"
                },
                new Department {
                    Name = "BPO"
                }
            };

            string[] employeeNames =
            {
                "Marcus,HighTower,acmecorp.com",
                "Jesse,Smith,gmail.com",
                "Albert,Einstein,outlook.com",
                "Dan,Wahlin,yahoo.com",
                "Ward,Bell,gmail.com",
                "Brad,Green,gmail.com",
                "Igor,Minar,gmail.com",
                "Miško,Hevery,gmail.com",
                "Michelle,Avery,acmecorp.com",
                "Heedy,Wahlin,hotmail.com",
                "Thomas,Martin,outlook.com",
                "Jean,Martin,outlook.com",
                "Robin,Cleark,acmecorp.com",
                "Juan,Paulo,yahoo.com",
                "Gene,Thomas,gmail.com",
                "Pinal,Dave,gmail.com",
                "Fred,Roberts,outlook.com",
                "Tina,Roberts,outlook.com",
                "Cindy,Jamison,gmail.com",
                "Robyn,Flores,yahoo.com",
                "Jeff,Wahlin,gmail.com",
                "Danny,Wahlin,gmail.com",
                "Elaine,Jones,yahoo.com"
            };
            var random = new Random();

            for (int i = 0; i < employeeNames.Count(); i++)
            {
                var employee = employeeNames[i].Split(',');
                context.Employees.Add(new Employee
                {
                    FirstName  = employee[0],
                    LastName   = employee[1],
                    Email      = string.Format("{0}{1}@{2}", employee[0], employee[1], employee[2]),
                    Birthday   = RandomDate(random),
                    Department = listDepartment[i % 4],
                    Phone      = GetRandomTelNo(random)
                });
            }
            context.Users.Add(new User
            {
                Email        = "*****@*****.**",
                PasswordHash = PasswordHashHelper.HashPassword("111111"),
                Roles        = new List <UserRole> {
                    new UserRole {
                        RoleName = Role.Admin
                    }
                }
            });
            context.Users.Add(new User
            {
                Email        = "*****@*****.**",
                PasswordHash = PasswordHashHelper.HashPassword("111111"),
                Roles        = new List <UserRole> {
                    new UserRole {
                        RoleName = Role.User
                    }
                }
            });
            context.SaveChanges();
            base.Seed(context);
        }