public HttpResponseMessage UpdateUserBasicInfo(UserBasicDto userBasicDto) { try { Validate(userBasicDto); KeyValuePair <HttpStatusCode, string> response; var user = Components.UsersController.GetUser(userBasicDto.UserId, PortalSettings, UserInfo, out response); if (user == null) { return(Request.CreateErrorResponse(response.Key, response.Value)); } var upadtedUser = Components.UsersController.Instance.UpdateUserBasicInfo(userBasicDto); return(Request.CreateResponse(HttpStatusCode.OK, upadtedUser)); } catch (SqlException ex) { Logger.Error(ex); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Localization.GetString("UsernameNotUnique", Components.Constants.LocalResourcesFile))); } catch (Exception ex) { Logger.Error(ex); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public HttpResponseMessage CreateUser(CreateUserContract contract) { try { var settings = new RegisterationDetails { PortalSettings = PortalSettings, Email = contract.Email, FirstName = contract.FirstName, LastName = contract.LastName, UserName = contract.UserName, Password = contract.Password, Question = contract.Question, Answer = contract.Answer, Notify = contract.Notify, Authorize = contract.Authorize, RandomPassword = contract.RandomPassword, IgnoreRegistrationMode = true }; var userInfo = RegisterController.Instance.Register(settings); return(Request.CreateResponse(HttpStatusCode.OK, userInfo != null ? UserBasicDto.FromUserDetails(Components.UsersController.Instance.GetUserDetail(PortalId, userInfo.UserId)) : null)); } catch (Exception ex) { Logger.Error(ex); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public static UserBasicInfo MapUserBasicDto(UserInfo uInfo, UserBasicDto d) { IFolderInfo userFolder = FolderManager.Instance.GetUserFolder(uInfo); UserBasicInfo info = new UserBasicInfo() { userId = d.UserId, displayName = d.Displayname, userName = d.Username, email = d.Email, avatar = uInfo.Profile.PhotoURL.Contains("no_avatar.gif") ? Vanjaro.Common.Utilities.UserUtils.GetProfileImage(PortalSettings.Current.PortalId, d.UserId, d.Email) : d.AvatarUrl, firstName = d.Firstname, lastName = d.Lastname, createdOnDate = d.CreatedOnDate, isDeleted = d.IsDeleted, authorized = uInfo.Membership.Approved, isSuperUser = d.IsSuperUser, isAdmin = d.IsAdmin, lastLogin = uInfo.Membership.LastLoginDate, lastActivity = uInfo.Membership.LastActivityDate, lastPasswordChange = uInfo.Membership.LastPasswordChangeDate, lastLockout = uInfo.Membership.LastLockoutDate, isLocked = uInfo.Membership.LockedOut, needUpdatePassword = uInfo.Membership.UpdatePassword, portalId = uInfo.PortalID, userFolder = FolderManager.Instance.GetUserFolder(uInfo).FolderPath.Substring(6), userFolderId = userFolder != null ? userFolder.FolderID : -1, hasUserFiles = FolderManager.Instance.GetFiles(userFolder, true).Any() }; return(info); }
public UserBasicDto UpdateUserBasicInfo(UserBasicDto userBasicDto) { var user = UserController.Instance.GetUser(PortalSettings.PortalId, userBasicDto.UserId); int portalId = PortalSettings.PortalId; if (user == null) { throw new ArgumentException("UserNotExist"); } if (userBasicDto.UserId == PortalSettings.AdministratorId) { //Clear the Portal Cache DataCache.ClearPortalCache(portalId, true); } if (user.IsSuperUser) { DataCache.ClearHostCache(true); } user.DisplayName = userBasicDto.Displayname; user.Email = userBasicDto.Email; //Update DisplayName to conform to Format if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) { user.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); } //either update the username or update the user details if (CanUpdateUsername(user) && !PortalSettings.Registration.UseEmailAsUserName) { UserController.ChangeUsername(user.UserID, userBasicDto.Username); user.Username = userBasicDto.Username; } //DNN-5874 Check if unique display name is required if (PortalSettings.Registration.RequireUniqueDisplayName) { var usersWithSameDisplayName = (List <UserInfo>)MembershipProvider.Instance().GetUsersBasicSearch(portalId, 0, 2, "DisplayName", true, "DisplayName", user.DisplayName); if (usersWithSameDisplayName.Any(u => u.UserID != user.UserID)) { throw new ArgumentException("DisplayNameNotUnique"); } } UserController.UpdateUser(portalId, user); if (PortalSettings.Registration.UseEmailAsUserName && (user.Username.ToLowerInvariant() != user.Email.ToLowerInvariant())) { UserController.ChangeUsername(user.UserID, user.Email); } return (UserBasicDto.FromUserInfo(UserController.Instance.GetUser(PortalSettings.PortalId, userBasicDto.UserId))); }
private void Validate(UserBasicDto userBasicDto) { Requires.NotNegative("UserId", userBasicDto.UserId); }
public static List <IUIData> GetData(string Identifier, Dictionary <string, string> UIEngineInfo, UserInfo userInfo, Dictionary <string, string> parameters) { int uid = 0; if (parameters.Count > 0) { int.TryParse(parameters["uid"], out uid); } PortalSettings ps = PortalController.Instance.GetCurrentSettings() as PortalSettings; Dictionary <string, IUIData> Settings = new Dictionary <string, IUIData>(); switch (Identifier) { case "setting_updateprofile": { if (uid > 0) { Settings.Add("BrowseUrl", new UIData { Name = "BrowseUrl", Value = Common.Utilities.Utils.BrowseUrl(-1, "Manage") }); Settings.Add("AllowedAttachmentFileExtensions", new UIData { Name = "AllowedAttachmentFileExtensions", Value = FileSetting.FileType }); Settings.Add("MaxFileSize", new UIData { Name = "MaxFileSize", Value = FileSetting.FileSize.ToString() }); if (!(parameters.ContainsKey("username") && parameters.ContainsKey("password"))) { return(Settings.Values.ToList()); } int UserID = uid; string keyword = string.Empty; UserInfo user = DotNetNuke.Entities.Users.UserController.GetUserById(ps.PortalId, UserID); UserBasicDto userDetails = UsersController.Instance.GetUserDetail(ps.PortalId, UserID); ProfileController.GetUserProfile(ref user); Settings.Add("UserDetails", new UIData { Name = "UserDetails", Options = UserManager.MapUserBasicDto(user, userDetails) }); Settings.Add("UserRoles", new UIData { Name = "UserRoles", Options = UsersController.Instance.GetUserRoles(user, keyword, out int totalRoles).Select(r => UserRoleDto.FromRoleInfo(ps, r)) }); Settings.Add("IsAdmin", new UIData { Name = "IsAdmin", Value = userInfo.IsInRole("Administrators").ToString() }); Settings.Add("ProfilePropertiesByCategories", new UIData { Name = "ProfilePropertiesByCategories", Options = Managers.UserManager.GetLocalizedCategories(user.Profile.ProfileProperties, user, true).Select(x => new { x.Key, x.Value }) }); if (string.IsNullOrEmpty(user.Profile.PreferredLocale)) { if (string.IsNullOrEmpty(DotNetNuke.Entities.Users.UserController.GetUserById(ps.PortalId, ps.AdministratorId).Profile.PreferredLocale)) { user.Profile.SetProfileProperty("PreferredLocale", !string.IsNullOrEmpty(ps.DefaultLanguage) ? ps.DefaultLanguage : Thread.CurrentThread.CurrentCulture.Name); } else { user.Profile.SetProfileProperty("PreferredLocale", DotNetNuke.Entities.Users.UserController.GetUserById(ps.PortalId, ps.AdministratorId).Profile.PreferredLocale); } } List <Entities.ProfileProperties> profileProperties = new List <Entities.ProfileProperties>(); ListController listController = new ListController(); foreach (ProfilePropertyDefinition d in user.Profile.ProfileProperties) { string ControlType = UserManager.GetControlType(d.DataType); if (ControlType == "Country" || ControlType == "Region" || ControlType == "List") { d.PropertyValue = string.IsNullOrEmpty(d.PropertyValue) ? "-1" : d.PropertyValue; } List <ListEntryInfo> data = listController.GetListEntryInfoItems(d.PropertyName, "", PortalSettings.Current.PortalId).ToList(); data.Insert(0, new ListEntryInfo { Text = Localization.GetString("NotSpecified", Components.Constants.LocalResourcesFile), Value = d.PropertyValue }); profileProperties.Add(new Entities.ProfileProperties { ProfilePropertyDefinition = d, ListEntries = data }); } Settings.Add("ProfileProperties", new UIData { Name = "ProfileProperties", Options = profileProperties }); //Profile URL dynamic Profile = null; if (!string.IsNullOrEmpty(user.Profile.Photo)) { Profile = BrowseUploadFactory.GetFile(ps, Convert.ToInt32(user.Profile.Photo)); } Settings.Add("PhotoURL", new UIData { Name = "PhotoURL", Options = Profile ?? user.Profile, Value = Vanjaro.Common.Utilities.UserUtils.GetProfileImage(PortalSettings.Current.PortalId, user.UserID, user.Email) }); var countries = GetCountryList(Thread.CurrentThread.CurrentCulture.Name).Values.OrderBy(x => x.NormalizedFullName).Select(x => new { Id = x.Id.ToString(), x.FullName, x.Name }).ToList(); countries.Insert(0, new { Id = "-1", FullName = Localization.GetString("NotSpecified", Components.Constants.LocalResourcesFile), Name = Localization.GetString("NotSpecified", Components.Constants.LocalResourcesFile) }); Settings.Add("Countries", new UIData { Name = "Countries", OptionsText = "Key", OptionsValue = "Value", Options = countries }); ReadOnlyCollection <TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); var Timezones = timeZones.Cast <TimeZoneInfo>().Select(x => new { Id = x.Id.ToString(), x.DisplayName }); Settings.Add("Time_Zones", new UIData { Name = "Time_Zones", OptionsText = "Key", OptionsValue = "Value", Options = Timezones }); Dictionary <string, Locale> ActiveLocales = new LocaleController().GetLocales(ps.PortalId); var activeLocales = ActiveLocales.Values.Cast <Locale>().Select(x => new { x.Code, x.Culture, x.EnglishName, x.NativeName, KeyID = x.KeyID.ToString(), x.Text }).ToList(); Settings.Add("Active_Locales", new UIData { Name = "Active_Locales", OptionsText = "Key", OptionsValue = "Value", Options = activeLocales }); }
//NOTE - While making modifications in this method, developer must refer to call tree in Register.ascx.cs. //Especially Validate and CreateUser methods. Register class inherits from UserModuleBase, which also contains bunch of logic. //This method can easily be modified to pass passowrd, display name, etc. //It is recommended to write unit tests. public UserBasicDto Register(RegisterationDetails registerationDetails) { var portalSettings = registerationDetails.PortalSettings; var username = registerationDetails.UserName; var email = registerationDetails.Email; Requires.NotNullOrEmpty("email", email); var disallowRegistration = !registerationDetails.IgnoreRegistrationMode && ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) || (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration)); if (disallowRegistration) { throw new Exception(Localization.GetString("RegistrationNotAllowed", Library.Constants.SharedResources)); } //initial creation of the new User object var newUser = new UserInfo { PortalID = portalSettings.PortalId, Email = email }; var cleanUsername = PortalSecurity.Instance.InputFilter(username, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup); if (!cleanUsername.Equals(username)) { throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); } var valid = UserController.Instance.IsValidUserName(username); if (!valid) { throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid.")); } //ensure this user doesn't exist if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null) { throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent", Library.Constants.SharedResources)); } //set username as email if not specified newUser.Username = string.IsNullOrEmpty(username) ? email : username; if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword) { newUser.Membership.Password = registerationDetails.Password; } else { //Generate a random password for the user newUser.Membership.Password = UserController.GeneratePassword(); } newUser.Membership.PasswordConfirm = newUser.Membership.Password; //set other profile properties newUser.Profile.InitialiseProfile(portalSettings.PortalId); newUser.Profile.PreferredLocale = new Localization().CurrentUICulture; newUser.Profile.PreferredTimeZone = portalSettings.TimeZone; //derive display name from supplied firstname, lastname or from email if (!string.IsNullOrEmpty(registerationDetails.FirstName) && !string.IsNullOrEmpty(registerationDetails.LastName)) { newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName; newUser.FirstName = registerationDetails.FirstName; newUser.LastName = registerationDetails.LastName; } else { newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal)); } //read all the user account settings var settings = UserController.GetUserSettings(portalSettings.PortalId); //Verify Profanity filter if (this.GetBoolSetting(settings, "Registration_UseProfanityFilter")) { var portalSecurity = PortalSecurity.Instance; if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) { throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed", Library.Constants.SharedResources)); } } //Email Address Validation var emailValidator = this.GetStringSetting(settings, "Security_EmailValidation"); if (!string.IsNullOrEmpty(emailValidator)) { var regExp = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Email); if (matches.Count == 0) { throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed", Library.Constants.SharedResources)); } } //Excluded Terms Verification var excludeRegex = this.GetExcludeTermsRegex(settings); if (!string.IsNullOrEmpty(excludeRegex)) { var regExp = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Username); if (matches.Count > 0) { throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed", Library.Constants.SharedResources)); } } //User Name Validation var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation"); if (!string.IsNullOrEmpty(userNameValidator)) { var regExp = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline); var matches = regExp.Matches(newUser.Username); if (matches.Count == 0) { throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed", Library.Constants.SharedResources)); } } //ensure unique username var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username); if (user != null) { if (this.GetBoolSetting(settings, "Registration_UseEmailAsUserName")) { throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail)); } var i = 1; string userName = null; while (user != null) { userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.GetUserByName(portalSettings.PortalId, userName); i++; } newUser.Username = userName; } //ensure unique display name if (this.GetBoolSetting(settings, "Registration_RequireUniqueDisplayName")) { user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName); if (user != null) { var i = 1; string displayName = null; while (user != null) { displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture); user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName); i++; } newUser.DisplayName = displayName; } } //Update display name format var displaynameFormat = this.GetStringSetting(settings, "Security_DisplayNameFormat"); if (!string.IsNullOrEmpty(displaynameFormat)) { newUser.UpdateDisplayName(displaynameFormat); } //membership is approved only for public registration newUser.Membership.Approved = (registerationDetails.IgnoreRegistrationMode || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize; newUser.Membership.PasswordQuestion = registerationDetails.Question; newUser.Membership.PasswordAnswer = registerationDetails.Answer; //final creation of user var createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify); //clear cache if (createStatus == UserCreateStatus.Success) { CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId)); } if (createStatus != UserCreateStatus.Success) { throw new Exception(UserController.GetUserCreateStatus(createStatus)); } // if (registerationDetails.IgnoreRegistrationMode) // { // Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings); // return UserBasicDto.FromUserInfo(newUser); // } //send notification to portal administrator of new user registration //check the receive notification setting first, but if register type is Private, we will always send the notification email. //because the user need administrators to do the approve action so that he can continue use the website. if (!registerationDetails.IgnoreRegistrationMode && (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration)) { Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings); SendAdminNotification(newUser, portalSettings); } return(UserBasicDto.FromUserInfo(newUser)); }
public override ConsoleResultModel Run() { var sbResults = new StringBuilder(); ConsoleErrorResultModel errorResultModel; UserInfo userInfo; if ( (errorResultModel = this._userValidator.ValidateUser( this.UserId, this.PortalSettings, this.User, out userInfo) ) != null ) { return(errorResultModel); } // Update the User // process the password first. If invalid, we can abort other changes to the user if (!string.IsNullOrEmpty(this.Password)) { try { this._usersController.ChangePassword(userInfo.PortalID, userInfo.UserID, this.Password); sbResults.Append(this.LocalizeString("ChangeSuccessful")); } catch (Exception ex) { return(new ConsoleErrorResultModel(ex.Message)); } } if (this.Approved.HasValue && userInfo.Membership.Approved != this.Approved.Value) { this._usersController.UpdateAuthorizeStatus(userInfo, userInfo.PortalID, this.Approved.Value); sbResults.Append(this.LocalizeString(this.Approved.Value ? "UserAuthorized" : "UserUnAuthorized")); } var basicUpdated = !string.IsNullOrEmpty(this.Username) || !string.IsNullOrEmpty(this.DisplayName) || !string.IsNullOrEmpty(this.FirstName) || !string.IsNullOrEmpty(this.LastName) || !string.IsNullOrEmpty(this.Email); var userBasicDto = new UserBasicDto { Displayname = userInfo.DisplayName, UserId = userInfo.UserID, Email = userInfo.Email, IsDeleted = userInfo.IsDeleted, Username = userInfo.Username, Firstname = userInfo.FirstName, Lastname = userInfo.LastName }; // Update Username if (!string.IsNullOrEmpty(this.Username)) { userBasicDto.Username = this.Username; } // Update other properties if (!string.IsNullOrEmpty(this.DisplayName)) { userBasicDto.Displayname = this.DisplayName; } if (!string.IsNullOrEmpty(this.FirstName)) { userBasicDto.Firstname = this.FirstName; } if (!string.IsNullOrEmpty(this.LastName)) { userBasicDto.Lastname = this.LastName; } if (!string.IsNullOrEmpty(this.Email)) { userBasicDto.Email = this.Email; } if (basicUpdated) { try { this._usersController.UpdateUserBasicInfo(userBasicDto, userInfo.PortalID); } catch (SqlException) { return(new ConsoleErrorResultModel(this.LocalizeString("UsernameNotUnique") + "\n" + sbResults)); } catch (Exception ex) { return(new ConsoleErrorResultModel(ex.Message + sbResults)); } } // retrieve the updated user var updatedUser = this._userControllerWrapper.GetUserById(userInfo.PortalID, userInfo.UserID); var lst = new List <UserModel> { new UserModel(updatedUser) }; return(new ConsoleResultModel(string.Empty) { Data = lst, Records = lst.Count, FieldOrder = UserModel.FieldOrder, Output = this.LocalizeString("UserUpdated") }); }