internal YouTubeHttpClient(GoogleOAuthClient client) : base(client) { Channels = new YouTubeChannelsRawEndpoint(client); Playlists = new YouTubePlaylistsRawEndpoint(client); PlaylistItems = new YouTubePlaylistItemsRawEndpoint(client); Videos = new YouTubeVideosRawEndpoint(client); }
/// <summary> /// The entry point of the application. /// </summary> /// <param name="args">Command line arguments.</param> /// <returns>The asynchronous operation task.</returns> public static async Task Main(string[] args) { // https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthConsoleApp var auth = new GoogleOAuthClient(); var token = await auth.PerformAuthentication(); var api = new GooglePhotosLibraryClient(new ApiClient()); // var albums = await api.GetAlbums(token); // var album = await api.CreateAlbum("Test1", token); var photoMetas = new List <PhotoMeta>() { new PhotoMeta( File.ReadAllBytes( @"C:\Users\hardy\Pictures\Flickr\flickr-downloadr-[2015 Turkey - Sumela monastery]-2018-11-05_21-36-46\23738517934.jpg"), "23738517934.jpg") { Title = "Sumela monastery", Description = "Sumela monastery description", Location = new GeoCoordinate(40.690229m, 39.657554m) } }; await api.UploadPhotosToAlbum("Test1", photoMetas, token); // Console.WriteLine($"Hello World! {album}"); }
internal IHttpQueryString GetQueryString(GoogleOAuthClient client) { // Validate the required parameters and properties if (client == null) { throw new ArgumentNullException(nameof(client)); } if (string.IsNullOrWhiteSpace(State)) { throw new PropertyNotSetException(nameof(State)); } if (string.IsNullOrWhiteSpace(client.ClientId)) { throw new PropertyNotSetException(nameof(client.ClientId)); } if (string.IsNullOrWhiteSpace(client.RedirectUri)) { throw new PropertyNotSetException(nameof(client.RedirectUri)); } // Generate the query string IHttpQueryString query = new HttpQueryString(); query.Add("response_type", "code"); query.Add("client_id", client.ClientId); query.Add("access_type", StringUtils.ToUnderscore(AccessType)); query.Add("prompt", ToString(Prompt)); query.Add("scope", Scope + string.Empty); query.Add("redirect_uri", client.RedirectUri); query.Add("state", State); return(query); }
/// <summary> /// Returns the <see cref="PlacesHttpClient"/> of the specified Google OAuth <paramref name="client"/>. /// </summary> /// <param name="client">The Google OAuth client.</param> /// <returns>An instance of <see cref="PlacesHttpClient"/>.</returns> /// <remarks> /// The <see cref="PlacesHttpClient"/> instance keeps an internal registry ensuring that calling this method /// multiple times for the same <paramref name="client"/> will result in the same instance of /// <see cref="PlacesHttpClient"/>. /// /// Specifically the <see cref="PlacesHttpClient"/> instance will be created the first time this method is /// called, while any subsequent calls to this method will result in the instance saved registry being /// returned. /// </remarks> public static PlacesHttpClient Places(this GoogleOAuthClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } return(client.GetApiClient(() => new PlacesHttpClient(client))); }
/// <summary> /// Gets a reference to the YouTube HTTP client. /// </summary> /// <param name="client">The Google OAuth client instance.</param> /// <returns>An instance of <see cref="YouTubeHttpClient"/>.</returns> public static YouTubeHttpClient YouTube(this GoogleOAuthClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } return(client.GetHttpClient(() => new YouTubeHttpClient(client))); }
/// <summary> /// Returns the <see cref="GeocodingHttpClient"/> of the specified Google OAuth <paramref name="client"/>. /// </summary> /// <param name="client">The Google OAuth client.</param> /// <returns>An instance of <see cref="GeocodingHttpClient"/>.</returns> /// <remarks> /// The <see cref="GeocodingHttpClient"/> instance keeps an internal registry ensuring that calling this method /// multiple times for the same <paramref name="client"/> will result in the same instance of /// <see cref="GeocodingHttpClient"/>. /// /// Specifically the <see cref="GeocodingHttpClient"/> instance will be created the first time this method is /// called, while any subsequent calls to this method will result in the instance saved registry being /// returned. /// </remarks> public static GeocodingHttpClient Geocoding(this GoogleOAuthClient client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } return(client.GetApiClient(() => new GeocodingHttpClient(client))); }
/// <summary> /// Initializes a new instance based on the specified OAuth client. The /// OAuth client must have an access token. Calling this method will /// not make any calls to the Google Accounts API. /// </summary> /// <param name="client">The OAuth client.</param> public static GoogleService CreateFromOAuthClient(GoogleOAuthClient client) { if (String.IsNullOrWhiteSpace(client.AccessToken)) { throw new ArgumentException("An access token must be present in the OAuth Client"); } return(new GoogleService { Client = client }); }
public GoogleCalendarManager( IMapper mapper, UserManager userManager, GoogleOAuthClient googleAuthClient, GoogleCalendarClient googleCalendarClient) { this.mapper = Throw.IfNull(mapper, nameof(mapper)); this.userManager = Throw.IfNull(userManager, nameof(userManager)); this.googleAuthClient = Throw.IfNull(googleAuthClient, nameof(googleAuthClient)); this.googleCalendarClient = Throw.IfNull(googleCalendarClient, nameof(googleCalendarClient)); }
/// <summary> /// Tries to login with Google Auth /// </summary> public void Login() { string code = Request.QueryString["code"]; string error = Request.QueryString["error"]; string baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"]; GoogleOAuthClient oauth = new GoogleOAuthClient { ClientId = "clientId", ClientSecret = "clientSecret", RedirectUri = baseUrl + "/umbraco/surface/auth/login" }; // Handle if an error occurs during the Google authentication (eg. if the user cancels the login) if (!String.IsNullOrWhiteSpace(error)) { return; } // Handle the state when the user is redirected back to our page after a successful login with the Google API if (!String.IsNullOrWhiteSpace(code)) { MemberServiceController memberService = new MemberServiceController(); // Exchange the authorization code for an access token GoogleAccessTokenResponse response = oauth.GetAccessTokenFromAuthorizationCode(code); string accessToken = response.AccessToken; // Initialize a new instance of the GoogleService class so we can make calls to the API GoogleService service = GoogleService.CreateFromAccessToken(accessToken); // Make a call to the API to get information about the authenticated user GoogleUserInfo user = service.GetUserInfo(); //Checks whether the user is logging in with a emakina account if (memberService.CreateNewMember(user.GivenName, user.FamilyName, user.Email, user.Id, user.Picture)) { FormsAuthentication.SetAuthCookie("google_" + user.Id, false); Response.Redirect("/"); } else { return; } } else { string redirect = (Request.QueryString["redirect"] ?? "/"); // Set the state (a unique/random value) string state = Guid.NewGuid().ToString(); Session["Google_" + state] = redirect; // Construct the authorization URL string authorizationUrl = oauth.GetAuthorizationUrl(state, GoogleScopes.Email + GoogleScopes.Profile, GoogleAccessType.Online, GoogleApprovalPrompt.Force); // Redirect the user to the OAuth dialog Response.Redirect(authorizationUrl); } }
public override ClaimsIdentity ProcessSignInResponse(string realm, string originalUrl, HttpContextBase httpContext) { var client = new GoogleOAuthClient(_clientId, _clientSecret); AuthenticationResult result; try { result = client.VerifyAuthentication(httpContext, this.MultiProtocolIssuer.ReplyUrl); } catch (WebException wex) { throw new InvalidOperationException(new StreamReader(wex.Response.GetResponseStream()).ReadToEnd(), wex); } var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, result.ExtraData["email"]) }; return(new ClaimsIdentity(claims, "Google")); }
/// <summary> /// Initializes a new instance based on the specified refresh token. /// The refresh token is used for making a call to the Google Accounts /// API to get a new access token. Access tokens typically expire after /// an hour (3600 seconds). /// </summary> /// <param name="clientId">The client ID.</param> /// <param name="clientSecret">The client secret.</param> /// <param name="refreshToken">The refresh token of the user.</param> public static GoogleService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken) { // Validation if (String.IsNullOrWhiteSpace(clientId)) { throw new ArgumentException("Parameter \"clientId\" cannot be NULL or empty", "clientId"); } if (String.IsNullOrWhiteSpace(clientSecret)) { throw new ArgumentException("Parameter \"clientSecret\" cannot be NULL or empty", "clientSecret"); } if (String.IsNullOrWhiteSpace(refreshToken)) { throw new ArgumentException("Parameter \"refreshToken\" cannot be NULL or empty", "refreshToken"); } // Partial client ID? if (!clientId.EndsWith(".apps.googleusercontent.com")) { clientId = clientId + ".apps.googleusercontent.com"; } // Initialize a new OAuth client with the specified client id and client secret GoogleOAuthClient client = new GoogleOAuthClient { ClientId = clientId, ClientSecret = clientSecret }; // Get a new access token from the specified request token GoogleAccessTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken); // Set the access token on the client client.AccessToken = response.AccessToken; // Initialize a new GoogleService instance based on the OAuth client return(new GoogleService { Client = client }); }
internal AnalyticsRawEndpoint(GoogleOAuthClient client) { Client = client; }
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 YouTubeRawEndpoint(GoogleOAuthClient client) { Client = client; }
internal YouTubeChannelsRawEndpoint(GoogleOAuthClient client) : base(client) { }
/// <summary> /// Initializes a new instance based on the specified Google OAuth <paramref name="client"/>. /// </summary> /// <param name="client">The Google OAuth client to be used.</param> public PlacesHttpClient(GoogleOAuthClient client) : base(client) { }
internal YouTubePlaylistsRawEndpoint(GoogleOAuthClient client) : base(client) { }
public virtual 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.IsNullOrWhiteSpace(ForumConfiguration.Instance.GooglePlusAppId) || string.IsNullOrWhiteSpace(ForumConfiguration.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 = ForumConfiguration.Instance.GooglePlusAppId, ClientSecret = ForumConfiguration.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(); 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")); } // 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[Constants.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")); }
protected void Page_Load(object sender, EventArgs e) { Title = "Google OAuth"; Callback = Request.QueryString["callback"]; ContentTypeAlias = Request.QueryString["contentTypeAlias"]; PropertyAlias = Request.QueryString["propertyAlias"]; Feature = Request.QueryString["feature"]; if (AuthState != null) { NameValueCollection stateValue = Session["Skybrud.Social_" + AuthState] as NameValueCollection; if (stateValue != null) { Callback = stateValue["Callback"]; ContentTypeAlias = stateValue["ContentTypeAlias"]; PropertyAlias = stateValue["PropertyAlias"]; Feature = stateValue["Feature"]; } } // Get the prevalue options GoogleOAuthPreValueOptions options = GoogleOAuthPreValueOptions.Get(ContentTypeAlias, PropertyAlias); if (!options.IsValid) { Content.Text += "Hold on now! The options of the underlying prevalue editor isn't valid."; return; } // Configure the OAuth client based on the options of the prevalue options GoogleOAuthClient client = new GoogleOAuthClient { ClientId = options.ClientId, ClientSecret = options.ClientSecret, RedirectUri = options.RedirectUri }; // Session expired? if (AuthState != null && Session["Skybrud.Social_" + AuthState] == null) { Content.Text = "<div class=\"error\">Session expired?</div>"; return; } // Check whether an error response was received from Google if (AuthError != null) { Content.Text = "<div class=\"error\">Error: " + AuthErrorDescription + "</div>"; if (AuthState != null) { Session.Remove("Skybrud.Social:" + AuthState); } return; } string state; // Redirect the user to the Google login dialog if (AuthCode == null) { // Generate a new unique/random state state = Guid.NewGuid().ToString(); // Save the state in the current user session Session["Skybrud.Social_" + state] = new NameValueCollection { { "Callback", Callback }, { "ContentTypeAlias", ContentTypeAlias }, { "PropertyAlias", PropertyAlias }, { "Feature", Feature } }; // Declare the scope GoogleScopeCollection defaultScope = new[] { GoogleScope.OpenId, GoogleScope.Email, GoogleScope.Profile }; string scope = options.Scope != null?string.Join(" ", options.Scope) : defaultScope.ToString(); // Construct the authorization URL string url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force); // Redirect the user Response.Redirect(url); return; } GoogleAccessTokenResponse info; try { info = client.GetAccessTokenFromAuthorizationCode(AuthCode); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to acquire access token</b><br />" + ex.Message + "</div>"; return; } try { // Initialize the Google service GoogleService service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken); // Get information about the authenticated user GoogleUserInfo user = service.GetUserInfo(); Content.Text += "<p>Hi <strong>" + user.Name + "</strong></p>"; Content.Text += "<p>Please wait while you're being redirected...</p>"; // Set the callback data GoogleOAuthData data = new GoogleOAuthData { Id = user.Id, Name = user.Name, Avatar = user.Picture, ClientId = client.ClientIdFull, ClientSecret = client.ClientSecret, RefreshToken = info.RefreshToken }; // Update the UI and close the popup window Page.ClientScript.RegisterClientScriptBlock(GetType(), "callback", String.Format( "self.opener." + Callback + "({0}); window.close();", data.Serialize() ), true); } catch (Exception ex) { Content.Text = "<div class=\"error\"><b>Unable to get user information</b><br />" + ex.Message + "</div>"; return; } }
public AnalyticsHttpClient(GoogleOAuthClient client) : base(client) { Data = new AnalyticsDataRawEndpoint(this); Management = new AnalyticsManagementRawEndpoint(this); }
internal YouTubeVideosRawEndpoint(GoogleOAuthClient client) : base(client) { }
/// <summary> /// Initializes a new instance based on the specified OAuth <paramref name="client"/>. /// </summary> /// <param name="client">An instance of <see cref="GoogleOAuthClient"/>.</param> protected YouTubeRawEndpointBase(GoogleOAuthClient client) { Client = client; }
public override void ProcessSignInRequest(Scope scope, HttpContextBase httpContext) { var client = new GoogleOAuthClient(_clientId, _clientSecret); client.RequestAuthentication(httpContext, MultiProtocolIssuer.ReplyUrl); }
/// <summary> /// Initializes a new instance based on the specified Google OAuth <paramref name="client"/>. /// </summary> /// <param name="client">The Google OAuth client to be used.</param> public GeocodingHttpClient(GoogleOAuthClient client) : base(client) { }
/// <summary> /// Initializes a new instance based on the specified <paramref name="client"/>. /// </summary> /// <param name="client">The parent Google client.</param> protected GoogleHttpClientBase(GoogleOAuthClient client) { Client = client; }