コード例 #1
0
        public void User_Registration_Tests_Succeed()
        {
            var status = _userRegistrationService.Register("*****@*****.**", "somerandom", PasswordFormat.Md5Hashed);

            Assert.AreEqual(UserRegistrationStatus.Success, status);

            status = _userRegistrationService.Register("*****@*****.**", "somerandomaer", PasswordFormat.Md5Hashed);
            Assert.AreEqual(UserRegistrationStatus.FailedAsEmailAlreadyExists, status);
        }
コード例 #2
0
 private void CreateTestData()
 {
     _registeredUserId    = _userRegistrationService.Register("UserName", "VeryHardPassword123");
     _registeredAdminId   = _userRegistrationService.Register("AdminName", "VeryHardPassword123");
     _registeredAdminRole = "Admin";
     _registeredUserRole  = "User";
     _roleProvider.CreateRole(_registeredAdminRole, false);
     _roleProvider.CreateRole(_registeredUserRole, false);
     _roleProvider.AddUserToRole(_registeredAdminId, _registeredAdminRole);
 }
コード例 #3
0
        private void SetDefaultUsersAndRoles()
        {
            Guid userId = _userRegistrationService.Register(DefaultAdminName, DefaultAdminPassword, false);

            _roleProvider.CreateRole(AdministratorRoleName, false);
            _roleProvider.AddUserToRole(userId, AdministratorRoleName);
        }
コード例 #4
0
        public IActionResult SaveUser(UserModel userModel)
        {
            var user = userModel.Id > 0 ? _userService.FirstOrDefault(x => x.Id == userModel.Id) : new User();

            if (user == null)
            {
                return(NotFound());
            }
            user.Active                = userModel.Active;
            user.CompanyName           = userModel.CompanyName;
            user.Email                 = userModel.Email;
            user.FirstName             = userModel.FirstName;
            user.LastName              = userModel.LastName;
            user.IsTaxExempt           = userModel.IsTaxExempt;
            user.DateOfBirth           = userModel.DateOfBirth;
            user.MobileNumber          = userModel.MobileNumber;
            user.NewslettersEnabled    = userModel.NewslettersEnabled;
            user.Remarks               = userModel.Remarks;
            user.RequirePasswordChange = userModel.RequirePasswordChange;
            user.Name            = $"{user.FirstName} {user.LastName}";
            user.IsAffiliate     = userModel.IsAffiliate;
            user.AffiliateActive = userModel.AffiliateActive;
            var firstActivation = user.Active && user.FirstActivationDate == null;

            if (firstActivation)
            {
                user.FirstActivationDate = DateTime.UtcNow;
            }
            if (user.AffiliateFirstActivationDate == null && userModel.AffiliateActive)
            {
                user.AffiliateFirstActivationDate = DateTime.UtcNow;
            }
            if (user.Id == 0)
            {
                user.Guid      = Guid.NewGuid();
                user.CreatedOn = DateTime.UtcNow;
                user.UpdatedOn = DateTime.UtcNow;
                user.Password  = userModel.Password;
                _userRegistrationService.Register(user, ApplicationConfig.DefaultPasswordFormat);
            }
            else
            {
                _userService.Update(user);
                //update password if so
                if (!userModel.Password.IsNullEmptyOrWhiteSpace())
                {
                    _userRegistrationService.UpdatePassword(user.Id, userModel.Password, ApplicationConfig.DefaultPasswordFormat);
                }
            }

            //get the role ids
            var roleIds = userModel.Roles?.Select(x => x.Id).ToArray() ?? null;

            _roleService.SetUserRoles(user.Id, roleIds, true);
            if (firstActivation)
            {
                RaiseEvent(NamedEvent.UserActivated, user);
            }
            return(R.Success.With("id", user.Id).Result);
        }
コード例 #5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("/Verify");
            FillDropdowns();

            if (ModelState.IsValid)
            {
                _succeeded = true;

                _userRegistrationService.UserRegistered += SendVerificationEmail;
                _userRegistrationService.UserRegistered += SetUserId;
                _userRegistrationService.UserRegistered += SetInvitationsForThisEmail;

                _userRegistrationService.RegisterFailed += RegisterFailed;

                await _userRegistrationService.Register(RegistrationData);

                if (_succeeded)
                {
                    return(LocalRedirect(returnUrl + $"?userid={_uId}"));
                }
            }

            return(Page());
        }
コード例 #6
0
        public async Task<RegisteredUserDto> Register(UserRegistrationRequest request)
        {
            var response = await _userRegistrationService.Register(request);

            Response.Cookies.SetToken(response.AccessToken);

            return response.User;
        }
コード例 #7
0
        public IHttpActionResult Register(RegisterModel registerModel)
        {
            const string contextName = "register";

            if (!ModelState.IsValid)
            {
                return(RespondFailure("All the fields are required to complete the registration", contextName));
            }

            if (string.Compare(registerModel.Password, registerModel.ConfirmPassword, StringComparison.InvariantCulture) != 0)
            {
                return(RespondFailure("The passwords do not match", contextName));
            }

            if (!registerModel.Agreement)
            {
                return(RespondFailure("You must agree to the terms & conditions to complete the registration", contextName));
            }

            //we can now try to register this user
            //so create a new object
            var user = new User()
            {
                Email           = registerModel.Email,
                FirstName       = registerModel.FirstName,
                LastName        = registerModel.LastName,
                Name            = $"{registerModel.FirstName} {registerModel.LastName}",
                Password        = registerModel.Password,
                DateCreated     = DateTime.UtcNow,
                DateUpdated     = DateTime.UtcNow,
                IsSystemAccount = false,
                ReferrerId      = registerModel.ReferrerId,
                Guid            = Guid.NewGuid(),
                Active          = _userSettings.UserRegistrationDefaultMode == RegistrationMode.Immediate
            };
            //register this user
            var registrationStatus = _userRegistrationService.Register(user, _securitySettings.DefaultPasswordStorageFormat);

            if (registrationStatus == UserRegistrationStatus.FailedAsEmailAlreadyExists)
            {
                return(RespondFailure("A user with this email is already registered", contextName));
            }

            //assign role to the user
            _roleService.AssignRoleToUser(SystemRoleNames.Registered, user);

            //so we are done, send a notification to user and admin
            _emailSender.SendUserRegisteredMessage(user);
            var responseMessage = "Your account has been successfully created.";

            if (_userSettings.UserRegistrationDefaultMode == RegistrationMode.WithActivationEmail)
            {
                SendActivationEmail(user);
                responseMessage += " Email verification is required before you can login. Please check your inbox for activation link.";
            }
            return(RespondSuccess(responseMessage, contextName));
        }
コード例 #8
0
        private static void SetDefaultUsersAndRoles()
        {
            IUserRegistrationService registrationService = bootstrapper.Kernel.Get <IUserRegistrationService>();
            IRoleProvider            roleProvider        = bootstrapper.Kernel.Get <IRoleProvider>();
            Guid userId = registrationService.Register("Timur", "Admin", false);

            roleProvider.CreateRole("Administrator", false);
            roleProvider.AddUserToRole(userId, "Administrator");
        }
コード例 #9
0
        public async Task <IActionResult> Register(UserRegistrationDTO user)
        {
            user.UserName = user.UserName.ToLower();
            if (await _userService.UserExists(user.UserName))
            {
                return(BadRequest("User Already Exists"));
            }

            await _userService.Register(user);

            return(StatusCode(201));
        }
コード例 #10
0
        public IActionResult RegisterPerson([FromBody] RegisterRequestModel registerRequestData)
        {
            var registerData = new RegistrationDataDto
            {
                Password = registerRequestData.Password,
                UserName = registerRequestData.UserName,
            };

            var token = registrationService.Register(registerData);

            return(Ok(new AuthenticationResponseModel {
                Token = token.Value
            }));
        }
コード例 #11
0
        public virtual LoginStatus SignIn(string email, bool isPersistent = false, bool forceCreateNewAccount = false)
        {
            var user = _userService.FirstOrDefault(x => x.Email == email);

            if (user == null)
            {
                //do we need to force create a new user
                if (forceCreateNewAccount)
                {
                    var password = _cryptographyService.GetRandomPassword();
                    //register now
                    var registrationStatus = _userRegistrationService.Register(email, password, _securitySettings.DefaultPasswordStorageFormat);

                    if (registrationStatus == UserRegistrationStatus.FailedAsEmailAlreadyExists)
                    {
                        return(LoginStatus.Failed);
                    }

                    //load user again
                    if (registrationStatus == UserRegistrationStatus.Success)
                    {
                        user = _userService.FirstOrDefault(x => x.Email == email);
                    }
                }
            }
            if (user == null)
            {
                return(LoginStatus.FailedUserNotExists);
            }

            if (user.Deleted)
            {
                return(LoginStatus.FailedDeletedUser);
            }

            if (user.IsSystemAccount)
            {
                return(LoginStatus.Failed);
            }

            if (!user.Active)
            {
                return(LoginStatus.FailedInactiveUser);
            }

            //create the authentication ticket for the user
            CreateAuthenticationTicket(user, isPersistent);

            return(LoginStatus.Success);
        }
コード例 #12
0
        public async Task <IActionResult> Register([FromBody] UserRegistrationDto newUser)
        {
            if (newUser == null)
            {
                return(BadRequest(new { Message = "Not enough information" }));
            }

            var result = await registrationService.Register(newUser);

            if (result.Succeeded)
            {
                return(Ok(new { Message = "Account created" }));
            }

            return(BadRequest(result.Errors));
        }
コード例 #13
0
        private void registerButton_Click(object sender, EventArgs e)
        {
            var user = new UserDto {
                FirstName         = firstNameMaskedTextBox.Text,
                LastName          = lastNameMaskedTextBox.Text,
                UserName          = userNameMaskedTextBox.Text,
                Password          = passwordMaskedTextBox.Text,
                DateOfBirth       = dateOfBirthPicker.Value,
                AccountRegistered = DateTime.Now,
                EmailAddress      = emailAddressMaskedTextBox.Text,
                MobileNumber      = mobileNumberMaskedTextBox.Text,
            };

            if (new Validation(_userRegistrationService).IsValidUserToCreate(user, true))
            {
                _userRegistrationService.Register(user);
                this.Hide();
                this.DialogResult = DialogResult.OK;
            }
        }
コード例 #14
0
 private void CreateTestData()
 {
     _registeredUserName     = "******";
     _registeredUserPassword = "******";
     _userRegistrationService.Register(_registeredUserName, _registeredUserPassword);
 }
コード例 #15
0
        private LoginStatus SignInImpl(string authenticationScheme, string email, string name = "", bool isPersistent = false,
                                       bool forceCreateNewAccount = false, string imitatorEmail = null)
        {
            var user = _userService.FirstOrDefault(x => x.Email == email);

            if (user == null)
            {
                //do we need to force create a new user
                if (forceCreateNewAccount)
                {
                    var password = _cryptographyService.GetRandomPassword();
                    //register now
                    var registrationStatus = _userRegistrationService.Register(email, password, _securitySettings.DefaultPasswordStorageFormat);

                    if (registrationStatus == UserRegistrationStatus.FailedAsEmailAlreadyExists)
                    {
                        return(LoginStatus.Failed);
                    }

                    //load user again
                    if (registrationStatus == UserRegistrationStatus.Success)
                    {
                        user = _userService.FirstOrDefault(x => x.Email == email);
                        if (!string.IsNullOrEmpty(name))
                        {
                            user.Name = name;
                            _userService.Update(user);
                        }
                    }
                }
            }
            if (user == null)
            {
                return(LoginStatus.FailedUserNotExists);
            }

            if (user.Deleted)
            {
                return(LoginStatus.FailedDeletedUser);
            }

            if (user.IsSystemAccount)
            {
                return(LoginStatus.Failed);
            }

            if (!user.Active)
            {
                return(LoginStatus.FailedInactiveUser);
            }

            //create the authentication ticket for the user
            CreateAuthenticationTicket(user, isPersistent, authenticationScheme, imitatorEmail);

            if (!imitatorEmail.IsNullEmptyOrWhiteSpace())
            {
                user.SetMeta(ApplicationConfig.ImitatorKey, imitatorEmail);
            }
            //persist user
            ApplicationEngine.CurrentHttpContext.SetCurrentUser(user);

            if (!user.IsImitator(out _))
            {
                //update last login date & details
                user.LastLoginDate      = DateTime.UtcNow;
                user.LastLoginIpAddress = WebHelper.GetClientIpAddress();
                user.LastActivityDate   = DateTime.UtcNow;
                _userService.Update(user);
            }

            return(LoginStatus.Success);
        }
コード例 #16
0
        public IActionResult Register(RegisterModel registerModel)
        {
            //are registrations enabled?
            if (_userSettings.UserRegistrationDefaultMode == RegistrationMode.Disabled)
            {
                return(R.Fail.With("error", T("New registrations are disabled at the moment")).Result);
            }
            var      inviteCode = registerModel.InviteCode;
            UserCode userCode   = null;

            if (_userSettings.UserRegistrationDefaultMode == RegistrationMode.InviteOnly)
            {
                if (inviteCode.IsNullEmptyOrWhiteSpace())
                {
                    return(R.Fail.With("error", T("Registrations are allowed only by invitation")).Result);
                }
                userCode = _userCodeService.GetUserCode(inviteCode, UserCodeType.RegistrationInvitation);
                if (userCode.Email != registerModel.Email || !IsCodeValid(userCode))
                {
                    return(R.Fail.With("error", T("Registrations are allowed only by invitation")).Result);
                }
            }
            //validate consents first
            //get one time consents
            var consents = _consentService.Get(x => x.OneTimeSelection && x.Published).ToList();

            if (consents.Any(x => x.IsRequired))
            {
                foreach (var requiredConsent in consents.Where(x => x.IsRequired))
                {
                    var sentModel = registerModel.Consents.FirstOrDefault(x => x.Id == requiredConsent.Id);
                    if (sentModel == null || sentModel.ConsentStatus != ConsentStatus.Accepted)
                    {
                        return(R.Fail.With("error", T("Please consent to '" + requiredConsent.Title + "'")).Result);
                    }
                }
            }
            var user = new User()
            {
                Email           = registerModel.Email,
                Password        = registerModel.Password,
                CreatedOn       = DateTime.UtcNow,
                UpdatedOn       = DateTime.UtcNow,
                IsSystemAccount = false,
                Guid            = Guid.NewGuid(),
                Active          = _userSettings.UserRegistrationDefaultMode == RegistrationMode.Immediate || _userSettings.UserRegistrationDefaultMode == RegistrationMode.InviteOnly
            };

            if (user.Active)
            {
                user.FirstActivationDate = DateTime.UtcNow;
            }
            //register this user
            var registrationStatus = _userRegistrationService.Register(user, _securitySettings.DefaultPasswordStorageFormat);

            if (registrationStatus == UserRegistrationStatus.FailedAsEmailAlreadyExists)
            {
                return(R.Fail.With("message", "A user with this email is already registered").Result);
            }

            var roleId = _roleService.Get(x => x.SystemName == SystemRoleNames.Registered).First().Id;

            //assign role to the user
            _roleService.SetUserRoles(user.Id, new[] { roleId });

            if (registerModel.Consents != null && registerModel.Consents.Any())
            {
                //save the consents
                var consentDictionary = registerModel.Consents.ToDictionary(x => x.Id, x => x.ConsentStatus);
                _gdprService.SetUserConsents(user.Id, consentDictionary);
            }

            //delete the invite code & user code if any
            _inviteRequestService.Delete(x => x.Email == registerModel.Email);
            if (userCode != null)
            {
                _userCodeService.Delete(userCode);
            }
            var verificationLink = "";

            if (registerModel.InviteCode.IsNullEmptyOrWhiteSpace())
            {
                //if there was no invite code, the email needs to be verified (if the admin wants so)
                if (_userSettings.UserRegistrationDefaultMode == RegistrationMode.WithActivationEmail)
                {
                    userCode = _userCodeService.GetUserCode(user.Id, _userSettings.UseNumericCodeForActivationEmail ? UserCodeType.EmailOtp : UserCodeType.EmailVerification);
                    var verificationCode = userCode.Code;
                    verificationLink = verificationCode;
                    if (!_userSettings.UseNumericCodeForActivationEmail)
                    {
                        verificationLink =
                            ApplicationEngine.RouteUrl(RouteNames.VerifyEmail, new { code = verificationCode }, true);
                    }
                }
            }

            //do we have any affiliate?
            var affiliate = ApplicationEngine.CurrentAffiliate;

            if (affiliate != null)
            {
                user.ReferrerId = affiliate.Id;
                _userService.Update(user);
            }

            //raise the event
            RaiseEvent(NamedEvent.UserRegistered, user, verificationLink);
            if (user.Active)
            {
                RaiseEvent(NamedEvent.UserActivated, user);
            }
            return(R.Success.With("mode", _userSettings.UserRegistrationDefaultMode).With("numericActivation", _userSettings.UseNumericCodeForActivationEmail).Result);
        }
コード例 #17
0
ファイル: UserController.cs プロジェクト: ins4n333/mobsocial
        public IHttpActionResult Post(UserEntityModel entityModel)
        {
            User user;

            user = entityModel.Id == 0 ? new User() : _userService.Get(entityModel.Id);

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

            //check if the email has already been registered
            var emailUser = _userService.Get(x => x.Email == entityModel.Email, null).FirstOrDefault();

            if (emailUser != null && emailUser.Id != user.Id)
            {
                VerboseReporter.ReportError("The email is already registered with another user", "post_user");
                return(RespondFailure());
            }

            //same for user name
            if (_userSettings.AreUserNamesEnabled)
            {
                var userNameUser = _userService.Get(x => x.UserName == entityModel.UserName, null).FirstOrDefault();
                if (userNameUser != null && userNameUser.Id != user.Id)
                {
                    VerboseReporter.ReportError("The username is already taken by another user", "post_user");
                    return(RespondFailure());
                }
            }

            //we should have at least one role
            if (entityModel.RoleIds.Count == 0)
            {
                VerboseReporter.ReportError("At least one role must be assigned to the user", "post_user");
                return(RespondFailure());
            }
            //is this a new user, we'll require password
            if (string.IsNullOrEmpty(entityModel.Password) && entityModel.Id == 0)
            {
                VerboseReporter.ReportError("You must specify the password for the user", "post_user");
                return(RespondFailure());
            }
            //are passwords same?
            if (string.Compare(entityModel.Password, entityModel.ConfirmPassword, StringComparison.Ordinal) != 0)
            {
                VerboseReporter.ReportError("The passwords do not match", "post_user");
                return(RespondFailure());
            }

            user.FirstName   = entityModel.FirstName;
            user.LastName    = entityModel.LastName;
            user.Email       = entityModel.Email;
            user.Remarks     = entityModel.Remarks;
            user.Active      = entityModel.Active;
            user.DateUpdated = DateTime.UtcNow;
            user.Name        = string.Concat(user.FirstName, " ", user.LastName);
            user.UserName    = entityModel.UserName;
            if (entityModel.Id == 0)
            {
                user.Password = entityModel.Password;
                _userRegistrationService.Register(user, _securitySettings.DefaultPasswordStorageFormat);
            }
            else
            {
                if (!string.IsNullOrEmpty(entityModel.Password)) // update password if provided
                {
                    if (string.IsNullOrEmpty(user.PasswordSalt))
                    {
                        user.PasswordSalt = _cryptographyService.CreateSalt(8);
                    }
                    user.Password = _cryptographyService.GetHashedPassword(entityModel.Password, user.PasswordSalt,
                                                                           _securitySettings.DefaultPasswordStorageFormat);
                }

                _userService.Update(user);
            }

            //assign the roles now
            var roles = _roleService.Get(x => x.IsActive);
            //current roles
            var currentRoleIds = user.UserRoles.Select(x => x.RoleId).ToList();
            //roles to unassign
            var rolesToUnassign = currentRoleIds.Except(entityModel.RoleIds);

            foreach (var roleId in rolesToUnassign)
            {
                var role = roles.FirstOrDefault(x => x.Id == roleId);
                if (role == null)
                {
                    continue;
                }

                _roleService.UnassignRoleToUser(role, user);
            }

            //roles to assign
            var rolesToAssign = entityModel.RoleIds.Except(currentRoleIds);

            foreach (var roleId in rolesToAssign)
            {
                var role = roles.FirstOrDefault(x => x.Id == roleId);
                if (role == null)
                {
                    continue;
                }

                _roleService.AssignRoleToUser(role, user);
            }

            //any images to assign
            if (entityModel.CoverImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultCoverId, entityModel.CoverImageId);
            }
            if (entityModel.ProfileImageId != 0)
            {
                user.SetPropertyValue(PropertyNames.DefaultPictureId, entityModel.ProfileImageId);
            }

            VerboseReporter.ReportSuccess("User saved successfully", "post_user");
            return(RespondSuccess(new {
                User = user.ToEntityModel(_mediaService, _mediaSettings)
            }));
        }
コード例 #18
0
        public bool Connect(ConnectedAccountRequest request)
        {
            //check if the user is already connected
            var connectedAccount = _connectedAccountService.FirstOrDefault(x =>
                                                                           x.ProviderName == request.ProviderName && x.ProviderUserId == request.ProviderUserId);

            request.AutoLogin = true;
            //get user by email
            var user = _userService.GetByUserInfo(request.Email);

            if (connectedAccount == null)
            {
                if (request.Name.IsNullEmptyOrWhiteSpace())
                {
                    request.Name = $"{request.FirstName} {request.LastName}";
                }
                //connect the account
                //first register the user
                user = user ?? new User()
                {
                    Email           = request.Email,
                    Password        = Guid.NewGuid().ToString(),
                    CreatedOn       = DateTime.UtcNow,
                    UpdatedOn       = DateTime.UtcNow,
                    IsSystemAccount = false,
                    Guid            = Guid.NewGuid(),
                    Active          = _userSettings.ActivateUserForConnectedAccount,
                    FirstName       = request.FirstName,
                    LastName        = request.LastName,
                    Name            = request.Name
                };
                //register this user
                var status = _userRegistrationService.Register(user, _securitySettings.DefaultPasswordStorageFormat);
                if (status == UserRegistrationStatus.Success)
                {
                    //set the role
                    var roleId = _roleService.FirstOrDefault(x => x.SystemName == SystemRoleNames.Registered).Id;
                    //assign role to the user
                    _roleService.SetUserRoles(user.Id, new[] { roleId });
                }

                //it's possible that user is already registered with this email or it may be a new registration
                //in any case create a connected account
                connectedAccount = new ConnectedAccount()
                {
                    ProviderName   = request.ProviderName,
                    ProviderUserId = request.ProviderUserId,
                    AccessToken    = request.AccessToken,
                    UserId         = user.Id
                };
                _connectedAccountService.Insert(connectedAccount);
            }
            else
            {
                //update token
                connectedAccount.AccessToken = request.AccessToken;
                _connectedAccountService.Update(connectedAccount);
            }
            //user is already connected, login if required
            if (request.AutoLogin)
            {
                //get the user
                var loginStatus = ApplicationEngine.SignIn(user.Email, user.Name, true);
                return(loginStatus == LoginStatus.Success);
            }

            return(true);
        }