public ActionResult Register(MemberAddViewModel userModel) { if (SettingsService.GetSettings().SuspendRegistration != true) { using (UnitOfWorkManager.NewUnitOfWork()) { // First see if there is a spam question and if so, the answer matches if (!string.IsNullOrEmpty(SettingsService.GetSettings().SpamQuestion)) { // There is a spam question, if answer is wrong return with error if (userModel.SpamAnswer == null || userModel.SpamAnswer.Trim() != SettingsService.GetSettings().SpamAnswer) { // POTENTIAL SPAMMER! ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.WrongAnswerRegistration")); return View(); } } // Secondly see if the email is banned if (_bannedEmailService.EmailIsBanned(userModel.Email)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.EmailIsBanned")); return View(); } } // Standard Login userModel.LoginType = LoginType.Standard; // Do the register logic return MemberRegisterLogic(userModel); } return RedirectToAction("Index", "Home"); }
public ActionResult MemberRegisterLogic(MemberAddViewModel userModel) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var userToSave = new MembershipUser { UserName = _bannedWordService.SanitiseBannedWords(userModel.UserName), Email = userModel.Email, Password = userModel.Password, IsApproved = userModel.IsApproved, Comment = userModel.Comment, }; var homeRedirect = false; // Now check settings, see if users need to be manually authorised // OR Does the user need to confirm their email var manuallyAuthoriseMembers = SettingsService.GetSettings().ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = SettingsService.GetSettings().NewMemberEmailConfirmation ?? false; if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded) { userToSave.IsApproved = false; } var createStatus = MembershipService.CreateUser(userToSave); if (createStatus != MembershipCreateStatus.Success) { ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus)); } else { // See if this is a social login and we have their profile pic if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl)) { // We have an image url - Need to save it to their profile var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl); // Set upload directory - Create if it doesn't exist var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.UploadFolderPath, userToSave.Id)); if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // Get the file name var fileName = Path.GetFileName(userModel.SocialProfileImageUrl); // Create a HttpPostedFileBase image from the C# Image using (var stream = new MemoryStream()) { // Microsoft doesn't give you a file extension - See if it has a file extension // Get the file extension var fileExtension = Path.GetExtension(fileName); if (string.IsNullOrEmpty(fileExtension)) { // no file extension so give it one fileName = string.Concat(fileName, ".jpg"); } image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName); // Upload the file var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService, true); // Don't throw error if problem saving avatar, just don't save it. if (uploadResult.UploadSuccessful) { userToSave.Avatar = uploadResult.UploadedFileName; } } } // Store access token for social media account in case we want to do anything with it if (userModel.LoginType == LoginType.Facebook) { userToSave.FacebookAccessToken = userModel.UserAccessToken; } if (userModel.LoginType == LoginType.Google) { userToSave.GoogleAccessToken = userModel.UserAccessToken; } if (userModel.LoginType == LoginType.Google) { userToSave.MicrosoftAccessToken = userModel.UserAccessToken; } // Set the view bag message here SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, userToSave); if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded) { homeRedirect = true; } try { // Only send the email if the admin is not manually authorising emails or it's pointless SendEmailConfirmationEmail(userToSave); unitOfWork.Commit(); if (homeRedirect) { if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/") && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\")) { return Redirect(userModel.ReturnUrl); } return RedirectToAction("Index", "Home", new { area = string.Empty }); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); FormsAuthentication.SignOut(); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } } return View("Register"); }
/// <summary> /// Add a new user /// </summary> /// <returns></returns> public ActionResult Register() { if (SettingsService.GetSettings().SuspendRegistration != true) { using (UnitOfWorkManager.NewUnitOfWork()) { var user = MembershipService.CreateEmptyUser(); // Populate empty viewmodel var viewModel = new MemberAddViewModel { UserName = user.UserName, Email = user.Email, Password = user.Password, IsApproved = user.IsApproved, Comment = user.Comment, AllRoles = RoleService.AllRoles() }; // See if a return url is present or not and add it var returnUrl = Request["ReturnUrl"]; if (!string.IsNullOrEmpty(returnUrl)) { viewModel.ReturnUrl = returnUrl; } return View(viewModel); } } return RedirectToAction("Index", "Home"); }
public ActionResult FacebookLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; if (AuthState != null) { var stateValue = Session["MVCForum_" + AuthState] as string[]; if (stateValue != null && stateValue.Length == 3) { Callback = stateValue[0]; ContentTypeAlias = stateValue[1]; PropertyAlias = stateValue[2]; } } // Get the prevalue options if (string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppId) || string.IsNullOrEmpty(SiteConstants.Instance.FacebookAppSecret)) { resultMessage.Message = "You need to add the Facebook app credentials"; resultMessage.MessageType = GenericMessages.danger; } else { // Settings valid move on // Configure the OAuth client based on the options of the prevalue options var client = new FacebookOAuthClient { AppId = SiteConstants.Instance.FacebookAppId, AppSecret = SiteConstants.Instance.FacebookAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["MVCForum_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Facebook if (AuthError != null) { Session.Remove("MVCForum_" + AuthState); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; } // Redirect the user to the Facebook login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = new[] { Callback, ContentTypeAlias, PropertyAlias }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, "public_profile", "email"); //"user_friends" // Redirect the user return Redirect(url); } // Exchange the authorization code for a user access token var userAccessToken = string.Empty; try { userAccessToken = client.GetAccessTokenFromAuthCode(AuthCode); } catch (Exception ex) { resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } try { if (string.IsNullOrEmpty(resultMessage.Message)) { // Initialize the Facebook service (no calls are made here) var service = FacebookService.CreateFromAccessToken(userAccessToken); // Declare the options for the call to the API var options = new FacebookGetUserOptions { Identifier = "me", Fields = new[] { "id", "name", "email", "first_name", "last_name", "gender" } }; var user = service.Users.GetUser(options); // Try to get the email - Some FB accounts have protected passwords var email = user.Body.Email; if (string.IsNullOrEmpty(email)) { resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress"); resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } // First see if this user has registered already - Use email address using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(email); if (userExists != null) { try { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } catch (Exception ex) { LoggingService.Error(ex); } } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = email, LoginType = LoginType.Facebook, Password = StringUtils.RandomString(8), UserName = user.Body.Name, UserAccessToken = userAccessToken }; // Get the image and save it var getImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=square", user.Body.Id); viewModel.SocialProfileImageUrl = getImageUrl; //Large size photo https://graph.facebook.com/{facebookId}/picture?type=large //Medium size photo https://graph.facebook.com/{facebookId}/picture?type=normal //Small size photo https://graph.facebook.com/{facebookId}/picture?type=small //Square photo https://graph.facebook.com/{facebookId}/picture?type=square // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult MicrosoftLogin() { var resultMessage = new GenericMessageViewModel(); var input = new { Code = AuthCode, State = AuthState, Error = new { HasError = !String.IsNullOrWhiteSpace(AuthError), Text = AuthError, ErrorDescription = AuthErrorDescription } }; // Get the prevalue options if (string.IsNullOrEmpty(SiteConstants.MicrosoftAppId) || string.IsNullOrEmpty(SiteConstants.MicrosoftAppSecret)) { resultMessage.Message = "You need to add the Microsoft app credentials to the web.config"; resultMessage.MessageType = GenericMessages.danger; } else { var client = new MicrosoftOAuthClient { ClientId = SiteConstants.MicrosoftAppId, ClientSecret = SiteConstants.MicrosoftAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (input.State != null && Session["MVCForum_" + input.State] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Microsoft if (input.Error.HasError) { Session.Remove("MVCForum_" + input.State); resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; } // Redirect the user to the Microsoft login dialog if (string.IsNullOrWhiteSpace(input.Code)) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = "/"; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, WindowsLiveScopes.Emails + WindowsLiveScopes.Birthday); // Redirect the user return Redirect(url); } // Exchange the authorization code for an access token MicrosoftTokenResponse accessTokenResponse; try { Session.Remove("MVCForum_" + input.State); accessTokenResponse = client.GetAccessTokenFromAuthCode(input.Code); } catch (Exception ex) { accessTokenResponse = null; resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } try { if (string.IsNullOrEmpty(resultMessage.Message) || accessTokenResponse != null) { //MicrosoftScope debug = accessTokenResponse.Body.Scope.Items; //accessTokenResponse.Body.AccessToken //foreach (MicrosoftScope scope in accessTokenResponse.Body.Scope.Items) { // scope //} //accessTokenResponse.Response.Body // Initialize a new MicrosoftService so we can make calls to the API var service = MicrosoftService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken); // Make the call to the Windows Live API / endpoint var response = service.WindowsLive.GetSelf(); // Get a reference to the response body var user = response.Body; var getEmail = user.Emails != null && !string.IsNullOrWhiteSpace(user.Emails.Preferred); if (!getEmail) { resultMessage.Message = LocalizationService.GetResourceString("Members.UnableToGetEmailAddress"); resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Emails.Preferred); if (userExists != null) { try { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } catch (Exception ex) { LoggingService.Error(ex); } } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Emails.Preferred, LoginType = LoginType.Microsoft, Password = StringUtils.RandomString(8), UserName = user.Name, UserAccessToken = accessTokenResponse.Body.AccessToken, SocialProfileImageUrl = string.Format("https://apis.live.net/v5.0/{0}/picture", user.Id) }; //var uri = string.Concat("https://apis.live.net/v5.0/me?access_token=",viewModel.UserAccessToken); //using (var dl = new WebClient()) //{ // var profile = JObject.Parse(dl.DownloadString(uri)); // var pictureUrl = ; // if (!string.IsNullOrEmpty(pictureUrl)) // { // //viewModel.SocialProfileImageUrl = getImageUrl; // } //} // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } else { resultMessage.MessageType = GenericMessages.danger; ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult GoogleLogin() { var resultMessage = new GenericMessageViewModel(); Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { var stateValue = Session["MVCForum_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } if (string.IsNullOrEmpty(SiteConstants.GooglePlusAppId) || string.IsNullOrEmpty(SiteConstants.GooglePlusAppSecret)) { resultMessage.Message = "You need to add the Google app credentials"; resultMessage.MessageType = GenericMessages.danger; } else { // Configure the OAuth client based on the options of the prevalue options var client = new GoogleOAuthClient { ClientId = SiteConstants.GooglePlusAppId, ClientSecret = SiteConstants.GooglePlusAppSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["MVCForum_" + AuthState] == null) { resultMessage.Message = "Session Expired"; resultMessage.MessageType = GenericMessages.danger; } // Check whether an error response was received from Google if (AuthError != null) { resultMessage.Message = AuthErrorDescription; resultMessage.MessageType = GenericMessages.danger; if (AuthState != null) Session.Remove("MVCForum_" + AuthState); } // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state var state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["MVCForum_" + state] = new NameValueCollection { { "Callback", Callback}, { "ContentTypeAlias", ContentTypeAlias}, { "PropertyAlias", PropertyAlias}, { "Feature", Feature} }; // Declare the scope var scope = new[] { GoogleScopes.OpenId, GoogleScopes.Email, GoogleScopes.Profile }; // Construct the authorization URL var url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user return Redirect(url); } var info = new GoogleAccessTokenResponse(); try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { resultMessage.Message = string.Format("Unable to acquire access token<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } try { // Initialize the Google service var service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user var user = service.GetUserInfo(); using (UnitOfWorkManager.NewUnitOfWork()) { var userExists = MembershipService.GetUserByEmail(user.Email); if (userExists != null) { // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.UserName, true); resultMessage.Message = LocalizationService.GetResourceString("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.success; ShowMessage(resultMessage); return RedirectToAction("Index", "Home"); } else { // Not registered already so register them var viewModel = new MemberAddViewModel { Email = user.Email, LoginType = LoginType.Google, Password = StringUtils.RandomString(8), UserName = user.Name, SocialProfileImageUrl = user.Picture, UserAccessToken = info.RefreshToken }; // Store the viewModel in TempData - Which we'll use in the register logic TempData[AppConstants.MemberRegisterViewModel] = viewModel; return RedirectToAction("SocialLoginValidator", "Members"); } } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.danger; } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }
public ActionResult Register(MemberAddViewModel userModel) { if (SettingsService.GetSettings().SuspendRegistration != true) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { // First see if there is a spam question and if so, the answer matches if (!string.IsNullOrEmpty(SettingsService.GetSettings().SpamQuestion)) { // There is a spam question, if answer is wrong return with error if (userModel.SpamAnswer == null || userModel.SpamAnswer.Trim() != SettingsService.GetSettings().SpamAnswer) { // POTENTIAL SPAMMER! ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.WrongAnswerRegistration")); return View(); } } // Secondly see if the email is banned if (_bannedEmailService.EmailIsBanned(userModel.Email)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Error.EmailIsBanned")); return View(); } var userToSave = new MembershipUser { UserName = _bannedWordService.SanitiseBannedWords(userModel.UserName), Email = userModel.Email, Password = userModel.Password, IsApproved = userModel.IsApproved, Comment = userModel.Comment, }; var homeRedirect = false; // Now check settings, see if users need to be manually authorised // OR Does the user need to confirm their email var manuallyAuthoriseMembers = SettingsService.GetSettings().ManuallyAuthoriseNewMembers; var memberEmailAuthorisationNeeded = SettingsService.GetSettings().NewMemberEmailConfirmation ?? false; if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded) { userToSave.IsApproved = false; } var createStatus = MembershipService.CreateUser(userToSave); if (createStatus != MembershipCreateStatus.Success) { ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus)); } else { // Set the view bag message here SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, userToSave); if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded) { homeRedirect = true; } try { unitOfWork.Commit(); // Only send the email if the admin is not manually authorising emails or it's pointless SendEmailConfirmationEmail(userToSave); if (homeRedirect) { if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/") && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\")) { return Redirect(userModel.ReturnUrl); } return RedirectToAction("Index", "Home", new { area = string.Empty }); } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); FormsAuthentication.SignOut(); ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } } return View(); } } return RedirectToAction("Index", "Home"); }