/// <summary> /// Sets the current user so that checking authentication and roles works. /// </summary> /// <remarks> /// Copies functionality from <c>DotNetNuke.HttpModules.Membership.MembershipModule.OnAuthenticateRequest</c> /// to get the current user set as the "Current User" /// </remarks> private void SetCurrentUser() { // Obtain PortalSettings from Current Context var portalSettings = PortalController.GetCurrentPortalSettings(); if (this.Context.Request.IsAuthenticated && portalSettings != null) { var roleController = new RoleController(); var cachedUser = UserController.GetCachedUser(portalSettings.PortalId, this.Context.User.Identity.Name); if (this.Context.Request.Cookies["portalaliasid"] != null) { // ReSharper disable PossibleNullReferenceException var portalCookie = FormsAuthentication.Decrypt(this.Context.Request.Cookies["portalaliasid"].Value); // check if user has switched portals if (portalSettings.PortalAlias.PortalAliasID != int.Parse(portalCookie.UserData)) { // expire cookies if portal has changed this.Context.Response.Cookies["portalaliasid"].Value = null; this.Context.Response.Cookies["portalaliasid"].Path = "/"; this.Context.Response.Cookies["portalaliasid"].Expires = DateTime.Now.AddYears(-30); this.Context.Response.Cookies["portalroles"].Value = null; this.Context.Response.Cookies["portalroles"].Path = "/"; this.Context.Response.Cookies["portalroles"].Expires = DateTime.Now.AddYears(-30); // ReSharper restore PossibleNullReferenceException } } // authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set ) if (cachedUser == null || cachedUser.IsDeleted || cachedUser.Membership.LockedOut || cachedUser.Membership.Approved == false || cachedUser.Username.ToLower() != this.Context.User.Identity.Name.ToLower()) { var portalSecurity = new PortalSecurity(); portalSecurity.SignOut(); // Remove user from cache if (cachedUser != null) { DataCache.ClearUserCache(portalSettings.PortalId, this.Context.User.Identity.Name); } // Redirect browser back to home page this.Context.Response.Redirect(this.Context.Request.RawUrl, true); return; } // valid Auth cookie // if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity if ( DateTime.Compare( cachedUser.Membership.LastActivityDate.AddMinutes(Host.UsersOnlineTimeWindow), DateTime.Now) < 0) { // update LastActivityDate and IP Address for user cachedUser.Membership.LastActivityDate = DateTime.Now; cachedUser.LastIPAddress = this.Context.Request.UserHostAddress; UserController.UpdateUser(portalSettings.PortalId, cachedUser); } // refreshroles is set when a role is added to a user by an administrator bool refreshCookies = cachedUser.RefreshRoles; // check for RSVP code if (!cachedUser.RefreshRoles && this.Context.Request.QueryString["rsvp"] != null && string.IsNullOrEmpty(this.Context.Request.QueryString["rsvp"]) == false) { foreach (RoleInfo objRole in roleController.GetPortalRoles(portalSettings.PortalId)) { if (objRole.RSVPCode == this.Context.Request.QueryString["rsvp"]) { roleController.UpdateUserRole(portalSettings.PortalId, cachedUser.UserID, objRole.RoleID); // clear portalroles so the new role is added to the cookie below refreshCookies = true; } } } // create cookies if they do not exist yet for this session. if (this.Context.Request.Cookies["portalroles"] == null || refreshCookies) { // keep cookies in sync var currentDateTime = DateTime.Now; // create a cookie authentication ticket ( version, user name, issue time, expires every hour, don't persist cookie, roles ) var portalTicket = new FormsAuthenticationTicket( 1, this.Context.User.Identity.Name, currentDateTime, currentDateTime.AddHours(1), false, portalSettings.PortalAlias.PortalAliasID.ToString()); // encrypt the ticket string portalAliasId = FormsAuthentication.Encrypt(portalTicket); // ReSharper disable PossibleNullReferenceException // send portal cookie to client this.Context.Response.Cookies["portalaliasid"].Value = portalAliasId; this.Context.Response.Cookies["portalaliasid"].Path = "/"; this.Context.Response.Cookies["portalaliasid"].Expires = currentDateTime.AddMinutes(1); // ReSharper restore PossibleNullReferenceException // get roles from UserRoles table string[] arrPortalRoles = roleController.GetRolesByUser(cachedUser.UserID, portalSettings.PortalId); // create a string to persist the roles, attach a portalID so that cross-portal impersonation cannot occur string strPortalRoles = portalSettings.PortalId + "!!" + string.Join(";", arrPortalRoles); // create a cookie authentication ticket ( version, user name, issue time, expires every hour, don't persist cookie, roles ) var rolesTicket = new FormsAuthenticationTicket( 1, this.Context.User.Identity.Name, currentDateTime, currentDateTime.AddHours(1), false, strPortalRoles); // encrypt the ticket string strRoles = FormsAuthentication.Encrypt(rolesTicket); // ReSharper disable PossibleNullReferenceException // send roles cookie to client this.Context.Response.Cookies["portalroles"].Value = strRoles; this.Context.Response.Cookies["portalroles"].Path = "/"; this.Context.Response.Cookies["portalroles"].Expires = currentDateTime.AddMinutes(1); if (refreshCookies) { // if rsvp, update portalroles in context because it is being used later this.Context.Request.Cookies["portalroles"].Value = strRoles; } } if (this.Context.Request.Cookies["portalroles"] != null) { // get roles from roles cookie if (this.Context.Request.Cookies["portalroles"].Value != string.Empty) { var roleTicket = FormsAuthentication.Decrypt(this.Context.Request.Cookies["portalroles"].Value); // ReSharper restore PossibleNullReferenceException if (roleTicket != null) { // get the role data and split it into portalid and a string array of role data string rolesdata = roleTicket.UserData; char[] separator = "!!".ToCharArray(); // need to use StringSplitOptions.None to preserve case where superuser has no roles string[] rolesParts = rolesdata.Split(separator, StringSplitOptions.None); // if cookie is for a different portal than current force a refresh of roles else used cookie cached version if (Convert.ToInt32(rolesParts[0]) != portalSettings.PortalId) { cachedUser.Roles = roleController.GetRolesByUser(cachedUser.UserID, portalSettings.PortalId); } else { cachedUser.Roles = rolesParts[2].Split(';'); } } else { cachedUser.Roles = roleController.GetRolesByUser(cachedUser.UserID, portalSettings.PortalId); } // Clear RefreshRoles flag if (cachedUser.RefreshRoles) { cachedUser.RefreshRoles = false; UserController.UpdateUser(portalSettings.PortalId, cachedUser); } } // save userinfo object in context this.Context.Items.Add("UserInfo", cachedUser); // load the personalization object var personalizationController = new PersonalizationController(); personalizationController.LoadProfile(this.Context, cachedUser.UserID, cachedUser.PortalID); // Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded Localization.SetLanguage(cachedUser.Profile.PreferredLocale); } } if (HttpContext.Current.Items["UserInfo"] == null) { this.Context.Items.Add("UserInfo", new UserInfo()); } }
/// <summary> /// TransferUsers transfers legacy users to the new ASP.NET MemberRole Architecture /// </summary> /// <remarks> /// </remarks> /// <param name="PortalID">Id of the Portal</param> /// <param name="arrUsers">An ArrayList of the Users</param> /// <param name="SuperUsers">A flag indicating whether the users are SuperUsers</param> /// <history> /// [cnurse] 11/6/2004 documented /// [cnurse] 12/15/2005 Moved to MembershipProvider /// </history> private void TransferUsers( int PortalID, ArrayList arrUsers, bool SuperUsers ) { UserController objUserCont = new UserController(); try { //Set the MemberRole API ApplicationName if( SuperUsers ) { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Start Transferring SuperUsers to MemberRole:<br>" ); } else { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Start Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>" ); } IDataReader dr; string EncryptionKey = ""; dr = DotNetNuke.Data.DataProvider.Instance().GetHostSetting( "EncryptionKey" ); if( dr.Read() ) { EncryptionKey = dr["SettingValue"].ToString(); } dr.Close(); int i; int iMin = 1; int iMax = 100; for( i = 0; i <= arrUsers.Count - 1; i++ ) { if( i%100 == 0 ) { if( iMin > arrUsers.Count ) { iMin = arrUsers.Count; } if( iMax > arrUsers.Count ) { iMax = arrUsers.Count; } HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Transferring Users:" + iMin.ToString() + " to " + iMax.ToString() + "<br>" ); iMin = iMin + 100; iMax = iMax + 100; } UserInfo objUser; objUser = (UserInfo)arrUsers[i]; MembershipCreateStatus objStatus; string strPassword; PortalSecurity objPortalSecurity = new PortalSecurity(); strPassword = objPortalSecurity.Decrypt( EncryptionKey, objUser.Membership.Password ); if( objUser.IsSuperUser ) { objUser.Membership.Approved = true; } MembershipUser objMembershipUser; objMembershipUser = System.Web.Security.Membership.CreateUser( objUser.Username, strPassword, objUser.Email, null, null, objUser.Membership.Approved, out objStatus ); if( objStatus != MembershipCreateStatus.Success ) { Exceptions.LogException( new Exception( objStatus.ToString() ) ); } else { try { ProfileBase objProfile; objProfile = ProfileBase.Create( objUser.Username, true ); objProfile["FirstName"] = objUser.Profile.FirstName; objProfile["LastName"] = objUser.Profile.LastName; objProfile["Unit"] = objUser.Profile.Unit; objProfile["Street"] = objUser.Profile.Street; objProfile["City"] = objUser.Profile.City; objProfile["Region"] = objUser.Profile.Region; objProfile["PostalCode"] = objUser.Profile.PostalCode; objProfile["Country"] = objUser.Profile.Country; objProfile["Telephone"] = objUser.Profile.Telephone; objProfile.Save(); } catch( Exception exc ) { Exceptions.LogException( exc ); } RoleController objDNNRoles = new RoleController(); string[] arrUserRoles = objDNNRoles.GetRolesByUser( objUser.UserID, PortalID ); if( arrUserRoles != null ) { try { System.Web.Security.Roles.AddUserToRoles( objUser.Username, arrUserRoles ); } catch( Exception exc ) { Exceptions.LogException( exc ); } } } } } finally { } if( SuperUsers ) { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Finish Transferring SuperUsers to MemberRole:<br>" ); } else { HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Finish Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>" ); } }
public void OnAuthenticateRequest( object s, EventArgs e ) { HttpContext Context = ( (HttpApplication)s ).Context; HttpRequest Request = Context.Request; HttpResponse Response = Context.Response; //First check if we are upgrading/installing if( Request.Url.LocalPath.EndsWith( "Install.aspx" ) ) { return; } //exit if a request for a .net mapping that isn't a content page is made i.e. axd if (Request.Url.LocalPath.ToLower().EndsWith(".aspx") == false && Request.Url.LocalPath.ToLower().EndsWith(".asmx") == false) { return; } // Obtain PortalSettings from Current Context PortalSettings portalSettings = PortalController.GetCurrentPortalSettings(); if( Request.IsAuthenticated && portalSettings != null ) { RoleController objRoleController = new RoleController(); UserInfo objUser = UserController.GetCachedUser( portalSettings.PortalId, Context.User.Identity.Name ); if( !Convert.ToBoolean( Request.Cookies["portalaliasid"] == null ) ) { FormsAuthenticationTicket PortalCookie = FormsAuthentication.Decrypt( Context.Request.Cookies["portalaliasid"].Value ); // check if user has switched portals if( portalSettings.PortalAlias.PortalAliasID != int.Parse( PortalCookie.UserData ) ) { // expire cookies if portal has changed Response.Cookies["portalaliasid"].Value = null; Response.Cookies["portalaliasid"].Path = "/"; Response.Cookies["portalaliasid"].Expires = DateTime.Now.AddYears( - 30 ); Response.Cookies["portalroles"].Value = null; Response.Cookies["portalroles"].Path = "/"; Response.Cookies["portalroles"].Expires = DateTime.Now.AddYears( - 30 ); } } // authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set ) if( objUser == null || objUser.Membership.LockedOut || objUser.Membership.Approved == false ) { PortalSecurity objPortalSecurity = new PortalSecurity(); objPortalSecurity.SignOut(); // Redirect browser back to home page Response.Redirect( Request.RawUrl, true ); return; } else // valid Auth cookie { // create cookies if they do not exist yet for this session. if( Request.Cookies["portalroles"] == null ) { // keep cookies in sync DateTime CurrentDateTime = DateTime.Now; // create a cookie authentication ticket ( version, user name, issue time, expires every hour, don't persist cookie, roles ) FormsAuthenticationTicket PortalTicket = new FormsAuthenticationTicket( 1, objUser.Username, CurrentDateTime, CurrentDateTime.AddHours( 1 ), false, portalSettings.PortalAlias.PortalAliasID.ToString() ); // encrypt the ticket string strPortalAliasID = FormsAuthentication.Encrypt( PortalTicket ); // send portal cookie to client Response.Cookies["portalaliasid"].Value = strPortalAliasID; Response.Cookies["portalaliasid"].Path = "/"; Response.Cookies["portalaliasid"].Expires = CurrentDateTime.AddMinutes( 1 ); // get roles from UserRoles table string[] arrPortalRoles = objRoleController.GetRolesByUser( objUser.UserID, portalSettings.PortalId ); // create a string to persist the roles string strPortalRoles = String.Join(";", arrPortalRoles); // create a cookie authentication ticket ( version, user name, issue time, expires every hour, don't persist cookie, roles ) FormsAuthenticationTicket rolesTicket = new FormsAuthenticationTicket( 1, objUser.Username, CurrentDateTime, CurrentDateTime.AddHours( 1 ), false, strPortalRoles ); // encrypt the ticket string strRoles = FormsAuthentication.Encrypt( rolesTicket ); // send roles cookie to client Response.Cookies["portalroles"].Value = strRoles; Response.Cookies["portalroles"].Path = "/"; Response.Cookies["portalroles"].Expires = CurrentDateTime.AddMinutes( 1 ); } if( Request.Cookies["portalroles"] != null ) { // get roles from roles cookie if( !String.IsNullOrEmpty( Request.Cookies["portalroles"].Value )) { FormsAuthenticationTicket RoleTicket = FormsAuthentication.Decrypt( Context.Request.Cookies["portalroles"].Value ); // convert the string representation of the role data into a string array // and store it in the Roles Property of the User objUser.Roles = RoleTicket.UserData.Split( ';' ); } Context.Items.Add( "UserInfo", objUser ); Localization.SetLanguage( objUser.Profile.PreferredLocale ); } } } if( HttpContext.Current.Items["UserInfo"] == null ) { Context.Items.Add( "UserInfo", new UserInfo() ); } }
private static string GetUserRoles() { if (HttpContext.Current != null && HttpContext.Current.User.Identity.IsAuthenticated) { var sb = new StringBuilder(128); UserInfo ui = UserController.GetCurrentUserInfo(); var rc = new RoleController(); // Not sure why DNN methods that return roles don't consistently return RoleInfo objects. hk if (ui.IsSuperUser) { foreach (RoleInfo role in rc.GetRoles()) { sb.Append("'"); sb.Append(role.RoleName); sb.Append("',"); } } else { string[] roles = rc.GetRolesByUser(ui.UserID, ui.PortalID); foreach (string s in roles) { sb.Append("'"); sb.Append(s); sb.Append("',"); } } // trim the last , if (sb.Length > 0) { sb.Length -= 1; } return sb.ToString(); } return "'Everyone'"; // is this always 'Everyone'? }
private static bool IsUserInRole(string roleName) { UserInfo ui = UserController.GetCurrentUserInfo(); var rc = new RoleController(); string[] roles = rc.GetRolesByUser(ui.UserID, ui.PortalID); foreach (string role in roles) { if (roleName == role) { return true; } } return false; }