public GoogleAccessTokenResponse GetAccessTokenFromRefreshToken(string refreshToken) { // Declare the POST data NameValueCollection postData = new NameValueCollection { { "client_id", ClientIdFull }, { "client_secret", ClientSecret }, { "refresh_token", refreshToken }, { "grant_type", "refresh_token" } }; // Make a call to the server JsonObject json = SocialUtils.DoHttpPostRequestAndGetBodyAsJsonObject("https://accounts.google.com/o/oauth2/token", null, postData); // Check for an error message if (json.HasValue("error")) { throw new Exception(json.GetString("error")); } // Parse the JSON response return(GoogleAccessTokenResponse.Parse(json)); }
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["Dialogue_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } if (string.IsNullOrEmpty(Dialogue.Settings().GoogleClientId) || string.IsNullOrEmpty(Dialogue.Settings().GoogleClientSecret)) { 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 = Dialogue.Settings().GoogleClientId, ClientSecret = Dialogue.Settings().GoogleClientSecret, RedirectUri = ReturnUrl }; // Session expired? if (AuthState != null && Session["Dialogue_" + 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("Dialogue_" + 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["Dialogue_" + state] = new NameValueCollection { { "Callback", Callback}, { "ContentTypeAlias", ContentTypeAlias}, { "PropertyAlias", PropertyAlias}, { "Feature", Feature} }; // Declare the scope var scope = new[] { GoogleScope.OpenId, GoogleScope.Email, GoogleScope.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 = AppHelpers.UmbServices().MemberService.GetByEmail(user.Email); if (userExists != null) { // Update access token userExists.Properties[AppConstants.PropMemberGoogleAccessToken].Value = info.RefreshToken; AppHelpers.UmbServices().MemberService.Save(userExists); // Users already exists, so log them in FormsAuthentication.SetAuthCookie(userExists.Username, true); resultMessage.Message = Lang("Members.NowLoggedIn"); resultMessage.MessageType = GenericMessages.Success; } else { // Not registered already so register them var viewModel = new RegisterViewModel { Email = user.Email, LoginType = LoginType.Google, Password = AppHelpers.RandomString(8), UserName = user.Name, SocialProfileImageUrl = user.Picture, UserAccessToken = info.RefreshToken }; return RedirectToAction("MemberRegisterLogic", "DialogueLoginRegisterSurface", viewModel); } } } catch (Exception ex) { resultMessage.Message = string.Format("Unable to get user information<br/>{0}", ex.Message); resultMessage.MessageType = GenericMessages.Danger; } } ShowMessage(resultMessage); return RedirectToUmbracoPage(Dialogue.Settings().ForumId); }
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.Instance.GooglePlusAppId) || string.IsNullOrEmpty(SiteConstants.Instance.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.Instance.GooglePlusAppId, ClientSecret = SiteConstants.Instance.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 = $"Unable to acquire access token<br/>{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 = $"Unable to get user information<br/>{ex.Message}"; resultMessage.MessageType = GenericMessages.danger; LoggingService.Error(ex); } } ShowMessage(resultMessage); return RedirectToAction("LogOn", "Members"); }