private void GetAndBulkUpdateUsers() { // Prepare the parameters // Get the data DataSet users = UserInfoProvider.GetUsers(null, null); if (!DataHelper.DataSourceIsEmpty(users)) { // Loop through the individual items foreach (DataRow userDr in users.Tables[0].Rows) { // Create object from DataRow UserInfo modifyUser = new UserInfo(userDr); // Update the properties // modifyUser.FullName = modifyUser.FullName.ToUpper(); // Save the changes // UserInfoProvider.SetUserInfo(modifyUser); int userId = modifyUser.UserID; int siteId = CMSContext.CurrentSiteID; // Save the binding UserSiteInfoProvider.AddUserToSite(userId, siteId); } } }
/// <summary> /// Adds user to site. Called when the "Add user to site" button is pressed. /// Expects the CreateUser method to be run first. /// </summary> private bool AddUserToSite() { // Get the user UserInfo user = UserInfoProvider.GetUserInfo("MyNewUser"); if (user != null) { int userId = user.UserID; int siteId = CMSContext.CurrentSiteID; // Save the binding UserSiteInfoProvider.AddUserToSite(userId, siteId); return(true); } return(false); }
protected void SaveSites() { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } // Remove old items string newValues = ValidationHelper.GetString(usSites.Value, null); string items = DataHelper.GetNewItemsInList(newValues, currentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { int siteId = ValidationHelper.GetInteger(item, 0); // remove user from the site UserInfoProvider.RemoveUserFromSite(userId, siteId); // Remove user's allowed cultures for this site UserCultureInfoProvider.RemoveUserFromSite(userId, siteId); } } } // Add new items items = DataHelper.GetNewItemsInList(currentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { bool falseValues = false; // Add all new items to site foreach (string item in newItems) { int siteId = ValidationHelper.GetInteger(item, 0); SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { if (ui.IsEditor) { if (!UserInfoProvider.LicenseVersionCheck(si.DomainName, FeatureEnum.Editors, VersionActionEnum.Insert, false)) { falseValues = true; ShowError(GetString("LicenseVersion.EditorSite")); continue; } } if (!UserInfoProvider.LicenseVersionCheck(si.DomainName, FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { falseValues = true; ShowError(GetString("LicenseVersion.SiteMembersSite")); continue; } // Check if email would be unique in site if (UserInfoProvider.IsEmailUnique(ui.Email, si.SiteName, ui.UserID)) { UserSiteInfoProvider.AddUserToSite(ui, si); } else { falseValues = true; ShowError(GetString("UserInfo.EmailAlreadyExistInSomeSite")); } } } // If some of sites could not be assigned reload selector value if (falseValues) { usSites.Value = GetUserSites(); usSites.Reload(true); } } } ShowChangesSaved(); }
private static void ImportWorker_DoWork(object sender, DoWorkEventArgs e) { try { BackgroundWorker worker = (BackgroundWorker)sender; // Save import profile if (ImportProfile.SaveImportProfile && !ImportProfile.UsesConsole) { SaveFile(SaveImportProfile); } // Decide whether to import if (!ImportProfile.ImportNow && !ImportProfile.UsesConsole) { return; } using (new CMSActionContext() { LogEvents = false, ContinuousIntegrationAllowObjectSerialization = false }) { #region "Initialization" // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } DateTime start = DateTime.Now; // Initialize CMS context CMSInit(); if (ImportProfile.UsesConsole) { // Ensure object in case they are not present in import profile EnsureObjects(); } if (ImportProfile.ImportUsersOnlyFromSelectedRoles) { // Narrow down imported users according to imported roles ImportProfile.Users.Clear(); } // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } // Initialize cumulative changed users and roles storages var rolesChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.RolesCreated, WellKnownEventLogEventsEnum.RolesUpdated, WellKnownEventLogEventsEnum.RolesDeleted); var usersChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.UsersCreated, WellKnownEventLogEventsEnum.UsersUpdated, WellKnownEventLogEventsEnum.UsersDeleted); #endregion // Delete non-existing objects (this also prevents conflicting code names) if (ImportProfile.DeleteNotExistingObjects) { DeleteNonExistingObjects(usersChanged, rolesChanged); } #region "Role import" foreach (var siteInfo in ImportProfile .Sites .Select(site => SiteInfoProvider.GetSiteInfo(site.Key)) .Where(info => info != null)) { foreach (Guid groupGuid in ImportProfile.Groups) { // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } // Try to get group IPrincipalObject group = PrincipalProvider.GetPrincipalObject(groupGuid); // If group is still null if (group == null) { MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject")); warnings++; // If deleting of not existing objects is enabled if (ImportProfile.DeleteNotExistingObjects) { DeleteRole(siteInfo, groupGuid); } } else { // Get role description string roleDescription = String.Empty; if (ImportProfile.ImportRoleDescription && (group.Description != null)) { roleDescription = group.Description; } // Get correct role name format string roleCodeName = group.GetCMSCodeName(true); // Get role display name string roleDisplayName = group.GetCMSDisplayName(); // Get safe role name roleCodeName = ValidationHelper.GetSafeRoleName(roleCodeName, siteInfo.SiteName); if (!String.IsNullOrEmpty(roleCodeName)) { // Add message to log MessageLog.LogEvent(ResHelper.GetString("Log_ImportingRole", roleDisplayName, CMS.Helpers.ResHelper.LocalizeString(siteInfo.DisplayName))); // Import role ImportRole(roleCodeName, roleDisplayName, siteInfo.SiteID, roleDescription, groupGuid, ImportProfile.UpdateObjectData, rolesChanged); if (ImportProfile.ImportUsersOnlyFromSelectedRoles) { ImportProfile.Users.AddRange(PrincipalProvider.GetUsersOf(group).Select(u => u.Identifier)); } } else { // Add message to log MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyRolename", group.Identifier)); warnings++; } } } } // Log created and updated and removed roles to EventLog rolesChanged.WriteEventsToEventLog(); #endregion #region "User import" foreach (var user in ImportProfile .Users .Distinct() .Select(userGuid => PrincipalProvider.GetPrincipalObject(userGuid))) { // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } if (user == null) { MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject")); continue; } string domainName = user.GetCMSCodeName(true); if (!String.IsNullOrEmpty(domainName)) { // Get user info object UserInfo userInfo = (UserInfoProvider.GetUserInfoByGUID((Guid)user.Identifier) ?? UserInfoProvider.GetUserInfo(domainName)); bool newUser = (userInfo == null); // When is desired to import new users only from selected roles if (newUser && ImportProfile.ImportNewUsersOnlyFromSelectedRoles) { // Skip users that does not belong to one of selected role bool skip = ImportProfile.Groups.Cast <Guid>().All(groupGuid => !user.IsPrincipalInGroup(groupGuid)); if (skip) { MessageLog.LogEvent(ResHelper.GetString("Log_SkippingDoesNotBelongToSelectedRole", domainName)); continue; } } if (ImportProfile.UpdateObjectData || newUser) { if (userInfo == null) { userInfo = new UserInfo(); // Add message to log MessageLog.LogEvent(ResHelper.GetString("Log_ImportingUser", domainName)); } else { // Add message to log MessageLog.LogEvent(ResHelper.GetString("Log_UpdatingUser", domainName)); } using (var transaction = new CMSTransactionScope()) { if (newUser) { userInfo.UserIsDomain = true; userInfo.UserGUID = (Guid)user.Identifier; // Set privilege level UserPrivilegeLevelEnum privilegeLevel = ImportProfile.ConfigureAsCMSEditor ? UserPrivilegeLevelEnum.Editor : UserPrivilegeLevelEnum.None; userInfo.SiteIndependentPrivilegeLevel = privilegeLevel; } if (userInfo.UserIsDomain) { // Set user's properties userInfo.UserIsExternal = true; userInfo.UserName = domainName; userInfo.Enabled = ValidationHelper.GetBoolean(user.Enabled, true); // Bind properties foreach (KeyValuePair <string, string> property in ImportProfile.UserProperties) { // Get attribute object attribute = user.GetProperty(property.Value); if (attribute != null) { try { string attrValue; // Get string representation of the attribute if (attribute is float || attribute is double || attribute is decimal) { attrValue = String.Format(CultureInfo.InvariantCulture, "{0}", attribute); } else if (attribute.GetType() == typeof(byte[])) { attrValue = PrincipalProvider.GetSID(attribute); } else if (attribute.GetType().BaseType == typeof(MarshalByRefObject)) { attrValue = PrincipalProvider.GetTimeFromInterval(attribute); } else { attrValue = attribute.ToString(); } // Set property userInfo.SetValue(property.Key, LimitLengthForField(attrValue, property.Key)); } catch { MessageLog.LogEvent(ResHelper.GetString("Log_ErrorParsingAttr", property.Value)); warnings++; } } else { FormFieldInfo field = UserFormInfo.GetFormField(property.Key); userInfo.SetValue(property.Key, field.GetPropertyValue(FormFieldPropertyEnum.DefaultValue)); } } // Create full name if empty if (String.IsNullOrEmpty(userInfo.FullName)) { userInfo.FullName = user.GetCMSDisplayName(); } // Store user info object and its user-settings if (userInfo.ChangedColumns().Any()) { // Store created/updated user for EventLog // User name is used, because AD accounts does not have to have first and/or given name specified (e.g. Guest, …) usersChanged.Add(userInfo.UserGUID, userInfo.UserName, newUser ? ChangeActionEnum.Created : ChangeActionEnum.Updated); UserInfoProvider.SetUserInfo(userInfo); } } else { MessageLog.LogEvent(ResHelper.GetString("Log_UserIsNotDomain", userInfo.UserName)); warnings++; } transaction.Commit(); } } else { MessageLog.LogEvent(ResHelper.GetString("Log_SkippingExistingUser", domainName)); } // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } // Assign user to sites and roles (for domain users only) if (!userInfo.UserIsDomain) { continue; } #region "Membership (roles) synchronization" if (!newUser && !ImportProfile.UpdateMemberships && !ImportProfile.UpdateMemberships) { // No membership synchronization will be performed continue; } // Initialize collection to cumulate membership changes var memberShipChanges = new CumulatedRolesMembership(); // Load all user roles from DB var userRoles = new HashSet <RoleInfo>(newUser ? Enumerable.Empty <RoleInfo>() // non-existing user cannot be present in a single role (in DB) : RoleInfoProvider .GetRoles() .WhereIn("RoleID", UserRoleInfoProvider .GetUserRoles() .WhereEquals("UserID", userInfo.UserID) .Column("RoleID")) .Columns("RoleID", "RoleGUID", "RoleDisplayName", "RoleIsDomain")); // Store user's roles before membership synchronization memberShipChanges.SetRolesBefore(userRoles); foreach (KeyValuePair <string, List <Guid> > site in ImportProfile.Sites) { // Get site info object var siteInfo = SiteInfoProvider.GetSiteInfo(site.Key); if (siteInfo != null) { try { // Add user to this site UserSiteInfoProvider.AddUserToSite(userInfo, siteInfo); } catch (Exception ex) { MessageLog.LogEvent(ResHelper.GetString("Log_GeneralWarning", ex.Message)); warnings++; } // Assign user to roles already existing in CMS if (newUser || ImportProfile.UpdateMemberships) { SetMemberships(user, userInfo, siteInfo, userRoles, site); } // Remove user from roles they is member no more if (!newUser && ImportProfile.UpdateMemberships) { RemoveExcessiveMemberships(user, userInfo, userRoles); } } else { MessageLog.LogEvent(ResHelper.GetString("Log_SiteNotExist", site.Key)); warnings++; } } // Store user's roles after membership synchronization memberShipChanges.SetRolesAfter(userRoles); // Log created and removed memberships to EventLog memberShipChanges.WriteEventsToEventLog(userInfo.UserName); #endregion } else { // Add message to log MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyUsername", user.Identifier)); warnings++; } } // Log created and updated and deleted users to EventLog usersChanged.WriteEventsToEventLog(); #endregion // Import canceled if (worker.CancellationPending) { e.Cancel = true; return; } TimeSpan duration = DateTime.Now - start; if (!worker.CancellationPending) { // Add message to log MessageLog.LogEvent(warnings == 0 ? ResHelper.GetString("Log_ImportComplete", duration.Hours, duration.Minutes, duration.Seconds) : ResHelper.GetString("Log_ImportCompleteWithWarnings", warnings, duration.Hours, duration.Minutes, duration.Seconds)); } } } catch (Exception ex) { MessageLog.LogError(ResHelper.GetString("Error_General"), ex); } }
public void ProcessRequest(HttpContext context) { var authorizationResponse = new AuthorizationResponse(); // If response_type is "code id_token", the authorization endpoint will give us back //4 values. // i) code: used in order to exchange the access token // ii) id_token: contains user's authentication information in an encoded format // iii) scope: the access privileges requested for access token // iv) session_state: allows you to restore the previous state of your application // // If response_type is "code", the authorization endpoint will give us back 2 values: // i) code: used in order to exchange the access token // ii) state: provide by us; allows you to restore the previous state of your application // Begin by determining whether authorization (code) or hybrid flow (code id_token) if (OAuthConfiguration.ResponseType == "CodeIdToken") { authorizationResponse.PopulateFrom(context.Request.Form); } else { authorizationResponse.Code = context.Request.QueryString["code"]; authorizationResponse.State = context.Request.QueryString["state"]; } // Check if authorization code is present in the response. if (string.IsNullOrEmpty(authorizationResponse.Code)) { throw new Exception("Authorization code is not present in the response."); } var tokenEndpoint = OAuthConfiguration.Authority + "/" + OAuthConfiguration.TokenEndpointPath; var userInfoEndpoint = OAuthConfiguration.Authority + "/" + OAuthConfiguration.UserInfoEndpointPath; // Use the authorization code to retrieve access and id tokens. var tokenResponse = Task.Run(() => HttpClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { Address = tokenEndpoint, ClientId = OAuthConfiguration.ClientId, ClientSecret = OAuthConfiguration.ClientSecret, Code = authorizationResponse.Code, RedirectUri = $"{OAuthConfiguration.Host}/SignInOidc.ashx" })) .ConfigureAwait(false) .GetAwaiter() .GetResult(); if (tokenResponse.IsError) { throw new Exception("There was an error retrieving the access token.", tokenResponse.Exception); } // If using an authorization code flow, we get the id_token from the token endpoint // so we populate it now into the authorizationResponse object if (OAuthConfiguration.ResponseType == "Code") { authorizationResponse.IdToken = tokenResponse.Json["id_token"].ToString(); } // Get user claims by calling the user info endpoint using the access token. var userInfoResponse = Task.Run(() => HttpClient.GetUserInfoAsync(new UserInfoRequest { Address = userInfoEndpoint, Token = tokenResponse.AccessToken })) .ConfigureAwait(false) .GetAwaiter() .GetResult(); //LOGGING// StreamWriter sw5 = new StreamWriter("c:\\docs\\logfile1.txt", append: true); sw5.WriteLine("The token response is: " + tokenResponse.Json); sw5.WriteLine("The endpoint is: " + userInfoEndpoint); sw5.WriteLine("The error is: " + userInfoResponse.Error); sw5.WriteLine("The raw is: " + userInfoResponse.Raw); sw5.Close(); //END LOGGING// if (userInfoResponse.IsError) { throw new Exception("There was an error retrieving user information from authority.", userInfoResponse.Exception); } // It is important to get the email claim and check if the user exists locally. var userClaims = userInfoResponse.Claims; //Commented out from original code //var userName = userClaims.GetValueOrDefault(OAuthConfiguration.UserNameClaim ?? JwtClaimTypes.Name); var userName = userInfoResponse.Json[OAuthConfiguration.UserNameClaim].ToString(); var email = userClaims.GetValueOrDefault(JwtClaimTypes.Email); if (string.IsNullOrEmpty(userName)) { throw new Exception("Username cannot be found in user claims."); } // Check if the user exists in Kentico. UserInfo userInfo = UserInfoProvider.GetUserInfo(userName); // Get admin claim so we can decide if we need to assign a specific role to the user. var isAdmin = userClaims.GetValueOrDefault <bool>(CustomClaimTypes.Admin); // In this case we need to create the user. if (userInfo == null) { var firstName = userClaims.GetValueOrDefault(JwtClaimTypes.GivenName); var lastName = userClaims.GetValueOrDefault(JwtClaimTypes.FamilyName); // Creates a new user object. userInfo = new UserInfo { // Sets the user properties. Email = email, Enabled = true, FirstName = firstName, FullName = $"{firstName} {lastName}", IsExternal = true, LastName = lastName, SiteIndependentPrivilegeLevel = isAdmin ? UserPrivilegeLevelEnum.GlobalAdmin : UserPrivilegeLevelEnum.None, UserCreated = DateTime.UtcNow, UserName = userName, UserIsDomain = true }; // Created user must first be created and saved so we can update other properties in the next steps. UserInfoProvider.SetUserInfo(userInfo); UserSiteInfoProvider.AddUserToSite(userInfo.UserID, SiteContext.CurrentSite.SiteID); var handler = UserCreated; handler?.Invoke(this, new UserCreatedEventArgs { User = userInfo, Claims = userClaims }); } else { // Update existing user's privilege level to reflect a possible change made on IdentityServer. if (isAdmin) { userInfo.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.GlobalAdmin; } userInfo.UserIsDomain = true; var userCurrentSite = UserSiteInfoProvider.GetUserSiteInfo(userInfo.UserID, SiteContext.CurrentSiteID); if (userCurrentSite == null) { UserSiteInfoProvider.AddUserToSite(userInfo.UserID, SiteContext.CurrentSiteID); } UserInfoProvider.SetUserInfo(userInfo); } // Log the user in. AuthenticateUser(userInfo.UserName, true); CookiesHelper.SetValue( name: CookieNames.OAuthCookie, values: new Dictionary <string, string> { { OidcConstants.TokenTypes.AccessToken, tokenResponse.AccessToken }, { OidcConstants.TokenTypes.RefreshToken, tokenResponse.RefreshToken }, { OidcConstants.TokenResponse.ExpiresIn, tokenResponse.ExpiresIn.ToString() }, { OidcConstants.ResponseTypes.IdToken, tokenResponse.IdentityToken } }, expires: DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn) ); // Try to retrieve state in order to navigate the user back to where he initially requested. var returnUrl = "/"; if (!string.IsNullOrEmpty(authorizationResponse.State)) { var stateProvider = new StateProvider <string>(); var state = stateProvider.RetrieveState(authorizationResponse.State); if (state != "") { returnUrl = state; } else { returnUrl = OAuthConfiguration.Host; } } //LOGGING// StreamWriter sw6 = new StreamWriter("c:\\docs\\logfile1.txt", append: true); sw6.WriteLine("The URL is: " + returnUrl); sw6.Close(); //END LOGGING// // Redirect to the requested page. context.Response.Redirect(returnUrl); HttpContext.Current.ApplicationInstance.CompleteRequest(); }