예제 #1
0
        ///<summary>
        ///Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        ///</summary>
        ///
        ///<param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Params["guid"] == null
                || !GuidAuths.ContainsKey(context.Request.Params["guid"]))
            {
                // Invalid or missing guid
                return;
            }

            string username = GuidAuths[context.Request.Params["guid"]];
            UserSession userSession;
            try
            {
                userSession = new UserSession(username);
                PageBase.SetCurrentUserSession(userSession);
                MatchmakerHelper.CurrentUsername = userSession.Username;
                userSession.Authorize(context.Session.SessionID);
            }
            catch (Exception err)
            {
                Global.Logger.LogError(err);
                return;
            }

            PageBase.SetCurrentUserSession(userSession);

            if (context.Request.Params["target"] != null)
            {
                switch (context.Request.Params["target"])
                {
                    case "mail":
                        context.Response.Redirect(Config.Urls.Home + "/MailBox.aspx");
                        break;
                    case "msg":
                        context.Response.Redirect(Config.Urls.Home + "/ShowMessage.aspx?mid=" +
                                                  context.Request.Params["mid"]);
                        break;
                    default:
                        context.Response.Redirect(Config.Urls.Home);
                        break;
                }
            }
            else
            {
                context.Response.Redirect(Config.Urls.Home);
            }
        }
예제 #2
0
        protected void fbLogin_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text.Length == 0)
            {
                showError(Lang.Trans("Please specify username!"));
                return;
            }
            if (txtPassword.Text.Length == 0)
            {
                showError(Lang.Trans("Please specify password!"));
                return;
            }

            UserSession user;
            try
            {
                user = new UserSession(txtUsername.Text);
                ((PageBase)Page).CurrentUserSession = user;
                MatchmakerHelper.CurrentUsername = user.Username;
                user.StealthMode = cbStealthMode.Checked;
                user.Authorize(txtPassword.Text, Session.SessionID);
                if (Config.Misc.EnableFacebookIntegration && user.FacebookID.HasValue && user.FacebookID > 0)
                {
                    FacebookHelper.AddFriends(user, 60, HttpContext.Current, null);
                }
            }
            catch (NotFoundException err)
            {
                showError(err.Message);
                return;
            }
            catch (AccessDeniedException err)
            {
                showError(err.Message);
                return;
            }
            catch (SmsNotConfirmedException)
            {
                Response.Redirect("SmsConfirm.aspx?username="******"Login");

            if (cbRememberMe.Checked)
            {
                string guid = User.CreatePendingGuid(user.Username);
                Response.Cookies["rememberMe"].Value = guid;
                Response.Cookies["rememberMe"].Expires = DateTime.Now.AddDays(7);
            }

            try
            {
                IPLogger.Log(user.Username, Request.UserHostAddress, IPLogger.ActionType.Login);
            }
            catch (Exception err)
            {
                Global.Logger.LogError("LoginBox IP Logger", err);
            }

            if (!string.IsNullOrEmpty(Request.Params["back_url"]))
                Response.Redirect(Request.Params["back_url"]);
            else
                Response.Redirect(MatchmakerHelper.CurrentHomePage);
        }
예제 #3
0
        public void TryLoginThroughFacebook(LoveHitchFacebookApp facebook, long id, string accessToken, string backUrl)
        {
            FacebookHelper.SessionFacebookApp = facebook;
            FacebookHelper.CurrentSessionAccessToken = accessToken;
            FacebookHelper.CurrentSessionUserID = id;
            FacebookHelper.IsCurrentSessionConnected = true;
            FacebookHelper.SessionConnectTriesElapsed = 0;

            SetCurrentUserSession(null);
            string[] usernames = null;
            UserSession userSession;

            try
            {
                usernames = Data.User.AuthorizeByFacebookID(id);
                userSession = new UserSession(usernames[0]);
                ((PageBase)Page).CurrentUserSession = userSession;
                MatchmakerHelper.CurrentUsername = userSession.Username;
                userSession.Authorize(Session.SessionID);
                userSession.LoggedInThroughFacebook = true;
                //facebook.Session.UserId = id;
                userSession.SetFacebookApp(facebook);
                //Response.Redirect(backUrl.ToLower().Contains("loginthroughfacebook.aspx") ? "home.aspx" : backUrl);
                userSession.ToUpdateFacebookFriendsData = true;
            }
            catch (NotFoundException)
            {
                if (CurrentUserSession != null)
                {
                    CurrentUserSession.FacebookID = id;
                    CurrentUserSession.Update();
                    MatchmakerHelper.CurrentUsername = CurrentUserSession.Username;
                    if (!CurrentUserSession.IsAuthorized) CurrentUserSession.Authorize(Session.SessionID);
                    CurrentUserSession.LoggedInThroughFacebook = true;
                    if (CurrentUserSession.FacebookID.HasValue && CurrentUserSession.FacebookID > 0)
                    {
                        var qry = "SELECT uid1, uid2 FROM friend " +
                            " WHERE uid1 IN (SELECT uid2 FROM friend WHERE uid1=me()) " +
                            " AND   uid2 IN (SELECT uid2 FROM friend WHERE uid1=me())";
                        JsonArray mutualFriendsByQuery = FacebookHelper.GetFqlResult(qry);
                        Session["FacebookMutualFriends"] =
                            mutualFriendsByQuery
                                .Select(o => new MutualFriendItem
                                {
                                    FriendID = long.Parse((string)((JsonObject)o)["uid1"]),
                                    MutualFriendID = long.Parse((string)((JsonObject)o)["uid2"])
                                })
                                .ToList();
                        FacebookHelper.AddFriends(CurrentUserSession, 0, HttpContext.Current, null);
                        Response.Redirect(backUrl ?? MatchmakerHelper.CurrentHomePage);
                        //Server.Transfer(backUrl ?? MatchmakerHelper.CurrentHomePage);
                    }
                }
                else
                {
                    Response.Redirect("Registration.aspx?facebook=1&back_url=" + backUrl);
                    //Server.Transfer("Registration.aspx?facebook=1&back_url=" + backUrl);
                    return;
                }
            }
            catch (AccessDeniedException err)
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                StatusPageMessage = err.Message;
                parameters["next"] = "ShowStatus.aspx";
                //Response.Redirect(facebook.GetLogoutUrl(parameters).ToString());
                Response.Redirect("ShowStatus.aspx");
                //Server.Transfer("ShowStatus.aspx");
                return;
            }
            catch (SmsNotConfirmedException)
            {
                Response.Redirect("SmsConfirm.aspx?username="******"next"] = Config.Urls.Home + "/ShowStatus.aspx";
                //Response.Redirect(facebook.GetLogoutUrl(parameters).ToString());
                Response.Redirect("ShowStatus.aspx");
                //Server.Transfer("ShowStatus.aspx");
                return;
            }
            catch (Exception err)
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                Global.Logger.LogWarning(err);
                StatusPageMessage = err.Message;
                parameters["next"] = Config.Urls.Home + "/ShowStatus.aspx";
                Response.Redirect("ShowStatus.aspx");
                //Server.Transfer("ShowStatus.aspx"); 
                return;
            }
            //Response.Redirect(backUrl.ToLower().Contains("loginthroughfacebook.aspx") ? "default.aspx" : backUrl);
            Response.Redirect(MatchmakerHelper.CurrentHomePage);
            //Response.Redirect("ManageProfile.aspx");
            //Server.Transfer("default.aspx", false);
        }
예제 #4
0
        protected void TryLogin()
        {
            string xmlToken;
            xmlToken = Request.Params["xmlToken"];
            if (xmlToken == null || xmlToken.Equals(""))
            {
                return;
            }

            Token token = new Token(xmlToken);
            UserSession user = null;
            try
            {
                string username = Classes.User.GetUsernameByTokenUniqueId(token.UniqueID);
                if (username == null)
                {
                    ClientScript.RegisterClientScriptBlock(GetType(), "error",
                        String.Format("var alert_string = '{0}';", Lang.Trans("This card is not associated with any account!")), 
                        true);
                    return;
                }
                user = new UserSession(username);
                Classes.User.AuthorizeByToken(token.UniqueID);
                user.Authorize(Session.SessionID);
            }
            catch (NotFoundException err)
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "error", String.Format("var alert_string = '{0}';",
                                                                                         err.Message), true);
                return;
            }
            catch (AccessDeniedException err)
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "error", String.Format("var alert_string = '{0}';",
                                                                                         err.Message), true);
                return;
            }
            catch (SmsNotConfirmedException err)
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "error",
                    String.Format("var alert_string = '{0}'; window.opener.location = 'SmsConfirm.aspx?username={1}'; window.close();",
                    err.Message, user.Username), true);
                return;
            }
            catch (ArgumentException err)
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "error", String.Format("var alert_string = '{0}';",
                                                                                         err.Message), true);
                return;
            }
            catch (Exception err)
            {
                Global.Logger.LogWarning(err);
                ClientScript.RegisterClientScriptBlock(GetType(), "error", String.Format("var alert_string = '{0}';",
                                                                                         err.Message), true);
                return;
            }

            ((PageBase)Page).CurrentUserSession = user;

            if (user.PrevLogin.Date != DateTime.Now.Date)
                Classes.User.AddScore(user.Username, Config.UserScores.DailyLogin, "Login");

            try
            {
                IPLogger.Log(user.Username, Request.UserHostAddress, IPLogger.ActionType.LoginCardSpace);
            }
            catch (Exception err)
            {
                Global.Logger.LogError("LoginCardSpace IP Logger", err);
            }

            if (Request.Params["back_url"] != null
                && Request.Params["back_url"].Length > 0)
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "redirect",
                    String.Format("window.opener.location = '{0}'; window.close();",
                    user.Username), true);
            }
            else
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "redirect",
                    String.Format("window.opener.location = '{0}'; window.close();",
                    Config.Urls.Home + "/Home.aspx"), true);
            }
        }
예제 #5
0
        private void PopulateUserDataUsingFacebook()
        {
            ezFixUpFacebookApp facebook = null;
            if (Global.GetSessionState()["facebook"] != null)
            {
                facebook = (ezFixUpFacebookApp)Global.GetSessionState()["facebook"];
            }
            else if ((Global.GetSessionState()["facebookAccessToken"] != null) &&
                     (((String)Global.GetSessionState()["facebookAccessToken"]).Length > 0))
            {
                facebook = new ezFixUpFacebookApp((String)Global.GetSessionState()["facebookAccessToken"]);
            }
            else if (Request.QueryString["access_token"] != null && Request.QueryString["access_token"].Length > 0)
            {
                facebook = new ezFixUpFacebookApp(Request.QueryString["access_token"]);
            }
            else
            {
                facebook = new ezFixUpFacebookApp();
            }

            Facebook.JsonObject user;
            long id;

            if (facebook.AppSecret == null)
            {
                facebook.AppSecret = Properties.Settings.Default.Facebook_Secret_Key;
            }
            try
            {
                user = facebook.Api("/me") as Facebook.JsonObject;

                if (user != null && user["id"] != null
                    && long.TryParse((String)user["id"], out id) && id > 0)
                {
                    FacebookID = id;

                    #region log on the user if she is already registered

                    string[] usernames = Classes.User.FetchUsernamesByFacebookID(new[] { facebook.UserId });
                    if (usernames.Length > 0)
                    {
                        UserSession userSession;
                        try
                        {
                            userSession = new UserSession(usernames[0]);
                            Classes.User.AuthorizeByFacebookID(facebook.UserId);
                            ((PageBase)Page).CurrentUserSession = userSession;
                            MatchmakerHelper.CurrentUsername = userSession.Username;
                            userSession.Authorize(Session.SessionID);
                        }
                        catch (NotFoundException)
                        {
                            goto populatedate;
                        }
                        catch (AccessDeniedException err)
                        {
                            IDictionary<string, object> parameters = new Dictionary<string, object>();
                            StatusPageMessage = err.Message;
                            parameters["next"] = Config.Urls.Home + "/ShowStatus.aspx";
                            Response.Redirect(facebook.GetLogoutUrl(parameters).ToString());
                            return;
                        }
                        catch (SmsNotConfirmedException)
                        {
                            Response.Redirect("SmsConfirm.aspx?username="******"next"] = Config.Urls.Home + "/ShowStatus.aspx";
                            Response.Redirect(facebook.GetLogoutUrl(parameters).ToString());
                            return;
                        }
                        catch (Exception err)
                        {
                            IDictionary<string, object> parameters = new Dictionary<string, object>();
                            Global.Logger.LogWarning(err);
                            StatusPageMessage = err.Message;
                            parameters["next"] = Config.Urls.Home + "/ShowStatus.aspx";
                            Response.Redirect(facebook.GetLogoutUrl(parameters).ToString());
                            return;
                        }
                        CurrentUserSession = userSession;
                        CurrentUserSession.LoggedInThroughFacebook = true;
                        Response.Redirect("Home.aspx");
                    }

                    #endregion

                populatedate:

                    string fbImgUrl = FacebookHelper.GetProfilePictureSource(facebook, id);
                    //ImageHandler.CreateFacebookImageUrl(id, ImageHandler.eFacebookImageType.Large);
                    this.LastAsyncFileUploadLocation = fbImgUrl;

                    var o = new FacebookHelper.FetchAndSaveSaveFacebookFriendImageClass();
                    o.FetchAndSaveFacebookImageBySource(fbImgUrl, id);

                    JsonObject friends = facebook.Api("/me/friends") as JsonObject;
                    if (friends != null)
                    {
                        JsonArray friendsArr = friends["data"] as JsonArray;
                        FacebookFriendIDs = new long[friendsArr.Count];
                        for (int i = 0; i < friendsArr.Count(); i++)
                        {
                            long.TryParse((string)((JsonObject)friendsArr[i])["id"], out FacebookFriendIDs[i]);
                        }
                    }
                    if (user != null)
                    {
                        DateTime birthday;
                        if (DateTime.TryParse((String)user["birthday"], CultureInfo.InvariantCulture,
                                              DateTimeStyles.None, out birthday))
                        {
                            datePicker1.SelectedDate = birthday;
                            //txtDatePicker.Text = datePicker1.SelectedDate.ToShortDateString();
                            BirthdayPicker1.CurrentText = datePicker1.SelectedDate.ToShortDateString();
                        }
                        Classes.User.eGender? gender = null;

                        if (!String.IsNullOrEmpty((String)user["gender"]))
                        {
                            switch (((String)user["gender"]).ToLower(CultureInfo.InvariantCulture))
                            {
                                case "male":
                                    gender = Classes.User.eGender.Male;
                                    break;
                                case "female":
                                    gender = Classes.User.eGender.Female;
                                    break;
                            }
                        }
                        if (gender.HasValue)
                        {
                            dropGender.SelectedValue = ((int)gender).ToString();

                            switch (gender)
                            {
                                case Classes.User.eGender.Male:
                                    dropInterestedIn.SelectedValue = ((int)Classes.User.eGender.Female).ToString();
                                    break;
                                case Classes.User.eGender.Female:
                                    dropInterestedIn.SelectedValue = ((int)Classes.User.eGender.Male).ToString();
                                    break;
                            }
                        }

                        if (user.ContainsKey("location"))
                        {
                            JsonObject location = (JsonObject)user["location"];
                            string locationName = null;
                            if (location.ContainsKey("name"))
                            {
                                locationName = (string)location["name"];
                            }
                            if (locationName.IsNotNullOrEmpty())
                            {
                                string[] locationTokens = locationName.Split(new[] { "," },
                                                                             StringSplitOptions.RemoveEmptyEntries);
                                var fbCountry = locationTokens.Length > 2 ? locationTokens[2].Trim() : "";
                                var fbRegion = locationTokens.Length > 1 ? locationTokens[1].Trim() : "";
                                var fbCity = locationTokens.Length > 0 ? locationTokens[0].Trim() : "";

                                var allCountries = Config.Users.GetCountries();
                                var regions = new string[0];
                                var cities = new string[0];
                                foreach (var country in allCountries)
                                {
                                    this.dropCountry.Items.Add(country);
                                    if (country.Contains(fbCountry))
                                    {
                                        this.dropCountry.SelectedValue = country;
                                    }
                                }
                                if (this.dropCountry.SelectedIndex > 0)
                                {
                                    regions = Config.Users.GetRegions(this.dropCountry.SelectedValue);
                                    foreach (var region in regions)
                                    {
                                        this.dropRegion.Items.Add(region);
                                        if (region.Contains(fbRegion))
                                        {
                                            this.dropRegion.SelectedValue = region;
                                        }
                                    }
                                    if (this.dropRegion.SelectedIndex > 0)
                                        cities = Config.Users.GetCities(this.dropCountry.SelectedValue,
                                                                        this.dropRegion.SelectedValue);
                                    foreach (var city in cities)
                                    {
                                        this.dropCity.Items.Add(city);
                                        if (city.Contains(fbCity))
                                            dropCity.SelectedValue = city;
                                    }
                                }
                            }
                        }

                        if (user.ContainsKey("big_pic") && !String.IsNullOrEmpty((String)user["pic_big"]))
                            PrimaryPhotoURL = (String)user["pic_big"];
                        else
                            PrimaryPhotoURL = String.Format("https://graph.facebook.com/{0}/picture?type={1}", id
                                                             , Config.FacebookSettings.FacebookDefaultImageIsNormal
                                                                            ? ezFixUp.ImageHandler.eFacebookImageType.Normal.ToString().ToLower()
                                                                            : ezFixUp.ImageHandler.eFacebookImageType.Large.ToString().ToLower());

                        if (user.ContainsKey("email") && !String.IsNullOrEmpty((String)user["email"]))
                            FacebookEmail = (String)user["email"];
                        txtEmail.Text = FacebookEmail;

                        //var albums = facebookService.photos.getAlbums(user.uid).ToArray();
                        //albums[0].

                        txtName.Text = (String)user["name"];
                        txtUsername.Text = (String)user["username"];
                        IsFacebookVerified = false;

                        if (user.ContainsKey("verified") && (user["verified"] is bool))
                            IsFacebookVerified = (bool)user["verified"];

                        //divCardSpace.Visible = false;
                        //divMySpace.Visible = false;
                        divFacebook.Visible = false;
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
예제 #6
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {

            if (!FacebookHelper.IsCurrentSessionConnected)
            {
                #region Validate username

                Global.GetSessionState()["IsRegistrationFormValidated"] = false;

                try
                {
                    if (txtUsername.Text.Length < 6)
                    {
                        ResponseEndWithErrorMessage("Please specify username, at list 6 alphanumeric characters!");
                        return;
                    }

                    if (Classes.User.IsUsernameTaken(txtUsername.Text))
                    {
                        ResponseEndWithErrorMessage("Username is already taken!");
                        return;
                    }

                    foreach (string reservedUsername in Config.Users.ReservedUsernames)
                    {
                        if (reservedUsername == txtUsername.Text.ToLower())
                        {
                            ResponseEndWithErrorMessage("Username is reserved!");
                            return;
                        }
                    }
                }
                catch (ArgumentException err) // Invalid username
                {
                    ResponseEndWithErrorMessage(err.Message);
                    return;
                }

                #endregion

                #region Validate passwords

                if (txtPassword.Text.Length < 6)
                {
                    ResponseEndWithErrorMessage("Please specify password, at leaset 6 alphanumeric characters!");
                    return;
                }
                if (txtPassword2.Text.Length == 0)
                {
                    ResponseEndWithErrorMessage("Please verify password!");
                    return;
                }
                if (txtPassword.Text != txtPassword2.Text)
                {
                    ResponseEndWithErrorMessage("Passwords do not match!");
                    return;
                }

                #endregion

                #region Validate captcha

                if (Config.Misc.EnableCaptcha &&
                        (Global.GetSessionState()["Captcha_RandomCode"] == null || (string)Global.GetSessionState()["Captcha_RandomCode"] != txtCaptcha.Text))
                {
                    Global.GetSessionState()["Captcha_RandomCode"] = null;
                    UpdatePanel4.Update();
                    ResponseEndWithErrorMessage("Invalid verification code!");
                    return;
                }

                #endregion
            }
            else
            {
                txtUsername.Text = FacebookHelper.CurrentSessionUserID.ToString();
            }
            #region Validate e-mail address

            try
            {
                if (txtEmail.Text.Length == 0)
                {
                    ResponseEndWithErrorMessage("Please specify e-mail address!");
                    return;
                }

                if (txtEmail.Text.ToLower().EndsWith("@mail.bg"))
                {
                    ResponseEndWithErrorMessage("E-mails from mail.bg are not accepted!");
                    return;
                }

                if (Config.Users.CheckForDuplicateEmails && Classes.User.IsEmailUsed(txtEmail.Text))
                {
                    ResponseEndWithErrorMessage("E-mail address is already used!");
                    return;
                }
            }
            catch (ArgumentException err) // Invalid e-mail address
            {
                ResponseEndWithErrorMessage(err.Message);
                return;
            }

            #endregion

            #region Validate name

            if (txtName.Text.Length == 0)
            {
                ResponseEndWithErrorMessage("Please enter your name!");
                return;
            }

            #endregion

            #region Validate gender

            if (dropGender.SelectedIndex < 0)
            {
                ResponseEndWithErrorMessage("Please select your gender!");
                return;
            }

            #endregion

            bool isSingleAccount = (rblAccountType.SelectedIndex > 0);
            if (isSingleAccount)
            {
                #region Validate InterestedIn

                if (Config.Users.InterestedInFieldEnabled)
                {
                    if (dropInterestedIn.SelectedIndex < 0)
                    {
                        ResponseEndWithErrorMessage("Please select who are you interested in!");
                        return;
                    }
                }

                #endregion

                #region Validate birthdate1

                //IFormatProvider culture = new CultureInfo("he-IL", true);
                //string dateFormat = "dd/MM/yyyy";
                //DateTime parsedDate;
                //if (DateTime.TryParseExact(txtDatePicker.Text, dateFormat, culture, DateTimeStyles.None, out parsedDate))
                //    datePicker1.SelectedDate = parsedDate;
                datePicker1.SelectedDate = BirthdayPicker1.SelectedDate;
                if (!datePicker1.ValidDateEntered)
                {
                    ResponseEndWithErrorMessage("Please select valid birthdate!");
                    return;
                }

                #endregion

                //#region Validate birthdate2
                //if((User.eGender)Convert.ToInt32(dropGender.SelectedValue) == Classes.User.eGender.Couple
                //        && !datePicker2.ValidDateEntered) 
                //{
                //    lblError.Text = Lang.Trans("Please select valid birthdate") + "!";
                //    return;
                //}
                //#endregion

                #region Validate location

                if (Config.Users.LocationPanelVisible)
                {
                    if (dropCountry != null && dropCountry.SelectedValue == String.Empty)
                    {
                        ResponseEndWithErrorMessage("Please select your country!");
                        return;
                    }
                    //if (txtZipCode != null && txtZipCode.Text == String.Empty)
                    //{
                    //    lblError.Text = Lang.Trans("Please enter your Zip/Postal Code");
                    //    return;
                    //}

                    //ifA B                                                                                                                                                                                                                                                          VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV(dropRegion.Items.Count >= 1 && dropRegion.SelectedValue == "") {
                    //    ResponseEndWithErrorMessage("Please select your state!");
                    //    return;
                    //}
                    //if(dropCity != null && dropCity.SelectedValue == "") {
                    //    ResponseEndWithErrorMessage("Please select your city!");
                    //    return;
                    //}
                }

                #endregion
            }

            #region Validate agreement

            if (!cbAgreement.Checked)
            {
                ResponseEndWithErrorMessage("You must accept the agreement to proceed!");
                return;
            }

            #endregion


            #region Validate Invitation Code
            if (Config.Users.InvitationCode != String.Empty)
            {
                if (Config.Users.InvitationCode != txtInvitationCode.Text)
                {
                    ResponseEndWithErrorMessage("Invalid Invitation Code!");
                    return;
                }
            }
            #endregion

            #region Validate IP address

            if (Properties.Settings.Default.BannedCountries.Count > 0)
            {
                foreach (string countryCode in Properties.Settings.Default.BannedCountries)
                {
                    if (IPToCountry.GetCountry(Request.UserHostAddress) == countryCode.Trim())
                    {
                        ResponseEndWithErrorMessage("Registration is not allowed for your country!");
                        return;
                    }
                }
            }

            #endregion

            Global.GetSessionState()["IsRegistrationFormValidated"] = true;

            var postRegistrationPopup = @"<div class='PostRegistrationPopupBg' >
                                        <table border='0' cellpadding='0' cellspacing='0' width='100%'>
                                            <tr style='height:40px;width:100%;'>
                                                <td></td>
                                            </tr>
                                            <tr style='height:30px;width:100%;'>
                                                <td></td>
                                            </tr>
                                            <tr style='height:55px;width:100%;'>
                                                <td>
                                                    <div class='fl' style='width:220px;height:50px;margin-left:40px;cursor:pointer;' 
                                                        onclick=""window.location='ManageProfile.aspx'""></div>
                                                    <div class='fl' style='width:200px;height:50px;margin-left:20px;cursor:pointer;'
                                                        onclick=""window.location='Home.aspx'""></div>
                                                </td>
                                            </tr>
                                            <tr style='height:30px;width:100%;'>
                                                <td></td>
                                            </tr>
                                        </table>
                                    </div>";
            //postRegistrationPopup = "";
            #region Validate Coupon Code
            var couponTxt = txtCouponCode.Text.Trim();
            bool useCoupon = false;
            Coupon coupon = null;

            if (couponTxt.IsNullOrEmpty())
                couponTxt = "FA7Z8X";

            //if (couponTxt.IsNotNullOrEmpty())
            {
                coupon = Coupon.Fetch(couponTxt);
                if (coupon == null)
                {
                    ResponseEndWithErrorMessage("Invalid Coupon Code!");
                    return;
                }
                else if (coupon.MaxUse > coupon.Used)
                {
                    useCoupon = true;
                    Coupon.UpdateUsedCounterByAddCount(couponTxt, 1);
                }
            }
            #endregion

            try
            {
                User newUser = new User(txtUsername.Text);

                newUser.Gender = (User.eGender)Convert.ToInt32(dropGender.SelectedValue);
                if (newUser.Gender == Classes.User.eGender.Couple)
                {
                    newUser.Birthdate2 = datePicker2.SelectedDate;
                }


                if (isSingleAccount)
                {
                    #region Save location

                    if (Config.Users.LocationPanelVisible)
                    {
                        if (dropCountry != null)
                        {
                            newUser.Country = dropCountry.SelectedValue;
                        }
                        if (dropRegion != null)
                        {
                            newUser.State = dropRegion.SelectedValue;
                        }
                        //if (txtZipCode != null)
                        //{
                        //    newUser.ZipCode = txtZipCode.Text;
                        //}
                        if (dropCity != null)
                        {
                            newUser.City = dropCity.SelectedValue;
                        }

                        Location loc = Config.Users.GetLocation(newUser.Country, newUser.State, newUser.City);

                        if (loc != null)
                        {
                            newUser.Longitude = loc.Longitude;
                            newUser.Latitude = loc.Latitude;
                        }
                    }

                    #endregion

                    if (Config.Users.InterestedInFieldEnabled)
                    {
                        newUser.InterestedIn = (User.eGender)Convert.ToInt32(dropInterestedIn.SelectedValue);
                    }
                    else
                    {
                        if (Config.Users.DisableGenderInformation)
                            newUser.InterestedIn = Classes.User.eGender.Male;
                        else
                            newUser.InterestedIn = newUser.Gender == Classes.User.eGender.Male
                                                     ? Classes.User.eGender.Female
                                                     : Classes.User.eGender.Male;
                    }

                }

                datePicker1.SelectedDate = BirthdayPicker1.SelectedDate;// DateTime.Parse(txtDatePicker.Text);
                newUser.Birthdate = datePicker1.SelectedDate;

                newUser.Email = txtEmail.Text;
                newUser.Name = txtName.Text;
                var pass = (-DateTime.Now.Ticks).ToString();
                if (pass.Length > 20) pass = pass.Substring(0, 20);
                newUser.Password = FacebookHelper.IsCurrentSessionConnected
                                        ? pass : txtPassword.Text;
                newUser.LanguageId = LanguageId;

                newUser.ReceiveEmails = Config.Users.EmailNotificationsDefault;
                if (ViewState["TokenUniqueId"] is string)
                    newUser.TokenUniqueId = (string)ViewState["TokenUniqueId"];

                #region Set and Delete invitedBy cookie

                if (Request.Cookies["invitedBy"] != null)
                {
                    newUser.InvitedBy = Server.HtmlEncode(Request.Cookies["invitedBy"].Value);

                    HttpCookie cookie = new HttpCookie("invitedBy");
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(cookie);
                }

                #endregion

                #region Set and Delete affiliateID cookie

                if (Request.Cookies["affiliateID"] != null)
                {
                    newUser.AffiliateID = Convert.ToInt32(Server.HtmlEncode(Request.Cookies["affiliateID"].Value));

                    HttpCookie cookie = new HttpCookie("affiliateID");
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(cookie);
                }

                #endregion

                if (Config.Misc.EnableMySpaceIntegration)
                    newUser.MySpaceID = MySpaceID;

                if (Config.Misc.EnableFacebookIntegration)
                    newUser.FacebookID = FacebookID;

                newUser.Create(Request.UserHostAddress);

                if (useCoupon)
                {
                    var username = newUser.Username;
                    Coupon.UpdateUsedCounterByAddCount(couponTxt, 1);

                    //give coupon gift to new user

                    var allBillingPlans = BillingPlan.Fetch();
                    BillingPlan plan = allBillingPlans.Where(p => p.Cycle == 1).FirstOrDefault();

                    var subId = Subscription.Create(username, plan.ID, "coupon = " + couponTxt);
                    var activeSubscription = Subscription.Fetch(subId);
                    activeSubscription.Activate(DateTime.Now);

                    if (coupon.CouponTypeId > (int)CouponType.eCouponType.PremiumMonth1)
                        activeSubscription.Renew(plan);

                    if (coupon.CouponTypeId > (int)CouponType.eCouponType.PremiumMonth2)
                        activeSubscription.Renew(plan);
                }
                else
                {
                    newUser.Credits = 181818;
                    newUser.Update();
                }

                if (Global.GetSessionState().ContainsKey("InvitedBy"))
                {
                    newUser.InvitedBy = Global.GetSessionState()["InvitedBy"] as string;
                    var byUser = Classes.User.Load(newUser.InvitedBy);
                    if (byUser != null)
                    {
                        byUser.InvitedByCount++;

                        if ((byUser.InvitedByCount % Config.UserScores.InvitedByCounter) == 0)
                        {
                            // Send Announcement Message + Assign a Gift
                            byUser.SendMessageInvitedByCounterTriggered("");
                        }
                        byUser.Update();
                    }
                    else
                    {
                        var invitations = HttpContext.Current.GetAppInvitationsForCurrentUser()
                                            .Where(i => i.CreatedTime > DateTime.Now.AddYears(-1))
                                            .OrderByDescending(i => i.CreatedTime)
                                            .Take(10).ToList(); //max 10 users in last year will be credited 

                        foreach (var inv in invitations)
                        {
                            var newInvitation = new FacebookInvitation(inv.RequestId, inv.SenderId, inv.RecipientId, inv.CreatedTime);
                            newInvitation.Save();
                        }
                    }
                }

                newUser.updateLastLogin(newUser.LastSessionID);

                StorePrimaryPhoto(newUser);
                if (File.Exists(LastAsyncFileUploadLocation))
                    File.Delete(LastAsyncFileUploadLocation);

                if (Config.Users.SmsConfirmationRequired)
                {
                    Response.Redirect("SmsConfirm.aspx?username="******"<b>Your account has been created successfully!</b><br>" +
                    //                                   "Please click on the link below to edit your profile.<br><br>");

                    //NameValueCollection link = new NameValueCollection();
                    //link.Add(Config.Urls.Home + "/ManageProfile.aspx", Config.Urls.Home + "/ManageProfile.aspx");
                    //StatusPageLink = link;
                    //((PageBase)Page).StatusPageLinkSkindId = "";
                    //((PageBase)Page).StatusPageLinkText = Config.Urls.Home + "/ManageProfile.aspx";
                    //((PageBase)Page).StatusPageLinkURL = Config.Urls.Home + "/ManageProfile.aspx";

                    UserSession userSession = null;
                    try
                    {
                        userSession = new UserSession(newUser.Username);
                        ((PageBase)Page).CurrentUserSession = userSession;
                        MatchmakerHelper.CurrentUsername = userSession.Username;
                        userSession.Authorize(Session.SessionID);

                        //if(Config.Misc.EnableMySpaceIntegration ||
                        if (Config.Misc.EnableFacebookIntegration)
                        {
                            FacebookHelper.AddFriends(newUser, 0, HttpContext.Current, null);
                        }


                        #region Autojoin to group

                        Group[] autojoinGroups = Group.Fetch(true);

                        if (autojoinGroups.Length > 0)
                        {
                            var groups =
                                    autojoinGroups.Where(
                                            g => g.Approved &&
                                            (g.AutojoinCountry == null || g.AutojoinCountry == userSession.Country) &&
                                            (g.AutojoinRegion == null || g.AutojoinRegion == userSession.State) &&
                                            (g.AutojoinCity == null || g.AutojoinCity == userSession.City));
                            foreach (Group group in groups)
                            {
                                GroupMember groupMember = new GroupMember(group.ID, userSession.Username);
                                groupMember.Active = true;
                                groupMember.Type = GroupMember.eType.Member;
                                groupMember.Save();
                                group.ActiveMembers++;
                                group.Save();
                            }
                        }

                        #endregion

                        //Response.Redirect("ManageProfile.aspx");
                        //multiViewButtons.ActiveViewIndex = 1;
                        //return;
                        StatusPageMessage = Lang.Trans("<b>Your account has been created successfully!</b><br><br>")
                                            + postRegistrationPopup;

                    }
                    catch (Exception err)
                    {
                        StatusPageMessage = err.Message;
                    }
                }
                else
                {
                    newUser.Active = false;
                    newUser.Update();
                    StatusPageMessage = Lang.Trans
                                            ("<b>Your account has been created successfully!</b><br><br>"
                                             + "You will receive a confirmation e-mail shortly. In order "
                                             + "to finish your registration you'll have to click the "
                                             + "activation link in the e-mail.");
                    Email.SendTemplateEmail(typeof(EmailTemplates.RegistrationConfirmation), newUser.Email, true, newUser.LanguageId);
                }
                if (newUser.InterestedIn == Classes.User.eGender.Matchmaker)
                    Response.Redirect("Home_mm.aspx");
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (ArgumentException err)
            {
                ResponseEndWithErrorMessage(err.Message);
                return;
            }
            catch (Exception err)
            {
                ResponseEndWithErrorMessage("Unknown error has occured while trying to create your account! Please try again later.");
                Log(err);
                return;
            }
            Response.Redirect("ShowStatus.aspx");
        }
예제 #7
0
        private void isRememberMeActivated()
        {
            if (Request.Cookies["rememberMe"] != null)
            {
                string guid = Request.Cookies["rememberMe"].Value;
                string username = Classes.User.FetchUserByGuid(guid);
                Classes.User user = null;
                try
                {
                    user = Classes.User.Load(username);
                    UserSession userSession = new UserSession(user.Username);
                    if (!user.Active)
                    {
                        if (!user.SmsConfirmed && Config.Users.SmsConfirmationRequired)
                        {
                            throw new SmsNotConfirmedException
                                (Lang.Trans("This account is not yet SMS confirmed!"));
                        }

                        throw new AccessDeniedException
                            (Lang.Trans("This account is not yet activated!"));
                    }

                    if (user.Deleted)
                    {
                        if (user.DeleteReason == null || user.DeleteReason.Trim().Length == 0)
                            throw new AccessDeniedException
                                (Lang.Trans("This user has been deleted!"));

                        throw new AccessDeniedException
                            (String.Format(Lang.Trans("This user has been deleted ({0})"), user.DeleteReason));
                    }

                    if (Config.Misc.EnableFacebookIntegration && FacebookHelper.IsCurrentSessionConnected && FacebookHelper.CurrentSessionUserID > 0)
                    {
                        if (user.FacebookID.HasValue)
                        {
                            if (FacebookHelper.CurrentSessionUserID != user.FacebookID)
                            {
                                throw new NotFoundException("The last ezFixUp user's Facebook ID connected from this computer doesn't match the current logged in Facebook user ID");
                                //FacebookHelper.SessionClear(Config.Urls.Home + "/LoginThroughFacebook.aspx");
                            }
                        }
                        else
                        {
                            user.FacebookID = FacebookHelper.CurrentSessionUserID;
                            user.Update();
                        }
                    }

                    ((PageBase)Page).CurrentUserSession = userSession;
                    MatchmakerHelper.CurrentUsername = userSession.Username;
                    userSession.Authorize(Session.SessionID);
                    
                    if (user.PrevLogin.Date != DateTime.Now.Date)
                        Classes.User.AddScore(user.Username, Config.UserScores.DailyLogin, "Login");

                    try
                    {
                        IPLogger.Log(user.Username, Request.UserHostAddress, IPLogger.ActionType.Login);
                    }
                    catch (Exception err)
                    {
                        Global.Logger.LogError("LoginBox IP Logger", err);
                    }
                }
                catch (NotFoundException err)
                {
                    Response.Cookies["rememberMe"].Expires = DateTime.Now.AddDays(-1);
                    lblError.Text = err.Message;
                    lblError.Visible = true;
                    return;
                }
                catch (AccessDeniedException err)
                {
                    lblError.Text = err.Message;
                    lblError.Visible = true;
                    return;
                }
                catch (SmsNotConfirmedException err)
                {
                    lblError.Text = err.Message;
                    lblError.Visible = true;
                    Response.Redirect("SmsConfirm.aspx?username="******"back_url"]))
                {
                    Response.Redirect(Request.Params["back_url"]);
                    return;
                }
                Response.Redirect("Home.aspx");
                return;
            }
        }
예제 #8
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text.Length == 0)
            {
                lblError.Text = Lang.Trans("Please specify username!");
                return;
            }
            if (txtPassword.Text.Length == 0)
            {
                lblError.Text = Lang.Trans("Please specify password!");
                return;
            }

            UserSession user;
            try
            {
                user = new UserSession(txtUsername.Text);
                user.StealthMode = cbStealthMode.Checked;
                user.Authorize(txtPassword.Text, Session.SessionID);
                //if(Config.Misc.EnableMySpaceIntegration ||
                if (Config.Misc.EnableFacebookIntegration && user.FacebookID.HasValue && user.FacebookID > 0)
                {
                    FacebookHelper.AddFriends(user, 60, HttpContext.Current, null);
                }
            }
            catch (NotFoundException err)
            {
                lblError.Text = err.Message;
                return;
            }
            catch (AccessDeniedException err)
            {
                lblError.Text = err.Message;
                return;
            }
            catch (SmsNotConfirmedException err)
            {
                lblError.Text = err.Message;
                Response.Redirect("SmsConfirm.aspx?username="******"Login");

            if (cbRememberMe.Checked || Request.Cookies["rememberMe"] != null)
            {
                string guid = Classes.User.CreatePendingGuid(user.Username);
                Response.Cookies["rememberMe"].Value = guid;
                Response.Cookies["rememberMe"].Expires = DateTime.Now.AddDays(7);
            }

            try
            {
                IPLogger.Log(user.Username, Request.UserHostAddress, IPLogger.ActionType.Login);
            }
            catch (Exception err)
            {
                Global.Logger.LogError("LoginBox IP Logger", err);
            }

            if (Request.Params["timestamp"] != null && !string.IsNullOrEmpty(Request.Params["back_url"]) && 
                !string.IsNullOrEmpty(Properties.Settings.Default.AuthSecretKey))
            {
                var timestamp = Request.Params["timestamp"];
                var sha1 = new SHA1Managed();
                var paramBytes = Encoding.UTF8.GetBytes(user.Username + timestamp + 
                    Properties.Settings.Default.AuthSecretKey);
                var hashBytes = sha1.ComputeHash(paramBytes);
                var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();

                var redirectUrl = String.Format("{3}{4}name={0}&timestamp={1}&hash={2}", user.Username, 
                    timestamp, hash, Request.Params["back_url"], 
                    Request.Params["back_url"].Contains("?") ? ":" : "?");
                if (!Config.Users.DisableGenderInformation)
                    redirectUrl += "&gender=" + user.Gender;
                Response.Redirect(redirectUrl);
            }
            else if (!string.IsNullOrEmpty(Request.Params["back_url"]))
                Response.Redirect(Request.Params["back_url"]);
            else
                Response.Redirect("Home.aspx");
        }
예제 #9
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            #region Validate username

            try
            {
                if (txtUsername.Text.Length == 0)
                {
                    lblError.Text =
                        Lang.Trans("Please specify username!");
                    return;
                }

                if (Classes.User.IsUsernameTaken(txtUsername.Text))
                {
                    lblError.Text =
                        Lang.Trans("Username is already taken!");
                    return;
                }

                foreach (string reservedUsername in Config.Users.ReservedUsernames)
                {
                    if (reservedUsername == txtUsername.Text.ToLower())
                    {
                        lblError.Text = Lang.Trans("Username is reserved!");
                        return;
                    }
                }
            }
            catch (ArgumentException err) // Invalid username
            {
                lblError.Text = err.Message;
                return;
            }

            #endregion

            #region Validate e-mail address

            try
            {
                if (txtEmail.Text.Length == 0)
                {
                    lblError.Text =
                        Lang.Trans("Please specify e-mail address!");
                    return;
                }

                if (txtEmail.Text.ToLower().EndsWith("@mail.bg"))
                {
                    lblError.Text =
                        Lang.Trans("E-mails from mail.bg are not accepted!");
                    return;
                }

                if (Config.Users.CheckForDuplicateEmails && Classes.User.IsEmailUsed(txtEmail.Text))
                {
                    lblError.Text =
                        Lang.Trans("E-mail address is already used!");
                    return;
                }
            }
            catch (ArgumentException err) // Invalid e-mail address
            {
                lblError.Text = err.Message;
                return;
            }

            #endregion

            #region Validate passwords

            if (txtPassword.Text.Length == 0)
            {
                lblError.Text = Lang.Trans("Please specify password!");
                return;
            }
            if (txtPassword2.Text.Length == 0)
            {
                lblError.Text = Lang.Trans("Please verify password!");
                return;
            }
            if (txtPassword.Text != txtPassword2.Text)
            {
                lblError.Text = Lang.Trans("Passwords do not match!");
                return;
            }

            #endregion

            #region Validate name

            if (txtName.Text.Length == 0)
            {
                lblError.Text = Lang.Trans("Please enter your name!");
                return;
            }

            #endregion

            #region Validate gender

            if (dropGender.SelectedIndex == 0)
            {
                lblError.Text = Lang.Trans("Please select your gender!");
                return;
            }

            #endregion

            #region Validate InterestedIn

            if (Config.Users.InterestedInFieldEnabled)
            {
                if (dropInterestedIn.SelectedIndex == 0)
                {
                    lblError.Text = Lang.Trans("Please select who are you interested in!");
                    return;
                }
            }

            #endregion

            #region Validate birthdate1

            if (!datePicker1.ValidDateEntered)
            {
                lblError.Text = Lang.Trans("Please select your birthdate!");
                return;
            }

            #endregion

            #region Validate birthdate2

            if ((User.eGender)Convert.ToInt32(dropGender.SelectedValue) == Classes.User.eGender.Couple
                && !datePicker2.ValidDateEntered)
            {
                lblError.Text = Lang.Trans("Please select your birthdate!");
                return;
            }

            #endregion

            #region Validate agreement

            if (!cbAgreement.Checked)
            {
                lblError.Text = Lang.Trans("You must accept the agreement to proceed!");
                return;
            }

            #endregion

            #region Validate location

            if (Config.Users.LocationPanelVisible)
            {
                if (dropCountry != null && dropCountry.SelectedValue == String.Empty)
                {
                    lblError.Text = Lang.Trans("Please select your country!");
                    return;
                }

                if (dropRegion.Items.Count > 1 && dropRegion.SelectedValue == "")
                {
                    lblError.Text = Lang.Trans("Please select your state!");
                    return;
                }

                if (txtZipCode != null && txtZipCode.Text == String.Empty)
                {
                    lblError.Text = Lang.Trans("Please enter your Zip/Postal Code");
                    return;
                }

                if (dropCity != null && dropCity.SelectedValue == "")
                {
                    lblError.Text = Lang.Trans("Please select your city!");
                    return;
                }
            }

            #endregion

            #region Validate Invitation Code

            if (Config.Users.InvitationCode != String.Empty)
            {
                if (Config.Users.InvitationCode != txtInvitationCode.Text)
                {
                    lblError.Text = Lang.Trans("Invalid Invitation Code!");
                    return;
                }
            }

            #endregion

            #region Validate IP address

            if (Properties.Settings.Default.BannedCountries.Count > 0)
            {
                foreach (string countryCode in Properties.Settings.Default.BannedCountries)
                {
                    if (IPToCountry.GetCountry(Request.UserHostAddress) == countryCode.Trim())
                    {
                        lblError.Text = Lang.Trans("Registration is not allowed for your country!");
                        return;
                    }
                }
            }

            #endregion

            try
            {
                User newUser = new User(txtUsername.Text);

                #region Save location

                if (Config.Users.LocationPanelVisible)
                {
                    if (dropCountry != null)
                    {
                        newUser.Country = dropCountry.SelectedValue;
                    }
                    if (dropRegion != null)
                    {
                        newUser.State = dropRegion.SelectedValue;
                    }
                    if (txtZipCode != null)
                    {
                        newUser.ZipCode = txtZipCode.Text;
                    }
                    if (dropCity != null)
                    {
                        newUser.City = dropCity.SelectedValue;
                    }

                    Location loc = Config.Users.GetLocation(newUser.Country, newUser.State, newUser.City);

                    if (loc != null)
                    {
                        newUser.Longitude = loc.Longitude;
                        newUser.Latitude = loc.Latitude;
                    }
                }

                #endregion

                newUser.Password = txtPassword.Text;
                newUser.Email = txtEmail.Text;
                newUser.Name = txtName.Text;
                newUser.Gender = (User.eGender)Convert.ToInt32(dropGender.SelectedValue);
                newUser.Birthdate = datePicker1.SelectedDate;
                newUser.LanguageId = LanguageId;
                if (newUser.Gender == Classes.User.eGender.Couple)
                {
                    newUser.Birthdate2 = datePicker2.SelectedDate;
                }

                if (Config.Users.InterestedInFieldEnabled)
                {
                    newUser.InterestedIn = (User.eGender)Convert.ToInt32(dropInterestedIn.SelectedValue);
                }
                else
                {
                    if (Config.Users.DisableGenderInformation)
                        newUser.InterestedIn = Classes.User.eGender.Male;
                    else
                        newUser.InterestedIn = newUser.Gender == Classes.User.eGender.Male
                                                   ?
                                                       Classes.User.eGender.Female
                                                   : Classes.User.eGender.Male;
                }
                newUser.ReceiveEmails = Config.Users.EmailNotificationsDefault;

                #region Set and Delete invitedBy cookie

                if (Request.Cookies["invitedBy"] != null)
                {
                    newUser.InvitedBy = Server.HtmlEncode(Request.Cookies["invitedBy"].Value);

                    HttpCookie cookie = new HttpCookie("invitedBy");
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(cookie);
                }

                #endregion

                #region Set and Delete affiliateID cookie

                if (Request.Cookies["affiliateID"] != null)
                {
                    newUser.AffiliateID = Convert.ToInt32(Server.HtmlEncode(Request.Cookies["affiliateID"].Value));

                    HttpCookie cookie = new HttpCookie("affiliateID");
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(cookie);
                }

                #endregion

                newUser.Create(Request.UserHostAddress);

                if (Config.Users.SmsConfirmationRequired)
                {
                    Response.Redirect("~/SmsConfirm.aspx?username="******"Home.aspx");
                    Response.Redirect("ManageProfile.aspx");
                }
                else
                    StatusPageMessage = Lang.Trans
                        ("<b>Your account has been created successfully!</b><br><br>"
                         + "You will receive a confirmation e-mail shortly. In order "
                         + "to finish your registration you'll have to click the "
                         + "activation link in the e-mail.");
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (ArgumentException err)
            {
                lblError.Text = err.Message;
                return;
            }
            catch (Exception err)
            {
                lblError.Text = Lang.Trans
                    ("Unknown error has occured while trying to create "
                     + "your account! Please try again later.");
                Log(err);
                return;
            }
            Response.Redirect("Default.aspx");
        }
예제 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                string username = Request.Params["username"];
                string guid = Request.Params["guid"];

                if (username != null)
                {
                    User user;
                    try
                    {
                        user = Classes.User.Load(username);
                    }
                    catch (NotFoundException)
                    {
                        StatusPageMessage =
                            Lang.Trans(
                                "Your registration has expired! Please register and create your account again.<br><br>");
                        Response.Redirect("Registr.aspx");
                        return;
                    }
                    if (Classes.User.IsValidPendingGuid(username, guid))
                    {
                        user.Active = true;
                        user.Update();

                        if (Config.Users.SendWelcomeMessage)
                        {
                            Message.SendWelcomeMessage(user);
                        }

                        Classes.User.RemovePendingGuids(guid, username);

                        StatusPageMessage = Lang.Trans("<b>Your registration has been confirmed!</b><br>" +
                                                       "Please click on the link below to edit your profile.<br><br>");

                        //NameValueCollection link = new NameValueCollection();
                        //link.Add(Config.Urls.Home + "/ManageProfile.aspx", Config.Urls.Home + "/ManageProfile.aspx");
                        //StatusPageLink = link;
                        ((PageBase)Page).StatusPageLinkSkindId = "";
                        ((PageBase)Page).StatusPageLinkText = Config.Urls.Home + "/ManageProfile.aspx";
                        ((PageBase)Page).StatusPageLinkURL = Config.Urls.Home + "/ManageProfile.aspx";

                        UserSession userSession = null;
                        try
                        {
                            userSession = new UserSession(username);
                            userSession.Authorize(Session.SessionID);
                            ((PageBase)Page).CurrentUserSession = userSession;

                            #region Autojoin to group

                            Group[] autojoinGroups = Group.Fetch(true);

                            if (autojoinGroups.Length > 0)
                            {
                                var groups =
                                    autojoinGroups.Where(
                                        g => g.Approved &&
                                        (g.AutojoinCountry == null || g.AutojoinCountry == userSession.Country) &&
                                        (g.AutojoinRegion == null || g.AutojoinRegion == userSession.State) &&
                                        (g.AutojoinCity == null || g.AutojoinCity == userSession.City));
                                foreach (Group group in groups)
                                {
                                    GroupMember groupMember = new GroupMember(group.ID, userSession.Username);
                                    groupMember.Active = true;
                                    groupMember.Type = GroupMember.eType.Member;
                                    groupMember.Save();
                                    group.ActiveMembers++;
                                    group.Save();
                                }
                            }

                            #endregion
                        }
                        catch (Exception err)
                        {
                            StatusPageMessage = err.Message;
                        }

                        Response.Redirect("ShowStatus.aspx");
                    }
                    else
                    {
                        StatusPageMessage =
                            Lang.Trans(
                                "<b>Your account is already confirmed or the provided confirmation URL is wrong</b><br><br>");
                        Response.Redirect("ShowStatus.aspx");
                    }
                }
            }
        }
예제 #11
0
        private void isRememberMeActivated()
        {
            if (Request.Cookies["rememberMe"] != null)
            {
                string guid = Request.Cookies["rememberMe"].Value;
                string username = Classes.User.FetchUserByGuid(guid);
                Classes.User user = null;
                try
                {
                    user = Classes.User.Load(username);
                    UserSession userSession = new UserSession(user.Username);
                    if (!user.Active)
                    {
                        if (!user.SmsConfirmed && Config.Users.SmsConfirmationRequired)
                        {
                            throw new SmsNotConfirmedException
                                (Lang.Trans("This account is not yet SMS confirmed!"));
                        }

                        throw new AccessDeniedException
                            (Lang.Trans("This account is not yet activated!"));
                    }

                    if (user.Deleted)
                    {
                        if (user.DeleteReason == null || user.DeleteReason.Trim().Length == 0)
                            throw new AccessDeniedException
                                (Lang.Trans("This user has been deleted!"));

                        throw new AccessDeniedException
                            (String.Format(Lang.Trans("This user has been deleted ({0})"), user.DeleteReason));
                    }

                    ((PageBase)Page).CurrentUserSession = userSession;
                    MatchmakerHelper.CurrentUsername = userSession.Username;
                    userSession.Authorize(Session.SessionID);

                    
                    if (user.PrevLogin.Date != DateTime.Now.Date)
                        Classes.User.AddScore(user.Username, Config.UserScores.DailyLogin, "Login");

                    try
                    {
                        IPLogger.Log(user.Username, Request.UserHostAddress, IPLogger.ActionType.Login);
                    }
                    catch (Exception err)
                    {
                        Global.Logger.LogError("LoginBox IP Logger", err);
                    }
                }
                catch (NotFoundException err)
                {
                    StatusPageMessage = err.Message;
                    return;
                }
                catch (AccessDeniedException err)
                {
                    StatusPageMessage = err.Message;
                    return;
                }
                catch (SmsNotConfirmedException err)
                {
                    StatusPageMessage = err.Message;
                    Response.Redirect("SmsConfirm.aspx?username="******"back_url"]))
                {
                    Response.Redirect(Request.Params["back_url"]);
                    return;
                }
                else
                {
                    Response.Redirect("Home.aspx");
                    return;
                }
            }
        }