public HttpResponseMessage ApproveGroup(NotificationDTO postData)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID);
                if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient");

                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseKey(notification.Context);
                if (_roleInfo == null)
                {
                    return  Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role");
                }
                if (!IsMod())
                {
                    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!");
                }
                var roleController = new RoleController();
                _roleInfo.Status = RoleStatus.Approved;
                roleController.UpdateRole(_roleInfo);
                var roleCreator = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID);
                //Update the original creator's role
                roleController.UpdateUserRole(PortalSettings.PortalId, roleCreator.UserID, _roleInfo.RoleID, RoleStatus.Approved, true, false);
                GroupUtilities.CreateJournalEntry(_roleInfo, roleCreator);

                var notifications = new Notifications();
                var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId);
                notifications.AddGroupNotification(Constants.GroupApprovedNotification, _tabId, _moduleId, _roleInfo, siteAdmin, new List<RoleInfo> { _roleInfo });
                NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId);

                return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }
        }
Exemplo n.º 2
0
        public ActionResult ApproveGroup(int notificationId)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(notificationId, UserInfo.UserID);
                if (recipient == null) return Json(new { Result = "error" });

                var notification = NotificationsController.Instance.GetNotification(notificationId);
                ParseKey(notification.Context);
                if (roleInfo == null)
                {
                    return Json(new { Result = "error" });
                }
                if (!IsMod())
                {
                    return Json(new { Result = "access denied" });
                }
                var roleController = new RoleController();
                roleInfo.Status = RoleStatus.Approved;
                roleController.UpdateRole(roleInfo);
                var roleCreator = UserController.GetUserById(PortalSettings.PortalId, roleInfo.CreatedByUserID);
                //Update the original creator's role
                roleController.UpdateUserRole(PortalSettings.PortalId, roleCreator.UserID, roleInfo.RoleID, RoleStatus.Approved, true, false);
                GroupUtilities.CreateJournalEntry(roleInfo, roleCreator);

                var notifications = new Notifications();
                var siteAdmin = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId);
                notifications.AddGroupNotification(Constants.GroupApprovedNotification, TabId, ModuleId, roleInfo, siteAdmin, new List<RoleInfo> { roleInfo });
                NotificationsController.Instance.DeleteAllNotificationRecipients(notificationId);

                return Json(new { Result = "success" });
            }
            catch (Exception exc)
            {
                DnnLog.Error(exc);
                return Json(new { Result = "error" });
            }
        }
        public HttpResponseMessage ApproveMember(NotificationDTO postData)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, UserInfo.UserID);
                if (recipient == null) return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient");

                var notification = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseKey(notification.Context);
                if (_memberId <= 0)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member");
                }

                if (_roleInfo == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role");
                }

                var member = UserController.GetUserById(PortalSettings.PortalId, _memberId);

                if (member != null)
                {
                    var roleController = new RoleController();
                    var memberRoleInfo = roleController.GetUserRole(PortalSettings.PortalId, _memberId, _roleInfo.RoleID);
                    memberRoleInfo.Status = RoleStatus.Approved;
                    roleController.UpdateUserRole(PortalSettings.PortalId, _memberId, _roleInfo.RoleID, RoleStatus.Approved, false, false);
                    
                    var notifications = new Notifications();
                    var groupOwner = UserController.GetUserById(PortalSettings.PortalId, _roleInfo.CreatedByUserID);
                    notifications.AddMemberNotification(Constants.MemberApprovedNotification, _tabId, _moduleId, _roleInfo, groupOwner, member);
                    NotificationsController.Instance.DeleteAllNotificationRecipients(postData.NotificationId);

                    return Request.CreateResponse(HttpStatusCode.OK, new {Result = "success"});
                }
            } catch (Exception exc)
            {
                Logger.Error(exc);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
            }

            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error");
        }
        /// <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>
        /// cmdRSVP_Click runs when the Subscribe to RSVP Code Roles Button is clicked
        /// </summary>
        /// <history>
        /// 	[cnurse]	01/19/2006  created
        /// </history>
        protected void cmdRSVP_Click( object sender, EventArgs e )
        {
            //Get the RSVP code
            string code = txtRSVPCode.Text;

            if( !String.IsNullOrEmpty(code) )
            {
                //Get the roles from the Database
                RoleController objRoles = new RoleController();
                ArrayList arrRoles = objRoles.GetPortalRoles( PortalSettings.PortalId );

                //Parse the roles
                foreach( RoleInfo objRole in arrRoles )
                {
                    if( objRole.RSVPCode == code )
                    {
                        //Subscribe User to Role
                        objRoles.UpdateUserRole( PortalId, UserInfo.UserID, objRole.RoleID );
                    }
                }
            }

            //Reset RSVP Code field
            txtRSVPCode.Text = "";

            DataBind();
        }
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <history>
        /// 	[cnurse]	03/13/2006
        /// </history>
        protected void Page_Load( Object sender, EventArgs e )
        {
            try
            {
                if( ( Request.QueryString["Services"] != null ) )
                {
                    Services = int.Parse( Request.QueryString["Services"] );
                }

                // free subscriptions
                if( ( Request.QueryString["RoleID"] != null ) )
                {
                    RoleID = int.Parse( Request.QueryString["RoleID"] );

                    RoleController objRoles = new RoleController();

                    RoleInfo objRole = objRoles.GetRole( RoleID, PortalSettings.PortalId );

                    if( objRole.IsPublic && objRole.ServiceFee == 0.0 )
                    {
                        objRoles.UpdateUserRole( PortalId, UserInfo.UserID, RoleID, Convert.ToBoolean( ( Request.QueryString["cancel"] != null ) ? true : false ) );

                        if( PortalSettings.UserTabId != - 1 )
                        {
                            // user defined tab
                            Response.Redirect( Globals.NavigateURL( PortalSettings.UserTabId ), true );
                        }
                        else
                        {
                            // admin tab
                            Response.Redirect( Globals.NavigateURL( TabId, "profile", "UserID=" + UserInfo.UserID ), true );
                        }
                    }
                    else
                    {
                        // EVENTLOGGER
                    }
                }

                // If this is the first visit to the page, bind the role data to the datalist
                if( Page.IsPostBack == false )
                {
                    //Localize the Headers
                    Localization.LocalizeDataGrid(ref grdServices, this.LocalResourceFile);
                }
            }
            catch( Exception exc ) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }
Exemplo n.º 7
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().Contains("upgradewizard.aspx")
                || request.Url.LocalPath.ToLower().Contains("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();

            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 roleController = new RoleController();
                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 (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 (!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"));
					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 = request.UserHostAddress;
                    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 TestableRoleController.Instance.GetRoles(portalSettings.PortalId, r => (r.SecurityMode != SecurityMode.SocialGroup || r.IsPublic) && 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());
            }
        }
Exemplo n.º 8
0
        private void UseTrial(int roleID)
        {
            var objRoles = new RoleController();
            RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);

            if (objRole.IsPublic && objRole.TrialFee == 0.0)
            {
                objRoles.UpdateUserRole(PortalId, UserInfo.UserID, roleID, false);

                //Raise SubscriptionUpdated Event
                OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName));
            }
            else
            {
                Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID, true);
            }
        }
Exemplo n.º 9
0
        private void Subscribe(int roleID, bool cancel)
        {
            var objRoles = new RoleController();
            RoleInfo objRole = objRoles.GetRole(roleID, PortalSettings.PortalId);

            if (objRole.IsPublic && objRole.ServiceFee == 0.0)
            {
                objRoles.UpdateUserRole(PortalId, UserInfo.UserID, roleID, cancel);

                //Raise SubscriptionUpdated Event
                OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(cancel, objRole.RoleName));
            }
            else
            {
                if (!cancel)
                {
                    Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID, true);
                }
                else
                {
                    Response.Redirect("~/admin/Sales/PayPalSubscription.aspx?tabid=" + TabId + "&RoleID=" + roleID + "&cancel=1", true);
                }
            }
        }
Exemplo n.º 10
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdRSVP_Click runs when the Subscribe to RSVP Code Roles Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	01/19/2006  created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void cmdRSVP_Click(object sender, EventArgs e)
        {
            //Get the RSVP code
            string code = txtRSVPCode.Text;
            bool rsvpCodeExists = false;
            if (!String.IsNullOrEmpty(code))
            {
                //Get the roles from the Database
                var objRoles = new RoleController();
                ArrayList arrRoles = objRoles.GetPortalRoles(PortalSettings.PortalId);

                //Parse the roles
                foreach (RoleInfo objRole in arrRoles)
                {
                    if (objRole.RSVPCode == code)
                    {
                        objRoles.UpdateUserRole(PortalId, UserInfo.UserID, objRole.RoleID);
                        rsvpCodeExists = true;

                        //Raise SubscriptionUpdated Event
                        OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName));
                    }
                }
                if (rsvpCodeExists)
                {
                    lblRSVP.Text = Localization.GetString("RSVPSuccess", LocalResourceFile);
                    //Reset RSVP Code field
                    txtRSVPCode.Text = "";
                }
                else
                {
                    lblRSVP.Text = Localization.GetString("RSVPFailure", LocalResourceFile);
                }
            }
            DataBind();
        }
Exemplo n.º 11
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                bool blnValid = true;
//                string strTransactionID;
                int intRoleID = 0;
                int intPortalID = PortalSettings.PortalId;
                int intUserID = 0;
//                string strDescription;
                double dblAmount = 0;
//                string strEmail;
                bool blnCancel = false;
                string strPayPalID = Null.NullString;
                var objRoles = new RoleController();
                var objPortalController = new PortalController();
                string strPost = "cmd=_notify-validate";
                foreach (string strName in Request.Form)
                {
                    string strValue = Request.Form[strName];
                    switch (strName)
                    {
                        case "txn_type": //get the transaction type
                            string strTransactionType = strValue;
                            switch (strTransactionType)
                            {
                                case "subscr_signup":
                                case "subscr_payment":
                                case "web_accept":
                                    break;
                                case "subscr_cancel":
                                    blnCancel = true;
                                    break;
                                default:
                                    blnValid = false;
                                    break;
                            }
                            break;
                        case "payment_status": //verify the status
                            if (strValue != "Completed")
                            {
                                blnValid = false;
                            }
                            break;
                        case "txn_id": //verify the transaction id for duplicates
//                            strTransactionID = strValue;
                            break;
                        case "receiver_email": //verify the PayPalId
                            strPayPalID = strValue;
                            break;
                        case "mc_gross": // verify the price
                            dblAmount = double.Parse(strValue);
                            break;
                        case "item_number": //get the RoleID
                            intRoleID = Int32.Parse(strValue);
                            //RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID);
                            break;
                        case "item_name": //get the product description
//                            strDescription = strValue;
                            break;
                        case "custom": //get the UserID
                            intUserID = Int32.Parse(strValue);
                            break;
                        case "email": //get the email
//                            strEmail = strValue;
                            break;
                    }
                    
					//reconstruct post for postback validation
					strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue));
                }
                
				//postback to verify the source
				if (blnValid)
                {
                    Dictionary<string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
                    string strPayPalURL;

                    // Sandbox mode
                    if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"].Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
                    else
                    {
                        strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }
                    var objRequest = Globals.GetExternalRequest(strPayPalURL);
                    objRequest.Method = "POST";
                    objRequest.ContentLength = strPost.Length;
                    objRequest.ContentType = "application/x-www-form-urlencoded";
                    using (var objStream = new StreamWriter(objRequest.GetRequestStream()))
                    {
                        objStream.Write(strPost);
                    }

                    string strResponse;
                    using (var objResponse = (HttpWebResponse) objRequest.GetResponse())
                    {
                        using (var sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }
                    }
                    switch (strResponse)
                    {
                        case "VERIFIED":
                            break;
                        default:
                            //possible fraud
							blnValid = false;
                            break;
                    }
                }
                if (blnValid)
                {
                    int intAdministratorRoleId = 0;
                    string strProcessorID = Null.NullString;
                    PortalInfo objPortalInfo = objPortalController.GetPortal(intPortalID);
                    if (objPortalInfo != null)
                    {
                        intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
                        strProcessorID = objPortalInfo.ProcessorUserId.ToLower();
                    }

                    if (intRoleID == intAdministratorRoleId)
                    {
						//admin portal renewal
                        strProcessorID = Host.ProcessorUserId.ToLower();
                        float portalPrice = objPortalInfo.HostFee;
                        if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objPortalController.UpdatePortalExpiry(intPortalID);
                        }
                        else
                        {
                            var objEventLog = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID = intUserID;
                            objEventLogInfo.LogTypeKey = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                    else
                    {
						//user subscription
                        RoleInfo objRoleInfo = TestableRoleController.Instance.GetRole(intPortalID, r => r.RoleID == intRoleID);
                        float rolePrice = objRoleInfo.ServiceFee;
                        float trialPrice = objRoleInfo.TrialFee;
                        if ((rolePrice.ToString() == dblAmount.ToString() || trialPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objRoles.UpdateUserRole(intPortalID, intUserID, intRoleID, blnCancel);
                        }
                        else
                        {
                            var objEventLog = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID = intUserID;
                            objEventLogInfo.LogTypeKey = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                }
            }
            catch (Exception exc) //Page failed to load
            {
                Exceptions.ProcessPageLoadException(exc);
            }
        }
Exemplo n.º 12
0
        protected void Page_Load( Object sender, EventArgs e )
        {
            try
            {
                string strName;
                StreamWriter objStream;
                bool blnValid = true;
                string strTransactionID;
                string strTransactionType;
                int intRoleID = 0;
                int intPortalID = PortalSettings.PortalId;
                int intUserID = 0;
                string strDescription;
                double dblAmount = 0;
                string strEmail;
                string strBody;
                bool blnCancel = false;
                string strPayPalID = String.Empty;

                RoleController objRoles = new RoleController();
                PortalController objPortalController = new PortalController();

                string strPost = "cmd=_notify-validate";
                foreach( string tempLoopVar_strName in Request.Form )
                {
                    strName = tempLoopVar_strName;
                    string strValue = Request.Form[strName];
                    switch( strName )
                    {
                        case "txn_type": // get the transaction type

                            strTransactionType = strValue;
                            switch( strTransactionType )
                            {
                                case "subscr_signup":
                                    break;

                                case "subscr_payment":
                                    break;

                                case "web_accept":

                                    break;
                                case "subscr_cancel":

                                    blnCancel = true;
                                    break;
                                default:

                                    blnValid = false;
                                    break;
                            }
                            break;
                        case "payment_status": // verify the status

                            if( strValue != "Completed" )
                            {
                                blnValid = false;
                            }
                            break;
                        case "txn_id": // verify the transaction id for duplicates

                            strTransactionID = strValue;
                            break;
                        case "receiver_email": // verify the PayPalId

                            strPayPalID = strValue;
                            break;
                        case "mc_gross": // verify the price

                            dblAmount = double.Parse( strValue );
                            break;
                        case "item_number": // get the RoleID

                            intRoleID = int.Parse( strValue );
                            RoleInfo objRole = objRoles.GetRole( intRoleID, intPortalID );
                            break;
                        case "item_name": // get the product description

                            strDescription = strValue;
                            break;
                        case "custom": // get the UserID

                            intUserID = int.Parse( strValue );
                            break;
                        case "email": // get the email

                            strEmail = strValue;
                            break;
                    }
                    // reconstruct post for postback validation
                    strPost += string.Format( "&{0}={1}", strName, Globals.HTTPPOSTEncode( strValue ) );
                }
                // postback to verify the source
                if( blnValid )
                {
                    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create( "https://www.paypal.com/cgi-bin/webscr" );
                    objRequest.Method = "POST";
                    objRequest.ContentLength = strPost.Length;
                    objRequest.ContentType = "application/x-www-form-urlencoded";

                    objStream = new StreamWriter( objRequest.GetRequestStream() );
                    objStream.Write( strPost );
                    objStream.Close();

                    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
                    StreamReader sr;
                    sr = new StreamReader( objResponse.GetResponseStream() );
                    string strResponse = sr.ReadToEnd();
                    sr.Close();

                    switch( strResponse )
                    {
                        case "VERIFIED":

                            break;
                        default:

                            // possible fraud
                            blnValid = false;
                            break;
                    }
                }

                if( blnValid )
                {
                    int intAdministratorRoleId = 0;
                    string strProcessorID = String.Empty;
                    PortalInfo objPortalInfo = objPortalController.GetPortal( intPortalID );
                    if( objPortalInfo != null )
                    {
                        intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
                        strProcessorID = objPortalInfo.ProcessorUserId.ToLower();
                    }
                    if( intRoleID == intAdministratorRoleId )
                    {
                        // admin portal renewal
                        strProcessorID = Convert.ToString( PortalSettings.HostSettings["ProcessorUserId"] ).ToLower();
                        float portalPrice = objPortalInfo.HostFee;
                        if( ( portalPrice.ToString() == dblAmount.ToString() ) && ( HttpUtility.UrlDecode( strPayPalID.ToLower() ) == strProcessorID ) )
                        {
                            objPortalController.UpdatePortalExpiry( intPortalID );
                        }
                        else
                        {
                            try
                            {
                                EventLogController objEventLog = new EventLogController();
                                LogInfo objEventLogInfo = new LogInfo();
                                objEventLogInfo.LogPortalID = intPortalID;
                                objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                                objEventLogInfo.LogUserID = intUserID;
                                objEventLogInfo.LogTypeKey = "POTENTIAL PAYPAL PAYMENT FRAUD";
                                objEventLog.AddLog( objEventLogInfo );
                            }
                            catch( Exception )
                            {
                            }
                        }
                    }
                    else
                    {
                        // user subscription
                        RoleInfo objRoleInfo = objRoles.GetRole( intRoleID, intPortalID );
                        double rolePrice = objRoleInfo.ServiceFee;
                        if( ( rolePrice.ToString() == dblAmount.ToString() ) && ( HttpUtility.UrlDecode( strPayPalID.ToLower() ) == strProcessorID ) )
                        {
                            objRoles.UpdateUserRole( intPortalID, intUserID, intRoleID, blnCancel );
                        }
                        else
                        {
                            try
                            {
                                //let's use the new logging provider.
                            }
                            catch( Exception )
                            {
                            }
                        }
                    }
                }
            }
            catch( Exception exc ) //Page failed to load
            {
                Exceptions.ProcessPageLoadException( exc );
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <history>
        /// 	[cnurse]	9/13/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        protected void Page_Load( Object sender, EventArgs e )
        {
            try
            {
                // Verify if portal has a customized registration page
                if (!Null.IsNull(PortalSettings.UserTabId) && Globals.IsAdminControl())
                {
                    // user page exists and trying to access this control directly with url param -> not allowed
                    Response.Redirect( Globals.NavigateURL( PortalSettings.UserTabId ) );
                }

                // Verify that the current user has access to this page
                if( PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && Request.IsAuthenticated == false )
                {
                    Response.Redirect( Globals.NavigateURL( "Access Denied" ), true );
                }

                if( ( Request.QueryString["Services"] != null ) )
                {
                    Services = int.Parse( Request.QueryString["Services"] );
                }

                // free subscriptions
                if( ( Request.QueryString["RoleID"] != null ) )
                {
                    RoleID = int.Parse( Request.QueryString["RoleID"] );

                    RoleController objRoles = new RoleController();

                    RoleInfo objRole = objRoles.GetRole( RoleID, PortalSettings.PortalId );

                    if( objRole.IsPublic && objRole.ServiceFee == 0.0 )
                    {
                        objRoles.UpdateUserRole( PortalId, UserInfo.UserID, RoleID, Convert.ToBoolean( ( Request.QueryString["cancel"] != null ) ? true : false ) );

                        if( PortalSettings.UserTabId != - 1 )
                        {
                            // user defined tab
                            Response.Redirect( Globals.NavigateURL( PortalSettings.UserTabId ), true );
                        }
                        else
                        {
                            // admin tab
                            Response.Redirect( Globals.NavigateURL( "Register" ), true );
                        }
                    }
                    else
                    {
                        // EVENTLOGGER
                    }
                }

                // If this is the first visit to the page, bind the role data to the datalist
                if( Page.IsPostBack == false )
                {
                    //Localize the Headers
                    Localization.LocalizeDataGrid(ref grdServices, this.LocalResourceFile);

                    ClientAPI.AddButtonConfirm( cmdUnregister, Localization.GetString( "CancelConfirm", this.LocalResourceFile ) );

                    BindData();

                    try
                    {
                        Globals.SetFormFocus(userControl);
                    }
                    catch
                    {
                        //control not there or error setting focus
                    }

                    // Store URL Referrer to return to portal
                    if( Request.UrlReferrer != null )
                    {
                        ViewState["UrlReferrer"] = Convert.ToString( Request.UrlReferrer );
                    }
                    else
                    {
                        ViewState["UrlReferrer"] = "";
                    }
                }

                lblRegistration.Text = Localization.GetSystemMessage( PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS" );
            }
            catch( Exception exc ) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }
Exemplo n.º 14
0
        public ActionResult ApproveMember(int notificationId)
        {
            try
            {
                var recipient = InternalMessagingController.Instance.GetMessageRecipient(notificationId, UserInfo.UserID);
                if (recipient == null) return Json(new { Result = "error" });

                var notification = NotificationsController.Instance.GetNotification(notificationId);
                ParseKey(notification.Context);
                if (MemberId <= 0) return Json(new { Result = "error" });

                if (roleInfo == null) return Json(new { Result = "error" });

                var member = UserController.GetUserById(PortalSettings.PortalId, MemberId);

                

                if (member != null)
                {
                    var roleController = new RoleController();
                    var memberRoleInfo = roleController.GetUserRole(PortalSettings.PortalId, MemberId, roleInfo.RoleID);
                    memberRoleInfo.Status = RoleStatus.Approved;
                    roleController.UpdateUserRole(PortalSettings.PortalId, MemberId, roleInfo.RoleID, RoleStatus.Approved, false, false);
                    
                    var notifications = new Notifications();
                    var groupOwner = UserController.GetUserById(PortalSettings.PortalId, roleInfo.CreatedByUserID);
                    notifications.AddMemberNotification(Constants.MemberApprovedNotification, TabId, ModuleId, roleInfo, groupOwner, member);
                    NotificationsController.Instance.DeleteAllNotificationRecipients(notificationId);

                    return Json(new { Result = "success" });
                }
            } catch (Exception exc)
            {
                DnnLog.Error(exc);
            }

            return Json(new { Result = "error" });
        }