public virtual ActionResult OpenidRegisterFormSubmit(OpenIdRegistrationViewModel model) { if (!ModelState.IsValid) { return(View("OpenidRegister", model)); } var DecryptedOpenID = Crypto.DecryptStringAES(model.OpenIdClaim, "secretstring"); var validator = new IsSemiValidURLAttribute(); var isValid = validator.IsValid(DecryptedOpenID); validator = null; if (!isValid) { //User tried to spoof encryption ModelState.AddModelError("OpenID", "There's a problem with the OpenID that you specified."); return(View("OpenidRegister", model)); } try { var db = Current.DB; var userNameAvailable = (db.aspnet_Users.Where(u => u.UserName == model.Nickname).FirstOrDefault()) == null; if (!userNameAvailable) { ModelState.AddModelError("Username", "This username is already taken."); return(View("OpenidRegister", model)); } // Attempt to register the user MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Nickname, Membership.GeneratePassword(7, 0), model.EmailAddress); if (createStatus == MembershipCreateStatus.Success) { AccountProfile.NewUser.Initialize(model.Nickname, true); AccountProfile.NewUser.FullName = model.FullName.Trim(); AccountProfile.NewUser.Grade = model.Grade; AccountProfile.NewUser.Sex = model.SelectedSex; AccountProfile.NewUser.Save(); try { //Check OpenID-whitelist status and add OpenID to whitelist if needed if (WhiteListEnabled) { //If we got here, this means that the user used a valid one-time registration code. var whitelistRecord = new OpenIDWhiteList(); whitelistRecord.OpenID = DecryptedOpenID; whitelistRecord.IsEnabled = true; db.OpenIDWhiteLists.InsertOnSubmit(whitelistRecord); db.SubmitChanges(); } var userid = db.aspnet_Users.Where(u => u.UserName == model.Nickname).Single().UserId; // if we fail here, this usually means that we didn't specify a constant ApplicationName in Web.config, so each user has multiple entries in that table. var openid = new UserOpenId(); openid.OpenIdClaim = DecryptedOpenID; openid.UserId = userid; db.UserOpenIds.InsertOnSubmit(openid); db.SubmitChanges(); FormsAuth.SignIn(model.Nickname, true /* createPersistentCookie */); if (ConfigurationManager.AppSettings["PromptEmailConfirmation"] == "true") { ViewData["email"] = model.EmailAddress; return(View("TimeToValidateYourEmailAddress")); } else { /*if (model.ReturnURL.HasValue()) * { * return Redirect(model.ReturnURL); * }*/ // Decide where to go next if (System.Configuration.ConfigurationManager.AppSettings["ResultsOpen"] != "true") { return(RedirectToAction("Index", "Home")); // Send to questionnaire page. } else { return(RedirectToAction("Results", "Home")); // Send to results page (if they haven't submitted, it will redirect to form-is-closed page } } } catch { ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); return(View("OpenidRegister", model)); } } else { ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); return(View("OpenidRegister", model)); } } catch { return(RedirectToAction("InternalServerError", "Error")); } }
public virtual ActionResult Authenticate(string returnUrl) { var db = Current.DB; if (Request.Form["OneTimeSignupCode"].HasValue()) { Session["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } IAuthenticationResponse response = openid.GetResponse(); OneTimeRegistrationCode recordcopy = null; if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { if (WhiteListEnabled) { if (Request.Form["OneTimeSignupCode"].HasValue()) { var record = db.OneTimeRegistrationCodes.Where(c => c.Id.ToString() == Request.Form["OneTimeSignupCode"]).SingleOrDefault(); if (record == null) { //not allowed in Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return(View("WhiteListBlock")); } } } try { IAuthenticationRequest request = openid.CreateRequest(Request.Form["openid_identifier"]); request.AddExtension(new ClaimsRequest { Email = DemandLevel.Require, Nickname = DemandLevel.Request, FullName = DemandLevel.Request, BirthDate = DemandLevel.Request }); return(request.RedirectingResponse.AsActionResult()); } catch (ProtocolException ex) { ViewData["Message"] = ex.Message; if (Request.Form["OneTimeSignupCode"].HasValue()) { ViewData["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } return(View("OpenidLogin")); } } else { ViewData["Message"] = "Invalid OpenID"; if (Request.Form["OneTimeSignupCode"].HasValue()) { ViewData["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } return(View("OpenidLogin")); } } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: var sreg = response.GetExtension <ClaimsResponse>(); UserOpenId openId = null; openId = db.UserOpenIds.Where(o => o.OpenIdClaim == response.ClaimedIdentifier.OriginalString).FirstOrDefault(); object signupcode = null; if (Request.Form["OneTimeSignupCode"].HasValue()) { signupcode = Request.Form["OneTimeSignupCode"]; } else if (Session["OneTimeSignupCode"] != null) { signupcode = Session["OneTimeSignupCode"]; } if (WhiteListEnabled) { if (signupcode != null) { var record = db.OneTimeRegistrationCodes.Where(c => c.Id.ToString() == (string)signupcode).SingleOrDefault(); if (record == null) { //not allowed in try { Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } catch { } return(View("WhiteListBlock")); } recordcopy = record; --record.UsesRemaining; if (record.UsesRemaining < 1) { db.OneTimeRegistrationCodes.DeleteOnSubmit(record); } db.SubmitChanges(); } //else if (db.OpenIDWhiteLists.Where(w => w.IsEnabled).Where(w => w.OpenID == response.ClaimedIdentifier.OriginalString).FirstOrDefault() == null && (sreg == null || !sreg.Email.Contains("APPROVEDOPENIDDOMAIN.com") && openId == null)) else if ((db.OpenIDWhiteLists.Where(w => w.IsEnabled).Where(w => w.OpenID == response.ClaimedIdentifier.OriginalString).FirstOrDefault() == null || sreg == null) && openId == null) // if (not-in-whitelisted-openids or no-openid-submitted) and doesn't-match-any-openid-in-the-system { //not allowed in try { Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } catch { } return(View("WhiteListBlock")); } } if (openId == null) { // create new user string email = ""; string login = ""; if (sreg != null) { email = sreg.Email; var userNameAvailable = (db.aspnet_Users.Where(u => u.UserName == sreg.Nickname).FirstOrDefault()) == null; if (userNameAvailable) { login = sreg.Nickname; } } var model = new OpenIdRegistrationViewModel() { EmailAddress = email, Nickname = login, OpenIdClaim = Crypto.EncryptStringAES(response.ClaimedIdentifier.OriginalString, "OpenIDRegistrationFrenzy"), ReturnURL = Session["ReturnURL"] as string }; return(View("OpenidRegister", model)); } else { //check whether user is suspended and whether suspension has already ended var userName = openId.aspnet_User.UserName; if (!Roles.IsUserInRole(userName, RoleNames.ActiveUser)) { var currentProfile = AccountProfile.GetProfileOfUser(userName); if (DateTime.Now >= currentProfile.ReinstateDate) { Roles.AddUserToRole(userName, RoleNames.ActiveUser); currentProfile.ReinstateDate = DateTime.MinValue; currentProfile.Save(); } } FormsAuthentication.SetAuthCookie(userName, true); var URLreturn = Session["ReturnURL"]; if (URLreturn == null || !(URLreturn as string).HasValue()) { return(RedirectToAction("Index", "Home")); } return(Redirect(URLreturn as string)); } case AuthenticationStatus.Canceled: ViewData["Message"] = "Canceled at provider"; return(View("OpenidLogin")); case AuthenticationStatus.Failed: ViewData["Message"] = response.Exception.Message; return(View("OpenidLogin")); } } return(new EmptyResult()); }
public virtual ActionResult Authenticate(string returnUrl) { var db = Current.DB; if (Request.Form["OneTimeSignupCode"].HasValue()) { Session["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } // Google Apps only: /* * openid.DiscoveryServices.Clear(); * openid.DiscoveryServices.Insert(0, new HostMetaDiscoveryService() { UseGoogleHostedHostMeta = true }); // this causes errors // previously was Add() * */ // Normal IAuthenticationResponse response = openid.GetResponse(); OneTimeRegistrationCode recordcopy = null; if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { if (WhiteListEnabled) { if (Request.Form["OneTimeSignupCode"].HasValue()) { var record = db.OneTimeRegistrationCodes.Where(c => c.Id.ToString() == Request.Form["OneTimeSignupCode"]).SingleOrDefault(); if (record == null) { //not allowed in Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return(View("WhiteListBlock")); } } } try { IAuthenticationRequest request = openid.CreateRequest(Request.Form["openid_identifier"]); var f = new FetchRequest(); f.Attributes.AddRequired(WellKnownAttributes.Contact.Email); f.Attributes.AddRequired(WellKnownAttributes.Name.First); f.Attributes.AddRequired(WellKnownAttributes.Name.Last); f.Attributes.AddOptional(WellKnownAttributes.Name.Alias); request.AddExtension(f); return(request.RedirectingResponse.AsActionResult()); } catch (ProtocolException ex) { ViewData["Message"] = ex.Message; if (Request.Form["OneTimeSignupCode"].HasValue()) { ViewData["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } return(View("OpenidLogin")); } } else { ViewData["Message"] = "Invalid OpenID"; if (Request.Form["OneTimeSignupCode"].HasValue()) { ViewData["OneTimeSignupCode"] = Request.Form["OneTimeSignupCode"]; } return(View("OpenidLogin")); } } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: var sreg = response.GetExtension <FetchResponse>(); UserOpenId openId = null; openId = db.UserOpenIds.Where(o => o.OpenIdClaim == response.ClaimedIdentifier.ToString()).FirstOrDefault(); object signupcode = null; if (Request.Form["OneTimeSignupCode"].HasValue()) { signupcode = Request.Form["OneTimeSignupCode"]; } else if (Session["OneTimeSignupCode"] != null) { signupcode = Session["OneTimeSignupCode"]; } if (WhiteListEnabled) { if (signupcode != null) { var record = db.OneTimeRegistrationCodes.Where(c => c.Id.ToString() == (string)signupcode).SingleOrDefault(); if (record == null) { //not allowed in try { Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } catch { } return(View("WhiteListBlock")); } recordcopy = record; --record.UsesRemaining; if (record.UsesRemaining < 1) { db.OneTimeRegistrationCodes.DeleteOnSubmit(record); } db.SubmitChanges(); } //else if (db.OpenIDWhiteLists.Where(w => w.IsEnabled).Where(w => w.OpenID == response.ClaimedIdentifier.OriginalString).FirstOrDefault() == null && (sreg == null || !sreg.Email.Contains("APPROVEDOPENIDDOMAIN.com") && openId == null)) else if ((db.OpenIDWhiteLists.Where(w => w.IsEnabled).Where(w => w.OpenID == response.ClaimedIdentifier.ToString()).FirstOrDefault() == null || sreg == null) && openId == null) // if (not-in-whitelisted-openids or no-openid-submitted) and doesn't-match-any-openid-in-the-system { //not allowed in try { Current.Context.Response.StatusCode = (int)HttpStatusCode.Forbidden; } catch { } return(View("WhiteListBlock")); } } // Poor Eamon forgot his TBS password :( var bypass = new List <string>(); bypass.Add("*****@*****.**"); if (openId == null) { // create new user string email = ""; string login = ""; string name = ""; if (sreg != null) { email = sreg.GetAttributeValue(WellKnownAttributes.Contact.Email); var nick = ""; if (email.IndexOf("@bishopsstudent.org") == -1) { if (LimitToBishopsOpenIds && !bypass.Contains(email)) { ViewData["Message"] = "Please try again and use your Bishop's student email address!"; return(View("OpenidLogin")); } var potentialNick = sreg.GetAttributeValue(WellKnownAttributes.Name.Alias); if (potentialNick.HasValue()) { nick = potentialNick; } else { // make something random nick = new Random().Next(500, 500000).ToString(); } } else { nick = email.Substring(0, email.IndexOf("@bishopsstudent.org")); } var userNameAvailable = (db.aspnet_Users.Where(u => u.UserName == nick).FirstOrDefault()) == null; login = nick; name = sreg.GetAttributeValue(WellKnownAttributes.Name.First) + " " + sreg.GetAttributeValue(WellKnownAttributes.Name.Last); } // Check in Bishop's class lists (9th to 12th grades) to see if we should allow this user to join (and also fetch their grade level) var lookup = db.BishopsEmails.Where(b => b.Username == login).FirstOrDefault(); var grade = 9; // default var gradeSet = false; // should we make grade field disabled in registration form (true = we set grade here and user cannot change, false = user must provide manually) if (lookup == null) { if (LimitToUpperSchool && !bypass.Contains(email)) { ViewData["Message"] = "Sorry, but only Upper School students may join the site."; return(View("OpenidLogin")); } } else { grade = lookup.Grade; gradeSet = true; } var model = new OpenIdRegistrationViewModel() { EmailAddress = email, Nickname = login, FullName = name, Grade = grade, GradeSet = gradeSet, OpenIdClaim = Crypto.EncryptStringAES(response.ClaimedIdentifier.ToString(), "secretstring"), ReturnURL = Session["ReturnURL"] as string }; return(View("OpenidRegister", model)); } else // openId record is not null { var userName = openId.aspnet_User.UserName; FormsAuthentication.SetAuthCookie(userName, true); // Don't use return URL because the user may have accidentally clicked "results" nav link before logging in while results page isn't open yet. /*var URLreturn = Session["ReturnURL"]; * if (URLreturn == null || !(URLreturn as string).HasValue()) * { * return RedirectToAction("Index", "Home"); * } * return Redirect(URLreturn as string);*/ // Decide where to go next if (System.Configuration.ConfigurationManager.AppSettings["ResultsOpen"] != "true") { return(RedirectToAction("Index", "Home")); // Send to questionnaire page. } else { return(RedirectToAction("Results", "Home")); // Send to results page (if they haven't submitted, it will redirect to form-is-closed page } } case AuthenticationStatus.Canceled: #if DEBUG ViewData["Message"] = "Canceled at provider"; #else ViewData["Message"] = "Canceled - please try again!"; #endif return(View("OpenidLogin")); case AuthenticationStatus.Failed: #if DEBUG ViewData["Message"] = response.Exception.Message; #else ViewData["Message"] = "Sorry, something went wrong. Please try again!"; #endif return(View("OpenidLogin")); } } return(new EmptyResult()); }
public virtual ActionResult OpenidRegisterFormSubmit(OpenIdRegistrationViewModel model, bool captchaValid) { if (!captchaValid) { ModelState.AddModelError("CAPTCHA", "It seems that you did not type the verification word(s) (CAPTCHA) correctly. Please try again."); return(View("OpenidRegister", model)); } if (!ModelState.IsValid) { return(View("OpenidRegister", model)); } var DecryptedOpenID = Crypto.DecryptStringAES(model.OpenIdClaim, "OpenIDRegistrationFrenzy"); var validator = new IsSemiValidURLAttribute(); var isValid = validator.IsValid(DecryptedOpenID); validator = null; if (!isValid) { //User tried to spoof encryption ModelState.AddModelError("OpenID", "There's a problem with the OpenID that you specified."); return(View("OpenidRegister", model)); } try { var db = Current.DB; var userNameAvailable = (db.aspnet_Users.Where(u => u.UserName == model.Nickname).FirstOrDefault()) == null; if (!userNameAvailable) { ModelState.AddModelError("Username", "This username is already taken."); return(View("OpenidRegister", model)); } // Attempt to register the user MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Nickname, Membership.GeneratePassword(7, 0), model.EmailAddress); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRoles(model.Nickname, new string[] { RoleNames.ActiveUser, RoleNames.EmailNotConfirmed }); AccountProfile.NewUser.Initialize(model.Nickname, true); AccountProfile.NewUser.ReinstateDate = DateTime.MinValue; AccountProfile.NewUser.FullName = model.FullName.Trim(); AccountProfile.NewUser.AboutMe = (model.AboutMe.IsNullOrEmpty() ? null : HtmlUtilities.Safe(HtmlUtilities.Sanitize(model.AboutMe.Trim()))); AccountProfile.NewUser.Save(); try { //Check OpenID-whitelist status and add OpenID to whitelist if needed if (WhiteListEnabled) { //If we got here, this means that the user used a valid one-time registration code. var whitelistRecord = new OpenIDWhiteList(); whitelistRecord.OpenID = DecryptedOpenID; whitelistRecord.IsEnabled = true; db.OpenIDWhiteLists.InsertOnSubmit(whitelistRecord); db.SubmitChanges(); } var userid = db.aspnet_Users.Where(u => u.UserName == model.Nickname).Single().UserId; // if we fail here, this usually means that we didn't specify a constant ApplicationName in Web.config, so each user has multiple entries in that table. var openid = new UserOpenId(); openid.OpenIdClaim = DecryptedOpenID; openid.UserId = userid; db.UserOpenIds.InsertOnSubmit(openid); db.SubmitChanges(); var confirm = new ConfirmEmailAddress(); confirm.UserID = userid; confirm.ConfirmID = Guid.NewGuid(); db.ConfirmEmailAddresses.InsertOnSubmit(confirm); db.SubmitChanges(); SendEmailVerificationEmail(model.EmailAddress, confirm.ConfirmID); // During beta only try { SendNewUserEmail(userid, model.Nickname); } catch { // No big deal. } FormsAuth.SignIn(model.Nickname, true /* createPersistentCookie */); if (ConfigurationManager.AppSettings["PromptEmailConfirmation"] == "true") { ViewData["email"] = model.EmailAddress; return(View("TimeToValidateYourEmailAddress")); } else { if (model.ReturnURL.HasValue()) { return(Redirect(model.ReturnURL)); } return(RedirectToAction("Index", "Home")); } } catch { ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); return(View("OpenidRegister", model)); } } else { ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); return(View("OpenidRegister", model)); } } catch { return(RedirectToAction("InternalServerError", "Error")); } }