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 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()); }