Beispiel #1
0
        public ChatUser AddUser(string userName, string email, string password)
        {
            if (!IsValidUserName(userName))
            {
                throw new InvalidOperationException(String.Format("'{0}' is not a valid user name.", userName));
            }

            if (String.IsNullOrEmpty(password))
            {
                ThrowPasswordIsRequired();
            }

            EnsureUserNameIsAvailable(userName);

            var user = new ChatUser
            {
                Name         = userName,
                Email        = email,
                Status       = (int)UserStatus.Active,
                Id           = Guid.NewGuid().ToString("d"),
                Salt         = _crypto.CreateSalt(),
                LastActivity = DateTime.UtcNow,
            };

            ValidatePassword(password);
            user.HashedPassword = password.ToSha256(user.Salt);

            _repository.Add(user);

            return(user);
        }
Beispiel #2
0
        public BursifyUser RegisterUser(string userEmail, string password, string userType)
        {
            BursifyUser user = null;

            using (IUnitOfWork uow = _unitOfWorkFactory.CreateUnitOfWork())
            {
                var existingUser = _userRepository.GetUserByEmail(userEmail);
                if (existingUser != null)
                {
                    return(null);
                }

                var salt = _cryptoService.CreateSalt();



                user = new BursifyUser
                {
                    Email              = userEmail,
                    PasswordHash       = _cryptoService.HashPassword(password, salt),
                    PasswordSalt       = salt,
                    UserType           = userType,
                    AccountStatus      = "Active",
                    RegistrationDate   = DateTime.UtcNow,
                    ProfilePicturePath = "def"
                };

                _userRepository.Save(user);
                uow.Commit();
            }
            return(user);
        }
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbUser != null &&
                string.Equals(dbUser.Email, requestModel.Email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new ConflictException("Email Already Exits");
            }
            var salt           = _encryptionService.CreateSalt();
            var hashedPassword = _encryptionService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };
            var createdUser = await _userRepository.AddAsync(user);

            //var response = new UserRegisterResponseModel
            //{
            //    Id = createdUser.Id, Email = createdUser.Email, FirstName = createdUser.FirstName,
            //    LastName = createdUser.LastName
            //};
            var response = _mapper.Map <UserRegisterResponseModel>(createdUser);

            return(response);
        }
Beispiel #4
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);//make sure the user exist or not

            if (dbUser != null &&
                string.Equals(dbUser.Email, requestModel.Email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new ConflictException("Email Already Exits");  //if user already exist, cannot create user ccount
            }
            var salt           = _encryptionService.CreateSalt();
            var hashedPassword = _encryptionService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };                                                      //create new user information
            var createdUser = await _userRepository.AddAsync(user); //add those information to DB

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }//manully mapping
Beispiel #5
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            //Make sure email does not exist in DB
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbUser != null &&
                string.Equals(dbUser.Email, requestModel.Email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("Email Already Exist");
            }

            //Create unique salt and hash the pw
            var salt           = _cryptoService.CreateSalt();
            var hashedPassWord = _cryptoService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassWord,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };
            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }
Beispiel #6
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            //make sure email not in db
            //we need to send email to our User Repo and see if the data exists for the email
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbUser != null && string.Equals(dbUser.Email, requestModel.Email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("Email Already Exits");
            }

            //first step is to create a random salt
            var salt           = _encryptionService.CreateSalt();
            var hashedPassword = _encryptionService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };
            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }
Beispiel #7
0
        public EmplonomyUser RegisterUser(string userEmail, string password, string name, string surname, string phone, int depId)
        {
            EmplonomyUser user = null;

            int?EmpNumber = GetLastUserID() + 1;

            DateTime birthdate       = new DateTime(1900, 1, 1);
            DateTime resignationDate = new DateTime(1900, 1, 1);

            var salt = _cryptoService.CreateSalt();

            user = new EmplonomyUser
            {
                DepartmentID           = depId,
                isManager              = false,
                EmployeeNumber         = "MishiftEmp" + EmpNumber,
                EmailAddress           = userEmail,
                EmailAddressAlt        = userEmail,
                PasswordHash           = _cryptoService.HashPassword(password, salt),
                PasswordSalt           = salt,
                CreateDate             = DateTime.Now,
                LastLoginDate          = DateTime.Now,
                IsLoggedin             = true,
                ConfirmedReg           = false,
                FailedPasswordAttempts = 0,
                AgreeTC         = true,
                Salary          = 0,
                FirstName       = name,
                LastName        = surname,
                Birthdate       = birthdate,
                HireDate        = DateTime.Now,
                ResignationDate = resignationDate,
                PhoneCell       = phone,
                AvatarURL       = "AvatarFilePath",
                isDeleted       = false
            };

            Add(user);
            Commit();

            return(user);
        }
        public Task <Nonce> CreateNonce()
        {
            return(Task.Factory.StartNew(() =>
            {
                string salt = crypto.CreateSalt();
                string data = Guid.NewGuid().ToString();
                string hash = this.crypto.CreateKey(salt, data);

                return new Nonce(hash);
            }));
        }
Beispiel #9
0
        public EmplonomyUser RegisterUserEmployee(string userEmail)
        {
            EmplonomyUser user = null;

            using (IUnitOfWork uow = _unitOfWorkFactory.CreateUnitOfWork())
            {
                var existingUser = _userRepository.GetUserByEmail(userEmail);
                if (existingUser != null)
                {
                    return(null);
                }

                int?EmpNumber = _userRepository.GetLastUserID() + 1;

                var salt     = _cryptoService.CreateSalt();
                var password = "******";

                user = new EmplonomyUser
                {
                    RoleID                 = 4,
                    EmployeeNumber         = "EmplonomyEmp" + EmpNumber,
                    EmailAddress           = userEmail,
                    EmailAddressAlt        = userEmail,
                    PasswordHash           = _cryptoService.HashPassword(password, salt),
                    PasswordSalt           = salt,
                    CreateDate             = DateTime.Now,
                    LastLoginDate          = DateTime.Now,
                    isDeleted              = false,
                    isLoggedin             = true,
                    ConfirmedReg           = false,
                    FailedPasswordAttempts = 0,
                    AgreeTC                = true
                };

                _userRepository.Save(user);
                uow.Commit();
            }
            return(user);
        }
Beispiel #10
0
        public async Task <ClaimsIdentity> SignupUser(ISignupServiceOptions options)
        {
            UserProviderLocal login = await(from p in this.db.LocalProvider.Include(o => o.User)
                                            where p.User.Username == options.Username
                                            select p).FirstOrDefaultAsync();

            if (login != null)
            {
                throw new ServiceException($"A user account for {options.Username} already exists");
            }

            User user = new User()
            {
                CultureName = options.CultureName,
                Enabled     = true,
                Username    = options.Username,
                DisplayName = options.DisplayName,
                TimeZoneId  = options.TimeZoneId
            };

            db.User.Add(user);

            string salt = crypto.CreateSalt();

            db.LocalProvider.Add(new UserProviderLocal()
            {
                PasswordSalt = salt,
                PasswordHash = crypto.CreateKey(salt, options.Password),
                User         = user,
                Provider     = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Local)
            });

            Role role = db.Role.FirstOrDefault(o => o.RoleId == RoleTypes.User);

            user.Roles.Add(new UserRole()
            {
                User = user,
                Role = role
            });

            db.SaveChanges();

            var fingerprint = this.deviceProfiler.DeriveFingerprint(user);

            return(user.ToClaimsIdentity(fingerprint));
        }
 public UserModule(ICryptoService crypto)
     : base("user")
 {
     //Get a list of all the users in the same organization as you.
     Get["/"] = _ =>
     {
         if (!IsAuthenticated)
         {
             return HttpStatusCode.Unauthorized;
         }
         var user =
             DocumentSession.Load<EmailUser>(Principal.GetUserId());
         var users =
             DocumentSession.Query<EmailUser>()
                 .Where(u => u.Organization.Id == user.Organization.Id)
                 .Select(c => new UserViewModel {Name = c.Name, Organization = c.Organization.Name}).ToList();
         return Response.AsJson(users);
     };
     Post["/"] = _ =>
     {
         //If User is authenticated and is the org admin.
         if (IsAuthenticated && Principal.HasClaim(EmailRClaimTypes.Admin))
         {
             return HttpStatusCode.Unauthorized;
         }
         var user =
             DocumentSession.Load<EmailUser>(Principal.GetUserId());
         var createUser = this.Bind<CreateUserViewModel>();
         var salt = crypto.CreateSalt();
         var newUser = new EmailUser
         {
             Email = createUser.Email,
             FriendlyName = createUser.FriendlyName,
             //Id = Guid.NewGuid(),
             Password = createUser.Password.ToSha256(salt),
             Salt = salt,
             LoginType = "Default",
             Organization = user.Organization,
             Name = createUser.UserName,
             IsAdmin = false
         };
         DocumentSession.Store(newUser);
         return HttpStatusCode.OK;
     };
 }
Beispiel #12
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            // 1. Call GetUserByEmail  with  requestModel.Email to check if the email exists in the User Table or not
            // if user/email exists return Email already exists and throw an Conflict exception

            // if email does not exists then we can proceed in creating the User record
            // 1. var salt =  Genreate a random salt
            // 2. var hashedPassword =  we take requestModel.Password and add Salt from above step and Hash them to generate Unique Hash
            // 3. Save Email, Salt, hashedPassword along with other details that user sent like FirstName, LastName etc
            // 4. return the UserRegisterResponseModel object with newly craeted Id for the User

            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbUser != null)
            {
                throw new Exception("Email alreadyy exists");
            }

            var salt           = _cryptoService.CreateSalt();
            var hashedPassword = _cryptoService.HashPassword(requestModel.Password, salt);

            var user = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };

            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = requestModel.Email,
                FirstName = requestModel.FirstName,
                LastName  = requestModel.LastName
            };

            return(response);
        }
Beispiel #13
0
        public User CreateUser(string username, string password, int[] roles = null)
        {
            var dbUser = _userRepository.GetUserByUserName(username);

            if (dbUser != null)
            {
                return(null);
            }
            var salt      = _cryptoService.CreateSalt();
            var hashedPwd = _cryptoService.HashPassword(password, salt);
            var user      = new User()
            {
                Email          = username,
                Salt           = salt,
                HashedPassword = hashedPwd
            };

            _userRepository.Add(user);
            _userRepository.SaveChanges();
            return(user);
        }
Beispiel #14
0
        public async Task <User> CreateUser(string email, string password, string firstName, string lastName)
        {
            var dbUser = await _userRepository.GetUserByEmail(email);

            if (dbUser != null)
            {
                return(null);
            }
            var salt         = _cryptoService.CreateSalt();
            var hashPassword = _cryptoService.HashPassword(password, salt);
            var user         = new User {
                Email          = email,
                FirstName      = firstName,
                LastName       = lastName,
                HashedPassword = hashPassword,
                Salt           = salt
            };
            var CreatedUser = await _userRepository.AddAsync(user);

            return(CreatedUser);
        }
Beispiel #15
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            //step1: check whether this user already exists in the db
            var dbuser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbuser != null)
            {
                //we already have this user(email) in our db
                throw new Exception("User already registered, Please try to login");
            }

            //step 2: create a random unique salt, always use industry hashing algorithm
            var salt = _cryptoService.CreateSalt();


            //step 3: We hash the password with the salt created by the above step
            var hashedPassword = _cryptoService.HashPassword(requestModel.Password, salt);

            //step 4: create user object so that we can save it to User Table
            var user = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };
            //Step 5 : Save it to db
            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }
Beispiel #16
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            //step1: create an user
            //step2: add the created user to the userRepository
            //step3: send the response back to the controller. (important)

            //make sure email does not exist in the database
            //we need to send email to our User repository and see if the data exists for the email
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            //if the user exists and there's an email that matches it.
            if (dbUser != null && string.Equals(dbUser.Email, requestModel.Email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("Email Already Exits");
            }

            //First step is to create a unique random salt.
            var salt           = _encryptionService.CreateSalt();
            var hashedPassword = _encryptionService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };
            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }
Beispiel #17
0
        public async Task <UserRegisterResponseModel> CreateUser(UserRegisterRequestModel requestModel)
        {
            //1.call getuserbyemail to check if  user has already existed
            //if existed, return email already exists and throw an exception
            //else proceed to create user
            //1. generate random salt
            //2. take requesModel.Password together with salt generate unique hashing
            //3. save essential information except for the password it self(save salt also)
            //4. return responseModel
            var dbUser = await _userRepository.GetUserByEmail(requestModel.Email);

            if (dbUser != null)
            {
                throw new Exception("Email has already existed.");
            }
            var salt           = _cryptoService.CreateSalt();
            var hashedPassword = _cryptoService.HashPassword(requestModel.Password, salt);
            var user           = new User
            {
                Email          = requestModel.Email,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = requestModel.FirstName,
                LastName       = requestModel.LastName
            };

            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserRegisterResponseModel
            {
                Id        = createdUser.Id,
                Email     = createdUser.Email,
                FirstName = createdUser.FirstName,
                LastName  = createdUser.LastName
            };

            return(response);
        }
Beispiel #18
0
        public async Task <IActionResult> Login(LoginModel loginModel)
        {
            if (_userService.Count() == 0)
            {
                var saltCode       = _cryptoService.CreateSalt(10);
                var hashedPassword = _cryptoService.Encrypt("12345", saltCode);

                _userService.Add(new Entities.Concrete.User
                {
                    Username = "******",
                    Email    = "*****@*****.**",
                    Password = hashedPassword,
                    SaltCode = saltCode
                });
            }

            User user = _userService.Get("Username='******'");

            if (user != null)
            {
                if (_userService.PasswordCheck(user, loginModel.Password))
                {
                    var claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Name, user.Username),
                        new Claim(ClaimTypes.Email, user.Email)
                    };

                    ClaimsIdentity  userIdentity = new ClaimsIdentity(claims, "login");
                    ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(principal);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View());
        }
Beispiel #19
0
        public async Task <User> CreateUserAsync(string userName, string password, string firstName, string lastName, int[] roles = null)
        {
            var user = await _userRepository.GetUserByUserNameAsync(userName);

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

            var salt           = _cryptoService.CreateSalt();
            var hashedPassword = _cryptoService.HashPassword(password, salt);

            var dbUser = new User
            {
                Email          = userName,
                Salt           = salt,
                HashedPassword = hashedPassword,
                FirstName      = firstName,
                LastName       = lastName,
            };

            return(await _userRepository.AddAsync(dbUser));
        }
Beispiel #20
0
        private static User EnsureAdmin(DbContextBase db, ICryptoService crypto)
        {
            User admin = db.User.SingleOrDefault(o => o.Username == AdminEmail);

            if (admin == null)
            {
                admin = new User()
                {
                    CultureName = "en",
                    DisplayName = "Webmaster",
                    Enabled     = true,
                    TimeZoneId  = Globalization.DefaultTimeZoneId,
                    Username    = AdminEmail
                };

                db.User.Add(admin);
                db.SaveChanges();
            }

            Role role = db.Role.FirstOrDefault(o => o.RoleId == RoleTypes.Admin);

            if (role == null)
            {
                string name = RoleTypes.System.FirstOrDefault(o => o.Key == RoleTypes.Admin).Value;

                role = new Role()
                {
                    CreatedByUser = admin,
                    Enabled       = true,
                    Name          = name,
                    RoleId        = RoleTypes.Admin
                };

                db.Role.Add(role);
                db.SaveChanges();
            }

            if (!db.UserRole.Any())
            {
                var userRole = new UserRole()
                {
                    Role = role,
                    User = admin
                };

                string salt = crypto.CreateSalt();
                string hash = crypto.CreateKey(salt, "P@ssw0rd");

                var userProvider = new UserProviderLocal
                {
                    ProviderId   = ProviderTypes.Local,
                    PasswordSalt = salt,
                    PasswordHash = hash,
                    User         = admin,
                };

                db.UserRole.Add(userRole);
                db.UserProvider.Add(userProvider);

                db.SaveChanges();
            }

            return(admin);
        }
Beispiel #21
0
        private static User EnsureAdmin(DbContextBase db, ICryptoService crypto)
        {
            User adminUser = db.User.SingleOrDefault(o => o.Username == AdminEmail);

            if (adminUser == null)
            {
                adminUser = new User()
                {
                    Username    = AdminEmail,
                    Enabled     = true,
                    DisplayName = "Webmaster",
                    Verified    = true
                };

                db.User.Add(adminUser);
                db.SaveChanges();
            }

            Role adminRole = db.Role.FirstOrDefault(o => o.RoleId == RoleTypes.Admin);

            if (adminRole == null)
            {
                adminRole = new Role()
                {
                    CreatedByUser = adminUser,
                    Enabled       = true,
                    Name          = "Administrator",
                    RoleId        = RoleTypes.Admin
                };
                db.Role.Add(adminRole);
                db.SaveChanges();
            }

            if (!db.UserRole.Any())
            {
                var userRole = new UserRole()
                {
                    Role = adminRole,
                    User = adminUser
                };

                string salt = crypto.CreateSalt();
                string hash = crypto.CreateKey(salt, "P@ssword");

                var userProvider = new UserProviderLocal
                {
                    CreatedOn    = DateTime.Now,
                    ProviderId   = ProviderTypes.Local,
                    PasswordSalt = salt,
                    PasswordHash = hash,
                    User         = adminUser,
                };

                db.UserRole.Add(userRole);
                db.UserProvider.Add(userProvider);

                db.SaveChanges();
            }

            return(adminUser);
        }