Exemplo n.º 1
0
        public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, bool cancel)
        {
            UserInfo     user               = UserController.GetUserById(portalId, userId);
            UserRoleInfo userRole           = GetUserRole(portalId, userId, roleId);
            var          eventLogController = new EventLogController();

            if (cancel)
            {
                if (userRole != null && userRole.ServiceFee > 0.0 && userRole.IsTrialUsed)
                {
                    //Expire Role so we retain trial used data
                    userRole.ExpiryDate = DateTime.Now.AddDays(-1);
                    userRole.Status     = status;
                    userRole.IsOwner    = isOwner;
                    provider.UpdateUserRole(userRole);
                    eventLogController.AddLog(userRole, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED);
                }
                else
                {
                    //Delete Role
                    DeleteUserRoleInternal(portalId, userId, roleId);
                    eventLogController.AddLog("UserId",
                                              userId.ToString(CultureInfo.InvariantCulture),
                                              PortalController.GetCurrentPortalSettings(),
                                              UserController.GetCurrentUserInfo().UserID,
                                              EventLogController.EventLogType.USER_ROLE_DELETED);
                }
            }
            else
            {
                int      UserRoleId    = -1;
                DateTime ExpiryDate    = DateTime.Now;
                DateTime EffectiveDate = Null.NullDate;
                bool     IsTrialUsed   = false;
                int      Period        = 0;
                string   Frequency     = "";
                if (userRole != null)
                {
                    UserRoleId    = userRole.UserRoleID;
                    EffectiveDate = userRole.EffectiveDate;
                    ExpiryDate    = userRole.ExpiryDate;
                    IsTrialUsed   = userRole.IsTrialUsed;
                }
                RoleInfo role = TestableRoleController.Instance.GetRole(portalId, r => r.RoleID == roleId);
                if (role != null)
                {
                    if (IsTrialUsed == false && role.TrialFrequency != "N")
                    {
                        Period    = role.TrialPeriod;
                        Frequency = role.TrialFrequency;
                    }
                    else
                    {
                        Period    = role.BillingPeriod;
                        Frequency = role.BillingFrequency;
                    }
                }
                if (EffectiveDate < DateTime.Now)
                {
                    EffectiveDate = Null.NullDate;
                }
                if (ExpiryDate < DateTime.Now)
                {
                    ExpiryDate = DateTime.Now;
                }
                if (Period == Null.NullInteger)
                {
                    ExpiryDate = Null.NullDate;
                }
                else
                {
                    switch (Frequency)
                    {
                    case "N":
                        ExpiryDate = Null.NullDate;
                        break;

                    case "O":
                        ExpiryDate = new DateTime(9999, 12, 31);
                        break;

                    case "D":
                        ExpiryDate = ExpiryDate.AddDays(Period);
                        break;

                    case "W":
                        ExpiryDate = ExpiryDate.AddDays(Period * 7);
                        break;

                    case "M":
                        ExpiryDate = ExpiryDate.AddMonths(Period);
                        break;

                    case "Y":
                        ExpiryDate = ExpiryDate.AddYears(Period);
                        break;
                    }
                }
                if (UserRoleId != -1 && userRole != null)
                {
                    userRole.ExpiryDate = ExpiryDate;
                    userRole.Status     = status;
                    userRole.IsOwner    = isOwner;
                    provider.UpdateUserRole(userRole);
                    eventLogController.AddLog(userRole, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.USER_ROLE_UPDATED);
                }
                else
                {
                    AddUserRole(portalId, userId, roleId, status, isOwner, EffectiveDate, ExpiryDate);
                }
            }

            //Remove the UserInfo from the Cache, as it has been modified
            DataCache.ClearUserCache(portalId, user.Username);
            DataCache.RemoveCache(String.Format(DataCache.RolesCacheKey, portalId));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Authenticates the request.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="allowUnknownExtensions">if set to <c>true</c> to allow unknown extensinons.</param>
        public static void AuthenticateRequest(HttpContextBase context, bool allowUnknownExtensions)
        {
            HttpRequestBase  request  = context.Request;
            HttpResponseBase response = context.Response;

            //First check if we are upgrading/installing
            if (!Initialize.ProcessHttpModule(context.ApplicationInstance.Request, allowUnknownExtensions, false))
            {
                return;
            }

            //Obtain PortalSettings from Current Context
            PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings();

            bool isActiveDirectoryAuthHeaderPresent = false;
            var  auth = request.Headers.Get("Authorization");

            if (!string.IsNullOrEmpty(auth))
            {
                if (auth.StartsWith("Negotiate"))
                {
                    isActiveDirectoryAuthHeaderPresent = true;
                }
            }

            if (request.IsAuthenticated && !isActiveDirectoryAuthHeaderPresent && portalSettings != null)
            {
                var user = UserController.GetCachedUser(portalSettings.PortalId, context.User.Identity.Name);
                //if current login is from windows authentication, the ignore the process
                if (user == null && context.User is WindowsPrincipal)
                {
                    return;
                }

                //authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set )
                if (RequireLogout(context, user))
                {
                    var portalSecurity = PortalSecurity.Instance;
                    portalSecurity.SignOut();

                    //Remove user from cache
                    if (user != null)
                    {
                        DataCache.ClearUserCache(portalSettings.PortalId, context.User.Identity.Name);
                    }

                    //Redirect browser back to home page
                    response.Redirect(request.RawUrl, true);
                    return;
                }

                if (!user.IsSuperUser && user.IsInRole("Unverified Users") && !HttpContext.Current.Items.Contains(DotNetNuke.UI.Skins.Skin.OnInitMessage))
                {
                    HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessage, Localization.GetString("UnverifiedUser", Localization.SharedResourceFile, CurrentCulture));
                }

                if (!user.IsSuperUser && HttpContext.Current.Request.QueryString.AllKeys.Contains("VerificationSuccess") && !HttpContext.Current.Items.Contains(DotNetNuke.UI.Skins.Skin.OnInitMessage))
                {
                    HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessage, Localization.GetString("VerificationSuccess", Localization.SharedResourceFile, CurrentCulture));
                    HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessageType, ModuleMessage.ModuleMessageType.GreenSuccess);
                }

                //if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity
                if (DateTime.Compare(user.Membership.LastActivityDate.AddMinutes(Host.UsersOnlineTimeWindow), DateTime.Now) < 0)
                {
                    //update LastActivityDate and IP Address for user
                    user.Membership.LastActivityDate = DateTime.Now;
                    user.LastIPAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(request);
                    UserController.UpdateUser(portalSettings.PortalId, user, false, false);
                }

                //check for RSVP code
                if (request.QueryString["rsvp"] != null && !string.IsNullOrEmpty(request.QueryString["rsvp"]))
                {
                    foreach (var role in RoleController.Instance.GetRoles(portalSettings.PortalId, r => (r.SecurityMode != SecurityMode.SocialGroup || r.IsPublic) && r.Status == RoleStatus.Approved))
                    {
                        if (role.RSVPCode == request.QueryString["rsvp"])
                        {
                            RoleController.Instance.UpdateUserRole(portalSettings.PortalId, user.UserID, role.RoleID, RoleStatus.Approved, false, false);
                        }
                    }
                }

                //save userinfo object in context
                if (context.Items["UserInfo"] != null)
                {
                    context.Items["UserInfo"] = user;
                }
                else
                {
                    context.Items.Add("UserInfo", user);
                }

                //Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded
                if (request.RawUrl != null && !ServicesModule.ServiceApi.IsMatch(request.RawUrl))
                {
                    Localization.SetLanguage(user.Profile.PreferredLocale);
                }
            }

            if (context.Items["UserInfo"] == null)
            {
                context.Items.Add("UserInfo", new UserInfo());
            }
        }
Exemplo n.º 3
0
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (this.userForm.IsValid && (this.User != null))
            {
                if (this.User.UserID == this.PortalSettings.AdministratorId)
                {
                    // Clear the Portal Cache
                    DataCache.ClearPortalCache(this.UserPortalID, true);
                }
                else
                {
                    DataCache.ClearUserCache(this.PortalId, this.User.Username);
                }

                try
                {
                    // Update DisplayName to conform to Format
                    this.UpdateDisplayName();

                    // DNN-5874 Check if unique display name is required
                    if (this.PortalSettings.Registration.RequireUniqueDisplayName)
                    {
                        var usersWithSameDisplayName = (List <UserInfo>)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName);
                        if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID))
                        {
                            throw new Exception("Display Name must be unique");
                        }
                    }

                    var prevUserEmail = UserController.Instance.GetUserById(this.PortalId, this.UserId)?.Email;

                    if (!string.IsNullOrWhiteSpace(prevUserEmail) && !prevUserEmail.Equals(this.User.Email, StringComparison.OrdinalIgnoreCase))
                    {
                        // on email address change need to invalidate existing 'reset password' link
                        this.User.PasswordResetExpiration = Null.NullDate;
                    }

                    UserController.UpdateUser(this.UserPortalID, this.User);

                    // make sure username matches possibly changed email address
                    if (this.PortalSettings.Registration.UseEmailAsUserName)
                    {
                        if (this.User.Username.ToLower() != this.User.Email.ToLower())
                        {
                            UserController.ChangeUsername(this.User.UserID, this.User.Email);

                            // after username changed, should redirect to login page to let user authenticate again.
                            var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(this.Request.RawUrl), false);
                            var spliter  = loginUrl.Contains("?") ? "&" : "?";
                            loginUrl = $"{loginUrl}{spliter}username={this.User.Email}&usernameChanged=true";
                            this.Response.Redirect(loginUrl, true);
                        }
                    }

                    this.Response.Redirect(this.Request.RawUrl);
                }
                catch (Exception exc)
                {
                    Logger.Error(exc);
                    if (exc.Message == "Display Name must be unique")
                    {
                        this.AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true);
                    }
                    else
                    {
                        this.AddModuleMessage("UserUpdatedError", ModuleMessage.ModuleMessageType.RedError, true);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public HttpResponseMessage RevertImpersonation()
        {
            var apiResponse          = new DTO.ApiResponse <bool>();
            CookieHeaderValue cookie = null;
            var impersonationToken   = string.Empty;

            try
            {
                var objPortalSecurity = new DotNetNuke.Security.PortalSecurity();

                var impersonationCookie = Common.GetUserImpersonationCookie().Split(':');

                var Id        = 0;
                var currentId = 0;

                int.TryParse(impersonationCookie.First(), out Id);
                int.TryParse(impersonationCookie.Last(), out currentId);

                if (currentId == 0 && UserInfo.UserID == -1)
                {
                    currentId = -1;
                }

                if (Id == 0 || UserInfo.UserID != currentId)
                {
                    objPortalSecurity.SignOut();
                }
                else
                {
                    var targetUserInfo = DotNetNuke.Entities.Users.UserController.GetUserById(PortalSettings.PortalId, Id);

                    if (targetUserInfo != null)
                    {
                        DataCache.ClearUserCache(PortalSettings.PortalId, PortalSettings.UserInfo.Username);

                        objPortalSecurity.SignOut();

                        DotNetNuke.Entities.Users.UserController.UserLogin(PortalSettings.PortalId, targetUserInfo, PortalSettings.PortalName, HttpContext.Current.Request.UserHostAddress, false);
                    }
                }

                apiResponse.Success = true;
            }
            catch (Exception err)
            {
                apiResponse.Success = false;
                apiResponse.Message = err.Message;

                Exceptions.LogException(err);
            }

            var actualResponse = Request.CreateResponse <DTO.ApiResponse <bool> >(HttpStatusCode.OK, apiResponse);


            var newcookie = new HttpCookie(Common.impersonationCookieKey, impersonationToken);

            newcookie.Expires = DateTime.Now.AddMinutes(-60);
            newcookie.Domain  = Request.RequestUri.Host;
            newcookie.Path    = "/";

            HttpContext.Current.Response.SetCookie(newcookie);

            return(actualResponse);
        }
Exemplo n.º 5
0
        public static void AuthenticateRequest(HttpContextBase context, bool allowUnknownExtensinons)
        {
            HttpRequestBase  request  = context.Request;
            HttpResponseBase response = context.Response;

            //First check if we are upgrading/installing
            if (request == null || request.Url == null ||
                request.Url.LocalPath.ToLower().EndsWith("install.aspx") ||
                request.Url.LocalPath.ToLower().EndsWith("upgradewizard.aspx") ||
                request.Url.LocalPath.ToLower().EndsWith("installwizard.aspx"))
            {
                return;
            }

            //exit if a request for a .net mapping that isn't a content page is made i.e. axd
            if (allowUnknownExtensinons == false &&
                request.Url.LocalPath.ToLower().EndsWith(".aspx") == false &&
                request.Url.LocalPath.ToLower().EndsWith(".asmx") == false &&
                request.Url.LocalPath.ToLower().EndsWith(".ashx") == false)
            {
                return;
            }

            //Obtain PortalSettings from Current Context
            PortalSettings portalSettings = PortalController.GetCurrentPortalSettings();

            if (request.IsAuthenticated && portalSettings != null)
            {
                var      roleController = new RoleController();
                UserInfo user           = UserController.GetCachedUser(portalSettings.PortalId, context.User.Identity.Name);

                //authenticate user and set last login ( this is necessary for users who have a permanent Auth cookie set )
                if (user == null || user.IsDeleted || user.Membership.LockedOut ||
                    (!user.Membership.Approved && !user.IsInRole("Unverified Users")) ||
                    user.Username.ToLower() != context.User.Identity.Name.ToLower())
                {
                    var portalSecurity = new PortalSecurity();
                    portalSecurity.SignOut();

                    //Remove user from cache
                    if (user != null)
                    {
                        DataCache.ClearUserCache(portalSettings.PortalId, context.User.Identity.Name);
                    }

                    //Redirect browser back to home page
                    response.Redirect(request.RawUrl, true);
                    return;
                }

                if (!user.IsSuperUser && user.IsInRole("Unverified Users") && !HttpContext.Current.Items.Contains(DotNetNuke.UI.Skins.Skin.OnInitMessage))
                {
                    HttpContext.Current.Items.Add(DotNetNuke.UI.Skins.Skin.OnInitMessage, Localization.GetString("UnverifiedUser"));
                }

                //if users LastActivityDate is outside of the UsersOnlineTimeWindow then record user activity
                if (DateTime.Compare(user.Membership.LastActivityDate.AddMinutes(Host.UsersOnlineTimeWindow), DateTime.Now) < 0)
                {
                    //update LastActivityDate and IP Address for user
                    user.Membership.LastActivityDate = DateTime.Now;
                    user.LastIPAddress = request.UserHostAddress;
                    UserController.UpdateUser(portalSettings.PortalId, user, false);
                }

                //check for RSVP code
                if (request.QueryString["rsvp"] != null && !string.IsNullOrEmpty(request.QueryString["rsvp"]))
                {
                    foreach (var role in TestableRoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved))
                    {
                        if (role.RSVPCode == request.QueryString["rsvp"])
                        {
                            roleController.UpdateUserRole(portalSettings.PortalId, user.UserID, role.RoleID);
                        }
                    }
                }

                //save userinfo object in context
                context.Items.Add("UserInfo", user);

                //Localization.SetLanguage also updates the user profile, so this needs to go after the profile is loaded
                Localization.SetLanguage(user.Profile.PreferredLocale);
            }

            if (context.Items["UserInfo"] == null)
            {
                context.Items.Add("UserInfo", new UserInfo());
            }
        }