/// <summary> /// Adds a locale to the system. Throws exception if the given locale has already been installed or /// if the given url mapping name has already been used. If the given locale is the first, its set /// to be the default locale. /// </summary> /// <param name="cultureInfo"></param> /// <param name="urlMappingName"></param> /// <param name="addAccessToAllUsers"></param> /// <param name="makeFlush"></param> /// <param name="isDefault"></param> internal static void AddLocale(CultureInfo cultureInfo, string urlMappingName, bool addAccessToAllUsers, bool makeFlush, bool isDefault) { using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope()) { Verify.That(!IsLocaleInstalled(cultureInfo), "The locale '{0}' has already been added to the system", cultureInfo); Verify.That(!IsUrlMappingNameInUse(urlMappingName), "The url mapping name '{0}' has already been used in the system", urlMappingName); if (!DataLocalizationFacade.ActiveLocalizationCultures.Any()) { addAccessToAllUsers = true; } var systemActiveLocale = DataFacade.BuildNew <ISystemActiveLocale>(); systemActiveLocale.Id = Guid.NewGuid(); systemActiveLocale.CultureName = cultureInfo.Name; systemActiveLocale.UrlMappingName = urlMappingName; systemActiveLocale.IsDefault = isDefault; DataFacade.AddNew(systemActiveLocale); if (addAccessToAllUsers) { List <string> usernames = (from u in DataFacade.GetData <IUser>() select u.Username).ToList(); foreach (string username in usernames) { UserSettings.AddActiveLocaleCultureInfo(username, cultureInfo); if (UserSettings.GetCurrentActiveLocaleCultureInfo(username) == null) { UserSettings.SetCurrentActiveLocaleCultureInfo(username, cultureInfo); UserSettings.SetForeignLocaleCultureInfo(username, cultureInfo); } } } if (DataLocalizationFacade.DefaultLocalizationCulture == null) { DataLocalizationFacade.DefaultLocalizationCulture = cultureInfo; } transactionScope.Complete(); } DynamicTypeManager.AddLocale(cultureInfo); if (makeFlush) { C1Console.Events.GlobalEventSystemFacade.FlushTheSystem(false); } }
private void finalizeCodeActivity_ExecuteCode(object sender, EventArgs e) { AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken); IUser newUser = this.GetBinding <IUser>(BindingNames.NewUser); var bindedUserFormLogin = this.GetBinding <IUserFormLogin>(BindingNames.UserFormLogin); NormalizeUsername(newUser); string password = this.GetBinding <string>(BindingNames.Password); newUser = DataFacade.AddNew <IUser>(newUser); UserFormLoginManager.CreateUserFormLogin(newUser.Id, password, bindedUserFormLogin.Folder); string cultureName = this.GetBinding <string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding <string>("C1ConsoleUiLanguageName"); UserSettings.SetUserCultureInfo(newUser.Username, CultureInfo.CreateSpecificCulture(cultureName)); UserSettings.SetUserC1ConsoleUiLanguage(newUser.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName)); CultureInfo locale = DataLocalizationFacade.DefaultLocalizationCulture; UserSettings.AddActiveLocaleCultureInfo(newUser.Username, locale); UserSettings.SetCurrentActiveLocaleCultureInfo(newUser.Username, locale); UserSettings.SetForeignLocaleCultureInfo(newUser.Username, locale); this.CloseCurrentView(); addNewTreeRefresher.PostRefreshMesseges(newUser.GetDataEntityToken()); LoggingService.LogEntry("UserManagement", $"New C1 Console user '{newUser.Username}' created by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); this.ExecuteWorklow(newUser.GetDataEntityToken(), typeof(EditUserWorkflow)); }
private void saveCodeActivity_ExecuteCode(object sender, EventArgs e) { IUser user = this.GetBinding <IUser>(BindingNames.User); var userFormLogin = GetBinding <IUserFormLogin>(BindingNames.UserFormLogin); var userFormLoginFromDatabase = user.GetUserFormLogin(); bool userValidated = true; ValidationResults validationResults = ValidationFacade.Validate(user); foreach (ValidationResult result in validationResults) { this.ShowFieldMessage($"{BindingNames.User}.{result.Key}", result.Message); userValidated = false; } List <CultureInfo> newActiveLocales = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList(); List <CultureInfo> currentActiveLocales = null; CultureInfo selectedActiveLocal = null; if (newActiveLocales.Count > 0) { currentActiveLocales = UserSettings.GetActiveLocaleCultureInfos(user.Username).ToList(); string selectedActiveLocaleName = (user.Username != UserSettings.Username ? this.GetBinding <string>("ActiveLocaleName") : UserSettings.ActiveLocaleCultureInfo.ToString()); if (selectedActiveLocaleName != null) { selectedActiveLocal = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName); if (!newActiveLocales.Contains(selectedActiveLocal)) { if (user.Username != UserSettings.Username) { this.ShowFieldMessage("ActiveLocaleName", GetText("Website.Forms.Administrative.EditUserStep1.ActiveLocaleNotChecked")); } else { this.ShowFieldMessage("ActiveLocalesFormsHelper_Selected", GetText("Website.Forms.Administrative.EditUserStep1.NoActiveLocaleSelected")); } userValidated = false; } } } else { this.ShowFieldMessage("ActiveLocalesFormsHelper_Selected", GetText("Website.Forms.Administrative.EditUserStep1.NoActiveLocaleSelected")); userValidated = false; } string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken); List <Guid> newUserGroupIds = UserGroupsFormsHelper.GetSelectedUserGroupIds(this.Bindings); List <string> newSerializedEnitityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList(); if (string.Compare(user.Username, UserSettings.Username, StringComparison.InvariantCultureIgnoreCase) == 0) { // Current user shouldn't be able to lock itself if (userFormLogin.IsLocked) { this.ShowMessage(DialogType.Message, Texts.EditUserWorkflow_EditErrorTitle, Texts.EditUserWorkflow_LockingOwnUserAccount); userValidated = false; } // Current user shouldn't be able to remove its own access to "System" perspective var groupsWithAccessToSystemPerspective = new HashSet <Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken)); if (!newSerializedEnitityTokens.Contains(systemPerspectiveEntityToken) && !newUserGroupIds.Any(groupsWithAccessToSystemPerspective.Contains)) { this.ShowMessage(DialogType.Message, Texts.EditUserWorkflow_EditErrorTitle, Texts.EditUserWorkflow_EditOwnAccessToSystemPerspective); userValidated = false; } } string newPassword = this.GetBinding <string>(BindingNames.NewPassword); if (newPassword == NotPassword || UserFormLoginManager.ValidatePassword(userFormLoginFromDatabase, newPassword)) { newPassword = null; } else { IList <string> validationMessages; if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out validationMessages)) { foreach (var message in validationMessages) { this.ShowFieldMessage(BindingNames.NewPassword, message); } userValidated = false; } } if (!userValidated) { return; } if (!userFormLogin.IsLocked) { userFormLogin.LockoutReason = (int)UserLockoutReason.Undefined; } else { bool wasLockedBefore = userFormLoginFromDatabase.IsLocked; if (!wasLockedBefore) { userFormLoginFromDatabase.LockoutReason = (int)UserLockoutReason.LockedByAdministrator; } } UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken); bool reloadUsersConsoles = false; using (var transactionScope = TransactionsFacade.CreateNewScope()) { DataFacade.Update(user); userFormLoginFromDatabase.Folder = userFormLogin.Folder; userFormLoginFromDatabase.IsLocked = userFormLogin.IsLocked; DataFacade.Update(userFormLoginFromDatabase); if (newPassword != null) { UserFormLoginManager.SetPassword(userFormLoginFromDatabase, newPassword); } string cultureName = this.GetBinding <string>("CultureName"); string c1ConsoleUiLanguageName = this.GetBinding <string>("C1ConsoleUiLanguageName"); UserSettings.SetUserCultureInfo(user.Username, CultureInfo.CreateSpecificCulture(cultureName)); UserSettings.SetUserC1ConsoleUiLanguage(user.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName)); List <string> existingSerializedEntityTokens = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList(); int intersectCount = existingSerializedEntityTokens.Intersect(newSerializedEnitityTokens).Count(); if ((intersectCount != newSerializedEnitityTokens.Count) || (intersectCount != existingSerializedEntityTokens.Count)) { UserPerspectiveFacade.SetSerializedEntityTokens(user.Username, newSerializedEnitityTokens); if (UserSettings.Username == user.Username) { reloadUsersConsoles = true; } } if (DataLocalizationFacade.ActiveLocalizationCultures.Any()) { foreach (CultureInfo cultureInfo in newActiveLocales) { if (!currentActiveLocales.Contains(cultureInfo)) { UserSettings.AddActiveLocaleCultureInfo(user.Username, cultureInfo); } } foreach (CultureInfo cultureInfo in currentActiveLocales) { if (!newActiveLocales.Contains(cultureInfo)) { UserSettings.RemoveActiveLocaleCultureInfo(user.Username, cultureInfo); } } if (selectedActiveLocal != null) { if (!UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username).Equals(selectedActiveLocal)) { reloadUsersConsoles = true; } UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, selectedActiveLocal); } else if (UserSettings.GetActiveLocaleCultureInfos(user.Username).Any()) { UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, UserSettings.GetActiveLocaleCultureInfos(user.Username).First()); } } List <IUserUserGroupRelation> oldRelations = DataFacade.GetData <IUserUserGroupRelation>(f => f.UserId == user.Id).ToList(); IEnumerable <IUserUserGroupRelation> deleteRelations = from r in oldRelations where !newUserGroupIds.Contains(r.UserGroupId) select r; DataFacade.Delete(deleteRelations); foreach (Guid newUserGroupId in newUserGroupIds) { Guid groupId = newUserGroupId; if (oldRelations.Any(f => f.UserGroupId == groupId)) { continue; } var userUserGroupRelation = DataFacade.BuildNew <IUserUserGroupRelation>(); userUserGroupRelation.UserId = user.Id; userUserGroupRelation.UserGroupId = newUserGroupId; DataFacade.AddNew(userUserGroupRelation); } LoggingService.LogEntry("UserManagement", $"C1 Console user '{user.Username}' updated by '{UserValidationFacade.GetUsername()}'.", LoggingService.Category.Audit, TraceEventType.Information); transactionScope.Complete(); } if (reloadUsersConsoles) { foreach (string consoleId in GetConsoleIdsOpenedByCurrentUser()) { ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), consoleId); } } SetSaveStatus(true); updateTreeRefresher.PostRefreshMesseges(user.GetDataEntityToken()); }
/// <summary> /// Used for "first time" login on systems configured for this. A way to create the first user. This only works on systems /// with no users and with a valid "auto create admin username" specified by the global settings. /// </summary> /// <param name="userName">The user name - must match GlobalSettingsProvider.AutoCreatedAdministratorUserName</param> /// <param name="password">A password that meets a minimum requirement.</param> /// <param name="email">THe users email.</param> /// <param name="validateAutoCreateUserName">When true only the username specified in Composite.config as auto createable (usually 'admin') is allowed. Set to false to use a different user name.</param> /// <returns>true if the user was auto created. Otherwise false.</returns> public static void AutoCreateAdministrator(string userName, string password, string email, bool validateAutoCreateUserName = true) { if (validateAutoCreateUserName && !CanBeAutoCreated(userName)) { throw new InvalidOperationException("Unable to auto create account. Either the user name is not eligble for auto creation or other users exists in the system. This feature only works for a specific user name and when no users exists."); } if (!LoginProviderPluginFacade.CanAddNewUser) { throw new InvalidOperationException("Unable to auto create account. The current login provider does not support adding users"); } if (!PermissionTypeFacade.CanAlterDefinitions) { throw new InvalidOperationException("Unable to auto create account. The current permission defintion provider does not support changes"); } //PasswordValidator validator = new PasswordValidator(); //ValidationResults validationResults = validator.Validate(password); //if (validationResults.IsValid == false) //{ // throw new InvalidOperationException("Unable to auto create account. The specified password is not strong enough."); //} // All seems bo be ok green light go for auto creating the user. string group = StringResourceSystemFacade.GetString("Composite.C1Console.Users", "AdministratorAutoCreator.DefaultGroupName"); LoginProviderPluginFacade.FormAddNewUser(userName, password, group, email); Log.LogVerbose("AdministratorAutoCreator", String.Format("Auto Created Administrator with user name '{0}'.", userName), LoggingService.Category.Audit); IUser user = DataFacade.GetData <IUser>().Where(f => f.Username == userName).SingleOrDefault(); IUserGroup userGroup = DataFacade.GetData <IUserGroup>().Where(f => f.Name == "Administrator").SingleOrDefault(); if (user != null && userGroup != null) { IUserUserGroupRelation userUserGroupRelation = DataFacade.BuildNew <IUserUserGroupRelation>(); userUserGroupRelation.UserId = user.Id; userUserGroupRelation.UserGroupId = userGroup.Id; DataFacade.AddNew <IUserUserGroupRelation>(userUserGroupRelation); } else { foreach (Element appRootElement in ElementFacade.GetRootsWithNoSecurity()) { string serializedEntityToken = EntityTokenSerializer.Serialize(appRootElement.ElementHandle.EntityToken); LoggingService.LogVerbose("AdministratorAutoCreator", String.Format("Adding '{0}' on element '{1}' ('{2}').", userName, appRootElement.VisualData.Label ?? "(no label)", serializedEntityToken), LoggingService.Category.Audit); UserPermissionDefinition userPermissionDefinition = new ConstructorBasedUserPermissionDefinition(userName, PermissionTypeFacade.GrantingPermissionTypes, serializedEntityToken); PermissionTypeFacade.SetUserPermissionDefinition(userPermissionDefinition); } Log.LogVerbose("AdministratorAutoCreator", string.Format("Activating all known perspectives for user '{0}'", userName)); IEnumerable <EntityToken> perspectiveEntityTokens = ElementFacade.GetPerspectiveElementsWithNoSecurity().Select(f => f.ElementHandle.EntityToken); UserPerspectiveFacade.SetEntityTokens(userName, perspectiveEntityTokens); } foreach (CultureInfo cultureInfo in DataLocalizationFacade.ActiveLocalizationCultures) { UserSettings.AddActiveLocaleCultureInfo(userName, cultureInfo); if (Core.Localization.LocalizationFacade.IsDefaultLocale(cultureInfo)) { UserSettings.SetCurrentActiveLocaleCultureInfo(userName, cultureInfo); UserSettings.SetForeignLocaleCultureInfo(userName, cultureInfo); } } }