public async Task<ActionResult> Index(CancellationToken cancellationToken, GmailFormModel email) { //return View(); var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); AuthorizationCodeMvcApp o = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()); if (result.Credential != null) { if (email.to != null) { BaseClientService.Initializer initializer = new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "ASP.NET MVC Sample5" }; var service = new GmailService(initializer); string fromEmail = "*****@*****.**"; //string fromName = @"AdamMorgan"; string fromName = ""; /// This code ss needed to extract signed in user info (email, display name) var gps = new PlusService(initializer); var me = gps.People.Get("me").Execute(); fromEmail = me.Emails.First().Value; //fromName = me.DisplayName; //////////////////////////////////////// MimeMessage message = new MimeMessage(); message.To.Add(new MailboxAddress("", email.to)); if (email.cc != null) message.Cc.Add(new MailboxAddress("", email.cc)); if (email.bcc != null) message.Bcc.Add(new MailboxAddress("", email.bcc)); if (email.subject != null) message.Subject = email.subject; var addr = new MailboxAddress(fromName, fromEmail); message.From.Add(addr); if (email.body != null) { message.Body = new TextPart("html") { Text = email.body }; } var ms = new MemoryStream(); message.WriteTo(ms); ms.Position = 0; StreamReader sr = new StreamReader(ms); Google.Apis.Gmail.v1.Data.Message msg = new Google.Apis.Gmail.v1.Data.Message(); string rawString = sr.ReadToEnd(); byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString); msg.Raw = System.Convert.ToBase64String(raw); var res = service.Users.Messages.Send(msg, "me").Execute(); } return View(); } else { string redirectUri = result.RedirectUri; /// Remove port from the redirect URL. /// This action is needed for http://gmailappasp.apphb.com/ application only. /// Remove it if you hosted solution not on the http://gmailappasp.apphb.com/ redirectUri = Regex.Replace(result.RedirectUri, @"(:\d{3,5})", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); /// return new RedirectResult(redirectUri); } }
/// <summary> /// List all of the people in the specified collection /// documentation: https://developers.google.com/+/api/latest/people/list /// </summary> /// <param name="service"></param> /// <param name="_userId">Get the collection of people for the person identified. Use "me" to indicate the authenticated user.</param> /// <returns></returns> public static IList<Person> GetAllPeople(PlusService service, string _userId) { PeopleResource.ListRequest list = service.People.List(_userId, PeopleResource.ListRequest.CollectionEnum.Visible); list.MaxResults = 10; PeopleFeed peopleFeed = list.Execute(); IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = list.Execute(); } return people; }
public static void POstGooglePlus() { string[] scopes = new string[] {PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile}; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = "9231245845-r8j2rtmtteakfut8qigee9c39mf10j3v.apps.googleusercontent.com", ClientSecret = "AvHRdSwtyNSZ9YVm6bDMPO6o", }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GooglePlus.Auth.Store") ).Result; // Now we create a Google service. All of our requests will be run though this. PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", }); }
/// <summary> /// Authenticate to Google Using Oauth2 /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> /// <param name="userName">A string used to identify a user.</param> /// <param name="datastore">datastore to use </param> /// <returns></returns> public static PlusService AuthenticateOauth(string clientId, string clientSecret, string userName, IDataStore datastore) { string[] scopes = new string[] { PlusService.Scope.PlusLogin, // know your basic profile info and your circles PlusService.Scope.PlusMe, // Know who you are on google PlusService.Scope.UserinfoEmail, // view your email address PlusService.Scope.UserinfoProfile}; // view your basic profile info. try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , datastore).Result; PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Authentication Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
public static void Main(string[] args) { Console.WriteLine("Plus API - Service Account"); Console.WriteLine("=========================="); String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE"; var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Plus API Sample", }); Activity activity = service.Activities.Get(ACTIVITY_ID).Execute(); Console.WriteLine(" Activity: " + activity.Object__.Content); Console.WriteLine(" Video: " + activity.Object__.Attachments[0].Url); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
/// <summary> /// Creates friend edges within the model for each match between this user's visible people /// and others who already exist in the database. /// </summary> /// <param name="user">The user object to create friend edges for.</param> /// <param name="ps">The Google+ API client service.</param> /// <returns>None.</returns> public static void GenerateFriends(User user, PlusService ps) { // Get the PeopleFeed for the currently authenticated user using the Google+ API. PeopleResource.ListRequest lr = ps.People.List("me", PeopleResource.CollectionEnum.Visible); PeopleFeed pf = lr.Fetch(); PhotohuntContext db = new PhotohuntContext(); do { foreach (Person p in pf.Items) { // Check whether the friend has an account on PhotoHunt bool userExists = db.Users.Any(u => u.googleUserId.Equals(p.Id)); if (userExists) { // Check whether friend edge already exists. User friend = db.Users.First(f => f.googleUserId.Equals(p.Id)); bool edgeExists = db.Edges.Any(e => e.photohuntUserId == user.id && e.friendUserId == friend.id); // Only add new edges when the user exists on PhotoHunt and the edge doesn't // already exist if (!edgeExists && userExists && friend.id != user.id) { // Save the friend edges. DirectedUserToEdge fromFriendEdge = new DirectedUserToEdge(); fromFriendEdge.friendUserId = friend.id; fromFriendEdge.photohuntUserId = user.id; db.Edges.Add(fromFriendEdge); DirectedUserToEdge toFriendEdge = new DirectedUserToEdge(); toFriendEdge.friendUserId = user.id; toFriendEdge.photohuntUserId = friend.id; db.Edges.Add(toFriendEdge); db.SaveChanges(); } } } lr.PageToken = pf.NextPageToken; pf = lr.Fetch(); } while (pf.NextPageToken != null); }
protected void Page_Load(object sender, EventArgs e) { // Create the Plus-Service if it is null. if (_service == null) { _service = new PlusService(_authenticator = CreateAuthenticator() ); _service.Key = ClientCredentials.ApiKey; } // Check if we received OAuth2 credentials with this request; if yes: parse it. if (HttpContext.Current.Request["code"] != null) { _authenticator.LoadAccessToken(); } // Change the button depending on our auth-state. listButton.Text = AuthState == null ? "Authenticate" : "Fetch ActivityList"; }
public static IList<Person> PeopleListByActivityPaging(PlusService service, string _activityId, PeopleResource.ListByActivityRequest.CollectionEnum _type, int NumberOfPages, int ItemsPerPage, string NextPageToken) { int max = ItemsPerPage; int count = 0; int iterate = NumberOfPages; PeopleResource.ListByActivityRequest list = service.People.ListByActivity(_activityId, _type); list.MaxResults = max; PeopleFeed peopleFeed = list.Execute(); IList<Person> people = new List<Person>(); count++; //// Loop through until we arrive at an empty page while (peopleFeed.Items != null || count <= iterate) { // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null || count >= iterate) { break; } // Execute and process the next page request peopleFeed = list.Execute(); count++; } Person token = new Person(); token.DisplayName = peopleFeed.NextPageToken; people.Add(token); return people; }
/// <summary> /// Write an app activity to Google using the Google+ API logging that the user /// has uploaded a Photo. /// </summary> /// <param name="user">The PhotoHunt user who uploaded the Photo.</param> /// <param name="dbPhoto">The Photo that was just uploaded.</param> public void WriteGooglePlusPhotoAppActivity(User user, Photo dbPhoto) { _authState = CreateState(user.googleAccessToken, user.googleRefreshToken, user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt); AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator <WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); Moment body = new Moment(); ItemScope target = new ItemScope(); target.Url = BASE_URL + "photo.aspx?photoId=" + dbPhoto.id; body.Target = target; body.Type = ADD_ACTIVITY_TYPE; MomentsResource.InsertRequest insert = new MomentsResource.InsertRequest(ps, body, "me", MomentsResource.Collection.Vault); try { insert.Fetch(); } catch (GoogleApiRequestException gare) { Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message + "\nThis could happen if the Google+ proxy can't access your server."); } }
public static IList<Activity> GetAllActivitiesLimited(PlusService service, string _userId, int NumberOfPages, int ItemsPerPage) { //List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list int max = ItemsPerPage; int count = 0; int iterate = NumberOfPages / max; ActivitiesResource.ListRequest list = service.Activities.List(_userId, ActivitiesResource.ListRequest.CollectionEnum.Public__); list.MaxResults = max; ActivityFeed activitesFeed = list.Execute(); IList<Activity> Activites = new List<Activity>(); count++; //// Loop through until we arrive at an empty page while (activitesFeed.Items != null || count <= iterate) { // Adding each item to the list. foreach (Activity item in activitesFeed.Items) { Activites.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (activitesFeed.NextPageToken == null || count <= iterate) { break; } // Prepare the next page of results list.PageToken = activitesFeed.NextPageToken; // Execute and process the next page request activitesFeed = list.Execute(); count++; } return Activites; }
public static string SearchGooglePlus(string query) { var service = new PlusService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = ApiKey }); var activities = service.Activities.Search(query).Execute().Items; var serializedResults = new StringBuilder(); foreach (var resultItem in activities) { serializedResults.AppendFormat( "<blockquote class=\"twitter-tweet\"><p>{0}</p><p><a href=\"{1}\"><img src=\"{2}\"/>{3}</a> - {4}</p></blockquote>", resultItem.Title, resultItem.Url, resultItem.Actor.Image.Url, resultItem.Actor.DisplayName, resultItem.Published); } return serializedResults.ToString(); }
static void Main(string[] args) { Console.WriteLine(@"Starting authorization..."); UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, new[] { PlusService.Scope.PlusLogin }, "me", CancellationToken.None).Result; // Create the service. var plusService = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Console Google+ Demo", }); Person me = plusService.People.Get("me").Execute(); Console.Write(@"Authorized user: "******"\n"); Console.Write(@"Press enter to exit."); Console.Read(); }
/// <summary> /// Search all public profiles. /// Documentation: https://developers.google.com/+/api/latest/people/search /// </summary> /// <param name="service"></param> /// <param name="_query">Specify a query string for full text search of public text in all profiles.</param> /// <returns></returns> public static IList<Person> SearchPeople(PlusService service, string _query) { PeopleFeed peopleFeed = null; PeopleResource.SearchRequest list = service.People.Search(_query); list.MaxResults = 5; try { peopleFeed = list.Execute(); } catch { } IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = list.Execute(); } return people; }
public static PlusService CreatePlusService(string apiKey, bool oAuth2, UserCredential credential) { if (oAuth2) { _plusService = new PlusService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "EQUATORPLAYER" }); } else { _plusService = new PlusService(new BaseClientService.Initializer { ApiKey = apiKey, ApplicationName = "EQUATORPLAYER" }); } return(_plusService); }
/// <summary> /// List all of the comments for an activity. /// Documentation: https://developers.google.com/+/api/latest/comments/list /// </summary> /// <param name="service">a Valid authenticated PlusService</param> /// <param name="_activityId">The ID of the activity to get comments for.</param> /// <returns></returns> public static IList<Comment> GetAllComments(PlusService service, string _activityId) { //List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list CommentsResource.ListRequest listComments = service.Comments.List(_activityId); listComments.MaxResults = 100; CommentFeed commentsFeed = listComments.Execute(); IList<Comment> Comments = new List<Comment>(); //// Loop through until we arrive at an empty page while (commentsFeed.Items != null) { // Adding each item to the list. foreach (Comment item in commentsFeed.Items) { Comments.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (commentsFeed.NextPageToken == null) { break; } // Prepare the next page of results listComments.PageToken = commentsFeed.NextPageToken; // Execute and process the next page request commentsFeed = listComments.Execute(); } return Comments; }
/// <summary> /// Get an activity. /// Documentation https://developers.google.com/plus/v1/reference/activities/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Plus service.</param> /// <param name="activityId">The ID of the activity to get.</param> /// <returns>ActivityResponse</returns> public static Activity Get(PlusService service, string activityId) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (activityId == null) { throw new ArgumentNullException(activityId); } // Make the request. return(service.Activities.Get(activityId).Execute()); } catch (Exception ex) { throw new Exception("Request Activities.Get failed.", ex); } }
public static List <SocialFeedItem> SearchGooglePlus(string query) { var service = new PlusService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = ApiKey }); var activities = service.Activities.Search(query).Execute().Items; var googlePlusFeed = (from result in activities select new SocialFeedItem() { DateCreated = result.Published.Value, DetailsUrl = result.Url, Source = FeedSource.GooglePlus, Text = result.Title, ThumbnailUrl = result.Actor.Image.Url, Username = result.Actor.DisplayName }).ToList(); return(googlePlusFeed); }
/// <summary> /// Get a comment. /// Documentation https://developers.google.com/plus/v1/reference/comments/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Plus service.</param> /// <param name="commentId">The ID of the comment to get.</param> /// <returns>CommentResponse</returns> public static Comment Get(PlusService service, string commentId) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (commentId == null) { throw new ArgumentNullException(commentId); } // Make the request. return(service.Comments.Get(commentId).Execute()); } catch (Exception ex) { throw new Exception("Request Comments.Get failed.", ex); } }
/// <summary> /// Get a person's profile. If your app uses scope https://www.googleapis.com/auth/plus.login, this method is guaranteed to return ageRange and language. /// Documentation https://developers.google.com/plus/v1/reference/people/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Plus service.</param> /// <param name="userId">The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user.</param> /// <returns>PersonResponse</returns> public static Person Get(PlusService service, string userId) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (userId == null) { throw new ArgumentNullException(userId); } // Make the request. return(service.People.Get(userId).Execute()); } catch (Exception ex) { throw new Exception("Request People.Get failed.", ex); } }
/// <summary> /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount /// </summary> /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns></returns> public static PlusService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return(null); } string[] scopes = new string[] { PlusService.Scope.PlusLogin, // know your basic profile info and your circles PlusService.Scope.PlusMe, // Know who you are on google PlusService.Scope.UserinfoEmail, // view your email address PlusService.Scope.UserinfoProfile }; // view your basic profile info. var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Authentication Sample", }); return(service); } catch (Exception ex) { Console.WriteLine(ex.InnerException); return(null); } }
public static IList<Activity> GetAllActivities(PlusService service, string _userId) { //List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list ActivitiesResource.ListRequest list = service.Activities.List(_userId, ActivitiesResource.ListRequest.CollectionEnum.Public); list.MaxResults = 100; ActivityFeed activitesFeed = list.Execute(); IList<Activity> Activites = new List<Activity>(); //// Loop through until we arrive at an empty page while (activitesFeed.Items != null) { // Adding each item to the list. foreach (Activity item in activitesFeed.Items) { Activites.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (activitesFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = activitesFeed.NextPageToken; // Execute and process the next page request activitesFeed = list.Execute(); } return Activites; }
protected override void OnViewInitialize(object sender, EventArgs e) { base.OnViewInitialize(sender, e); View.Username = "******"; View.DOB = null; View.SaveUser += View_SaveUser; string[] scopes = new string[] { PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile, PlusService.Scope.PlusMe }; UserCredential userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "463454622140-9g7bisaft6gt1imkfrufs3r1v0v6avgi.apps.googleusercontent.com", ClientSecret = "WPWGZkOvWk-VxoLNq7nySCHY" }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Current-See.GooglePlus.Auth.Store")) .Result; PlusService service = new PlusService( new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = "Current-See" }); PeopleResource test = service.People; }
public static void Main(string[] args) { Console.WriteLine("Plus API - Service Account"); Console.WriteLine("=========================="); String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE"; var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { PlusService.Scope.PlusMe } }.FromCertificate(certificate)); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Plus API Sample", }); Activity activity = service.Activities.Get(ACTIVITY_ID).Execute(); Console.WriteLine(" Activity: " + activity.Object.Content); Console.WriteLine(" Video: " + activity.Object.Attachments[0].Url); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public static string SearchGooglePlus(string query) { var service = new PlusService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = ApiKey }); var activities = service.Activities.Search(query).Execute().Items; var serializedResults = new StringBuilder(); foreach (var resultItem in activities) { serializedResults.AppendFormat( "<blockquote class=\"twitter-tweet\"><p>{0}</p><p><a href=\"{1}\"><img src=\"{2}\"/>{3}</a> - {4}</p></blockquote>", resultItem.Title, resultItem.Url, resultItem.Actor.Image.Url, resultItem.Actor.DisplayName, resultItem.Published); } return(serializedResults.ToString()); }
/// <summary> /// List all of the people in the specified collection for a particular activity. /// The collection parameter specifies which people to list, such as people who have +1'd or reshared this activity. /// Documentation: https://developers.google.com/+/api/latest/people/listByActivity /// </summary> /// <param name="service"></param> /// <param name="_activityId">The ID of the activity to get the list of people for.</param> /// <param name="_type">plusoners or resharers</param> /// <returns></returns> public static IList<Person> PeopleListByActivity(PlusService service, string _activityId, PeopleResource.ListByActivityRequest.CollectionEnum _type) { PeopleResource.ListByActivityRequest list = service.People.ListByActivity(_activityId, _type); list.MaxResults = 100; PeopleFeed peopleFeed = list.Execute(); IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = list.Execute(); } return people; }
/// <summary> /// Search public activities. /// /// Documentation: https://developers.google.com/+/api/latest/activities/search /// </summary> /// <param name="service">a Valid authenticated PlusService</param> /// <param name="_query">Full-text search query string.</param> /// <returns></returns> public static IList<Activity> SearchActivities(PlusService service, string _query) { //List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list ActivitiesResource.SearchRequest list = service.Activities.Search(_query); list.MaxResults = 20; ActivityFeed activitesFeed = list.Execute(); IList<Activity> Activites = new List<Activity>(); int Count = 0; //// Loop through until we arrive at an empty page while (activitesFeed.Items != null) { // Adding each item to the list. foreach (Activity item in activitesFeed.Items) { Activites.Add(item); Count++; } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (activitesFeed.NextPageToken == null || Count > 300) { break; } // Prepare the next page of results list.PageToken = activitesFeed.NextPageToken; // Execute and process the next page request activitesFeed = list.Execute(); } return Activites; }
/// <summary> /// Creates friend edges within the model for each match between this user's visible people /// and others who already exist in the database. This method is here for cases where the /// method call is used asynchronously. /// </summary> /// <param name="user">The user object to create friend edges for.</param> /// <param name="authState">Contains the IAuthorizationState object which is used to /// authorize the client to generate the signed in user's visible people.</param> /// <returns>None.</returns> public void GenerateFriends(User user, IAuthorizationState authState) { // Set the authorization state in the base class for the authorization call. _authState = authState; var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator <WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); GenerateFriends(user, ps); }
/// <summary> /// Get a comment. /// Documentation: https://developers.google.com/+/api/latest/comments/get /// </summary> /// <param name="service"></param> /// <param name="_commentId">The ID of the comment to get.</param> /// <returns></returns> public static Comment Getcomment(PlusService service, string _commentId) { CommentsResource.GetRequest Request = service.Comments.Get(_commentId); return Request.Execute(); }
static void Main(string[] args) { //Scopes for use with Google+ API // activating Google+ API in console // Documentation: https://developers.google.com/+/api/oauth string[] scopes = new string[] { PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile ,"profile" }; string _client_id = "1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com"; string _client_secret = "NDmluNfTgUk6wgmy7cFo64RV"; // https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com&redirect_uri=http://localhost:15918/authorize/&scope=https://www.googleapis.com/auth/plus.login%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&data-requestvisibleactions=http://schema.org/AddAction PlusService service = null; UserCredential credential = null; try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GooglePlusm.Auth.Store")).Result; } catch (Exception ex) { //If the user hits cancel you wont get access. if (ex.InnerException.Message.IndexOf("access_denied") != -1) { Console.WriteLine("User declined access"); Console.ReadLine(); return; } else { Console.WriteLine("Unknown Authentication Error:" + ex.Message); Console.ReadLine(); return; } } // Now we create a Google service. All of our requests will be run though this. service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", }); Moment body = new Moment(); body.Type = "http://schema.org/AddAction"; ItemScope itemScope = new ItemScope(); itemScope.Id = "target-id-1" ; itemScope.Type = "http://schema.org/AddAction"; itemScope.Name = "The Google+ Platform"; itemScope.Description = "A page that describes just how awesome Google+ is!"; itemScope.Image = "https://developers.google.com/+/plugins/snippet/examples/thing.png"; body.Object = itemScope; try { var l = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault); l.Execute(); } catch (Exception ex) { int i = 1; } // Getting a list of ALL a users public activities. IList<Activity> _Activities = DaimtoGooglePlusHelper.GetAllActivities(service, "me"); foreach (Activity item in _Activities) { Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems); } //Just getting an activity that has some comments for the example below. Activity withComment = _Activities.Where(x => x.Object.Replies.TotalItems > 0).FirstOrDefault(); // Getting a list of all the comments for an activity IList<Comment> _comments = DaimtoGooglePlusHelper.GetAllComments(service, withComment.Id); foreach (Comment item in _comments) { Console.WriteLine("Comment " + item.Actor.DisplayName + " Plus 1s: " + item.Plusoners.TotalItems); } //Listing of all the people the user has circled. IList<Person> people = DaimtoGooglePlusHelper.GetAllPeople(service, "me"); Console.ReadLine(); }
static void Main(string[] args) { // authentication // nuget install-package Google.Apis // install-package Google.Apis.Auth string[] scopes = new string[] { // PlusService.Scope.PlusMe, The https://www.googleapis.com/auth/plus.me scope is not recommended as a login scope because, for users who have not upgraded to Google+, it does not return the user's name or email address. PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile }; string _client_id = "1046123799103-7mk8g2iok1dv9fphok8v2kv82hiqb0q6.apps.googleusercontent.com"; string _client_secret = "GeE-cD7PtraV0LqyoxqPnOpv"; UserCredential credential = null; try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, scopes, Environment.UserName, CancellationToken.None, // new LocalFileDataStore("Daimto.Auth.Store")).Result; new DatabaseDataStore(@"LINDAL-PC2013\SQL2012", "LindaTest", "test123", "test", "test")).Result; } catch (Exception ex) { //If the user hits cancel you wont get access. if (ex.InnerException.Message.IndexOf("access_denied") != -1) { Console.WriteLine("User declined access"); Console.ReadLine(); return; } else { Console.WriteLine("Unknown Authentication Error:" + ex.Message); Console.ReadLine(); return; } } finally { string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Daimto.Auth.Store\Google.Apis.Auth.OAuth2.Responses.TokenResponse-" + Environment.UserName; Console.WriteLine("refreshToken:" + credential.Token.RefreshToken); Console.WriteLine("AccessToken:" + credential.Token.AccessToken); Console.WriteLine(""); Console.WriteLine("FileDatastore:" + filename); Console.WriteLine(""); using (StreamReader sr = new StreamReader(filename)) { String line = sr.ReadToEnd(); Console.WriteLine(line); } // Now we create a Google service. All of our requests will be run though this. PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", }); int i = 1; // Getting a list of ALL a users public activities. IList <Activity> _Activities = GetAllActivities(service, "me"); foreach (Activity item in _Activities) { Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems); } } int o = 1; }
public static string getAccountId(PlusService serviceplus) { Person user = getPlusUser(serviceplus); return(user.Id); }
protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { var form = GetForm(); if (form != null) { string accessToken = form["AccessToken"]; if (!string.IsNullOrWhiteSpace(accessToken)) { var props = new AuthenticationProperties(); if (Options.SaveTokens) { // logic here similar to https://github.com/aspnet/Security/blob/beaa2b443d46ef8adaf5c2a89eb475e1893037c2/src/Microsoft.AspNetCore.Authentication.OAuth/OAuthHandler.cs#L103 var authTokens = new List <AuthenticationToken> { new AuthenticationToken { Name = "access_token", Value = accessToken } }; // other tokens here if we can get them (currently access_token is the only one we can get from AppScript) props.StoreTokens(authTokens); } // validate the token and get user info bool isSuccess = false; using (var plusService = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = GoogleCredential.FromAccessToken(accessToken) })) { Person userInfo; try { var req = plusService.People.Get("me"); userInfo = await req.ExecuteAsync(); } catch (Exception) { //TODO: handle getting userinfo errors gracefully with logging throw; } var identity = new ClaimsIdentity( new List <Claim> { new Claim(ClaimTypes.NameIdentifier, userInfo.Id), new Claim(ClaimTypes.Name, userInfo.DisplayName), new Claim(ClaimTypes.GivenName, userInfo.Name?.GivenName), new Claim(ClaimTypes.Surname, userInfo.Name?.FamilyName), new Claim("urn:google:profile", userInfo.Url), new Claim(ClaimTypes.Email, userInfo.Emails.FirstOrDefault()?.Value) }, AppScriptOAuthAuthenticationDefaults.AuthenticationScheme); var user = new ClaimsPrincipal(identity); await Context.SignInAsync(SignInScheme, user, props); isSuccess = true; } if (isSuccess) { string returnUrl = form["ReturnUrl"]; if (!string.IsNullOrWhiteSpace(returnUrl)) { Context.Response.Redirect(returnUrl); } } } } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.Equals("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.Equals("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; string userid = context.Request["gplus_id"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Manually perform the OAuth2 flow for now. var authObject = ManualCodeExchanger.ExchangeCode(code); // Create an authorization state from the returned token. _authState = CreateState( authObject.access_token, authObject.refresh_token, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(authObject.expires_in)); // Use Tokeninfo to validate the user and the client. var tokeninfo_request = new Oauth2Service().Tokeninfo(); tokeninfo_request.Access_token = _authState.AccessToken; var tokeninfo = tokeninfo_request.Fetch(); if (userid == tokeninfo.User_id && tokeninfo.Issued_to == CLIENT_ID) { context.Session["authState"] = _authState; } else { // The credentials did not match. context.Response.StatusCode = 401; return; } } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. _authState = (IAuthorizationState)context.Session["authState"]; AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator<WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(authenticator); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.CollectionEnum.Visible).Fetch(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. _authState = (IAuthorizationState)context.Session["authState"]; string token = (_authState.RefreshToken != null) ? _authState.RefreshToken : _authState.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
static void Main(string[] args) { //Scopes for use with Google+ API // activating Google+ API in console // Documentation: https://developers.google.com/+/api/oauth string[] scopes = new string[] { PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile, "profile" }; string _client_id = "1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com"; string _client_secret = "NDmluNfTgUk6wgmy7cFo64RV"; // https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com&redirect_uri=http://localhost:15918/authorize/&scope=https://www.googleapis.com/auth/plus.login%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&data-requestvisibleactions=http://schema.org/AddAction PlusService service = null; UserCredential credential = null; try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GooglePlusm.Auth.Store")).Result; } catch (Exception ex) { //If the user hits cancel you wont get access. if (ex.InnerException.Message.IndexOf("access_denied") != -1) { Console.WriteLine("User declined access"); Console.ReadLine(); return; } else { Console.WriteLine("Unknown Authentication Error:" + ex.Message); Console.ReadLine(); return; } } // Now we create a Google service. All of our requests will be run though this. service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", }); Moment body = new Moment(); body.Type = "http://schema.org/AddAction"; ItemScope itemScope = new ItemScope(); itemScope.Id = "target-id-1"; itemScope.Type = "http://schema.org/AddAction"; itemScope.Name = "The Google+ Platform"; itemScope.Description = "A page that describes just how awesome Google+ is!"; itemScope.Image = "https://developers.google.com/+/plugins/snippet/examples/thing.png"; body.Object = itemScope; try { var l = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault); l.Execute(); } catch (Exception ex) { int i = 1; } // Getting a list of ALL a users public activities. IList <Activity> _Activities = DaimtoGooglePlusHelper.GetAllActivities(service, "me"); foreach (Activity item in _Activities) { Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems); } //Just getting an activity that has some comments for the example below. Activity withComment = _Activities.Where(x => x.Object.Replies.TotalItems > 0).FirstOrDefault(); // Getting a list of all the comments for an activity IList <Comment> _comments = DaimtoGooglePlusHelper.GetAllComments(service, withComment.Id); foreach (Comment item in _comments) { Console.WriteLine("Comment " + item.Actor.DisplayName + " Plus 1s: " + item.Plusoners.TotalItems); } //Listing of all the people the user has circled. IList <Person> people = DaimtoGooglePlusHelper.GetAllPeople(service, "me"); Console.ReadLine(); }
public static void getActivities() { InitProvider(); OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); PlusService service = new PlusService(auth); ActivityFeed list = service.Activities.List(userid, ActivitiesResource.Collection.Public).Fetch(); Console.Write("2 " + list.Title); }
static void Main(string[] args) { //Scopes for use with Google+ API // activating Google+ API in console // Documentation: https://developers.google.com/+/api/oauth string[] scopes = new string[] { // PlusService.Scope.PlusMe, The https://www.googleapis.com/auth/plus.me scope is not recommended as a login scope because, for users who have not upgraded to Google+, it does not return the user's name or email address. PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile }; string _client_id = "1046123799103-7mk8g2iok1dv9fphok8v2kv82hiqb0q6.apps.googleusercontent.com"; string _client_secret = "GeE-cD7PtraV0LqyoxqPnOpv"; PlusService service = null; UserCredential credential = null; try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id, ClientSecret = _client_secret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GooglePlus.Auth.Store")).Result; } catch (Exception ex) { //If the user hits cancel you wont get access. if (ex.InnerException.Message.IndexOf("access_denied") != -1) { Console.WriteLine("User declined access"); Console.ReadLine(); return; } else { Console.WriteLine("Unknown Authentication Error:" + ex.Message); Console.ReadLine(); return; } } // Now we create a Google service. All of our requests will be run though this. service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", }); // Getting a list of ALL a users public activities. IList <Activity> _Activities = DaimtoGooglePlusHelper.GetAllActivities(service, "me"); foreach (Activity item in _Activities) { Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems); } //Just getting an activity that has some comments for the example below. Activity withComment = _Activities.Where(x => x.Object.Replies.TotalItems > 0).FirstOrDefault(); // Getting a list of all the comments for an activity IList <Comment> _comments = DaimtoGooglePlusHelper.GetAllComments(service, withComment.Id); foreach (Comment item in _comments) { Console.WriteLine("Comment " + item.Actor.DisplayName + " Plus 1s: " + item.Plusoners.TotalItems); } //Listing of all the people the user has circled. IList <Person> people = DaimtoGooglePlusHelper.GetAllPeople(service, "me"); Console.ReadLine(); }
/// <summary> /// Write an app activity to Google using the Google+ API logging that the user /// has uploaded a Photo. /// </summary> /// <param name="user">The PhotoHunt user who uploaded the Photo.</param> /// <param name="dbPhoto">The Photo that was just uploaded.</param> public void WriteGooglePlusPhotoAppActivity(User user, Photo dbPhoto) { _authState = CreateState(user.googleAccessToken, user.googleRefreshToken, user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt); AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator<WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); Moment body = new Moment(); ItemScope target = new ItemScope(); target.Url = BASE_URL + "photo.aspx?photoId=" + dbPhoto.id; body.Target = target; body.Type = ADD_ACTIVITY_TYPE; MomentsResource.InsertRequest insert = new MomentsResource.InsertRequest(ps, body, "me", MomentsResource.Collection.Vault); try { insert.Fetch(); } catch (GoogleApiRequestException gare) { Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message + "\nThis could happen if the Google+ proxy can't access your server."); } }
private static void Run() { UserCredential credential; var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = new[] { PlusService.Scope.PlusLogin } }; var flow = new AAGoogleAuthorizationCodeFlow(initializer); credential = new AuthorizationCodeInstalledApp(flow, new LocalServerCodeReceiver()).AuthorizeAsync ("user", CancellationToken.None).Result; // Create the service. var service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Gus API", }); Moment body = new Moment(); ItemScope target = new ItemScope(); target.Url = "https://developers.google.com/+/web/snippet/examples/widget"; target.Image = "http://picpaste.com/pics/001.1437292069.jpg"; //target.Type = "http://schema.org/Thing"; target.Description = "The description for the action"; target.Name = "An example of add activity"; body.Target = target; body.Type = "http://schemas.google.com/AddActivity"; //PeopleResource.GetRequest personRequest = service.People.Get("me"); //Person _me = personRequest.Execute(); MomentsResource.InsertRequest insert = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault); //new MomentsResource.InsertRequest( // service, // body, // "me", // MomentsResource.InsertRequest.CollectionEnum.Vault); Moment wrote = insert.Execute(); MomentsResource.ListRequest ls = service.Moments.List("me", MomentsResource.ListRequest.CollectionEnum.Vault); MomentsFeed feeds = ls.Execute(); }
public static bool?verfiedAccount(PlusService serviceplus) { Person user = getPlusUser(serviceplus); return(user.Verified.Value); }
private void POstGooglePlus(UserCredential credential) { PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); Moment body = new Moment(); body.Type = "http://schema.org/AddAction"; ItemScope itemScope = new ItemScope(); itemScope.Id = "target-id-1"; itemScope.Type = "http://schema.org/AddAction"; itemScope.Name = "The Google+ Platform"; itemScope.Description = "A page that describes just how awesome Google+ is!"; itemScope.Image = "https://developers.google.com/+/plugins/snippet/examples/thing.png"; body.object__ = itemScope; var l = service.Moments.Insert(body, "me", MomentsResource.InsertRequest.CollectionEnum.Vault); l.Execute(); PeopleResource.GetRequest personRequest = service.People.Get("me"); Person _me = personRequest.Execute(); }
public static string getName(PlusService serviceplus) { Person user = getPlusUser(serviceplus); return(user.DisplayName); }
/// <summary> /// Get a person /// Documentation: https://developers.google.com/+/api/latest/people/get /// </summary> /// <param name="service"></param> /// <param name="_userId">Get a person's profile.If using the userId value "me", this method requires authentication using a token that has been granted the OAuth scope</param> /// <returns></returns> public static Person GetPerson(PlusService service, string _userId) { PeopleResource.GetRequest personRequest = service.People.Get(_userId); return personRequest.Execute(); }
public static string getPhotoUrl(PlusService serviceplus) { Person user = getPlusUser(serviceplus); return(user.Image.Url); }
/// <summary> /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount /// </summary> /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns></returns> public static PlusService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return null; } string[] scopes = new string[] { PlusService.Scope.PlusLogin, // know your basic profile info and your circles PlusService.Scope.PlusMe, // Know who you are on google PlusService.Scope.UserinfoEmail, // view your email address PlusService.Scope.UserinfoProfile}; // view your basic profile info. var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. PlusService service = new PlusService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Authentication Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
public static string getCurrentLocation(PlusService serviceplus) { Person user = getPlusUser(serviceplus); return(user.CurrentLocation); }
/// <summary> /// Get an activity /// Documentation: https://developers.google.com/+/api/latest/activities/get /// </summary> /// <param name="service"></param> /// <param name="_activityId">The ID of the activity to get.</param> /// <returns></returns> public static Activity GetActivity(PlusService service, string _activityId) { ActivitiesResource.GetRequest activityRequest = service.Activities.Get(_activityId); return activityRequest.Execute(); }
public async Task <bool> Handle(LoginGooglePlusUserRequest request) { if (request.SecurityContext.GetAuthenticatedUser() != null) { // The user is already connected return(true); } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GooglePlusSecrets.Secrets, Scopes = GooglePlusSecrets.Scopes }); var token = await flow.ExchangeCodeForTokenAsync( "", request.Code, "postmessage", CancellationToken.None); // Get tokeninfo for the access token if you want to verify. var service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); var oauthRequest = service.Tokeninfo(); oauthRequest.AccessToken = token.AccessToken; var info = oauthRequest.Execute(); // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. var credential = new UserCredential(flow, "me", token); await credential.RefreshTokenAsync(CancellationToken.None); token = credential.Token; var plusService = new PlusService( new Google.Apis.Services.BaseClientService.Initializer { ApplicationName = "DLVoter", HttpClientInitializer = credential }); var me = await plusService.People.Get("me").ExecuteAsync(); var user = new User { FirstName = me.Name.GivenName, LastName = me.Name.FamilyName, ExternalCorrelationId = new ExternalCorrelationId { Value = info.UserId }, Type = UserType.GooglePlus }; user.OAuthToken = new OAuthToken { Value = token?.RefreshToken ?? token?.AccessToken }; request.SecurityContext.SetAuthenticatedUser(user); // ToDo: Add or update user in database return(true); }
/// <summary> /// Creates friend edges within the model for each match between this user's visible people /// and others who already exist in the database. This method is here for cases where the /// method call is used asynchronously. /// </summary> /// <param name="user">The user object to create friend edges for.</param> /// <param name="authState">Contains the IAuthorizationState object which is used to /// authorize the client to generate the signed in user's visible people.</param> /// <returns>None.</returns> public void GenerateFriends(User user,IAuthorizationState authState) { // Set the authorization state in the base class for the authorization call. _authState = authState; var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator<WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); GenerateFriends(user, ps); }
// RefreshService /// <summary> /// Ensures that the current Plus service is authenticated and valid /// </summary> private void RefreshService() { // Create the service. if (plusService == null) { // Register the authenticator. var auth = CreateAuthenticator(); plusService = new PlusService(auth); if (plusService != null) { PeopleResource.GetRequest prgr = plusService.People.Get("me"); me = prgr.Fetch(); } } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // Create an authorization state from the returned token. context.Session["authState"] = token; // Get tokeninfo for the access token if you want to verify. Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = token.AccessToken; Tokeninfo info = request.Execute(); string gplus_id = info.UserId; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. token = (TokenResponse)context.Session["authState"]; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); UserCredential credential = new UserCredential(flow, "me", token); bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; token = credential.Token; ps = new PlusService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = ".NET Quickstart", HttpClientInitializer = credential }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. token = (TokenResponse)context.Session["authState"]; string tokenToRevoke = (token.RefreshToken != null) ? token.RefreshToken : token.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + tokenToRevoke); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
/// <summary> /// Either: /// 1. Create a user for the given ID and credential /// 2. Or, update the existing user with the existing credential /// /// If 2, then ask Google for the user's public profile information to store. /// </summary> /// <param name="authState">The OAuth v2 state for authorizing the user.</param> /// <returns>A User object that represents the created user.</returns> public User SaveTokenForUser(IAuthorizationState authState) { // Set the auth state in a the superclass for the authorization call. _authState = authState; var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator<WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(authenticator); Person me = ps.People.Get("me").Fetch(); // Load the user model from the DB if the user already exists. bool userExists = false; User user = new User(); PhotohuntContext db = new PhotohuntContext(); User existing = db.Users.FirstOrDefault(u => u.googleUserId.Equals(me.Id)); if (existing != null) { user = existing; userExists = true; } if (!userExists) { // Save the new user. user.googleAccessToken = authState.AccessToken; user.googleRefreshToken = authState.RefreshToken == null ? "" : authState.RefreshToken; user.googleExpiresIn = (int)(authState.AccessTokenExpirationUtc.Value - authState.AccessTokenIssueDateUtc.Value).TotalSeconds; user.googleExpiresAt = authState.AccessTokenExpirationUtc.Value; user.googleUserId = me.Id; user.googleDisplayName = me.DisplayName; user.googlePublicProfilePhotoUrl = me.Image.Url; user.googlePublicProfileUrl = me.Url; user.email = me.Emails == null ? "" : me.Emails[0].Value; db.Users.Add(user); db.SaveChanges(); db.Entry(user); // Use the FriendsHelper to generate this user's list of friends // who also use this app. PhotoHunt.utils.FriendsHelper.GenerateFriends(user, ps); } else { // Update the existing user's authorization state. Note that we aren't updating the // refresh token because it is only returned the first time the user authorizes the // app. user.googleAccessToken = authState.AccessToken; user.googleExpiresIn = (int)(authState.AccessTokenExpirationUtc.Value - authState.AccessTokenIssueDateUtc.Value).TotalSeconds; user.googleExpiresAt = authState.AccessTokenExpirationUtc.Value; db.SaveChanges(); } return user; }
/// <summary> /// Writes a Google+ App Activity to Google logging that the user has voted on a PhotoHunt /// photo. /// </summary> /// <param name="user">The user who has voted.</param> /// <param name="voteTarget">The photo the user has voted on.</param> public void WriteGooglePlusVoteAppActivity(User user, Photo voteTarget) { // Write an app activity for the vote. // Set the auth state in a the superclass for the authorization call. _authState = CreateState(user.googleAccessToken, user.googleRefreshToken, user.googleExpiresAt.AddSeconds(user.googleExpiresIn * -1), user.googleExpiresAt); AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator<WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); Moment body = new Moment(); ItemScope target = new ItemScope(); ItemScope result = new ItemScope(); // The target (an image) will be parsed from this URL containing microdata. target.Url = BASE_URL + "photo.aspx?photoId=" + voteTarget.id; // Just use a static review result. result.Type = SCHEMA_REVIEW_TYPE; result.Name = "A vote for this PhotoHunt photo."; result.Url = target.Url; result.Text = "This photo embodies " + voteTarget.themeDisplayName; body.Target = target; body.Result = result; body.Type = REVIEW_ACTIVITY_TYPE; MomentsResource.InsertRequest insert = new MomentsResource.InsertRequest( ps, body, "me", MomentsResource.Collection.Vault); try { insert.Fetch(); } catch (GoogleApiRequestException gare) { Debug.WriteLine("Error while writing app activity: " + gare.InnerException.Message + "\nThis could happen if the Google+ proxy can't access your server."); } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // Create an authorization state from the returned token. context.Session["authState"] = token; // Get tokeninfo for the access token if you want to verify. Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = token.AccessToken; Tokeninfo info = request.Execute(); string gplus_id = info.UserId; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. token = (TokenResponse)context.Session["authState"]; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); UserCredential credential = new UserCredential(flow, "me", token); bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; token = credential.Token; ps = new PlusService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = ".NET Quickstart", HttpClientInitializer = credential }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. token = (TokenResponse)context.Session["authState"]; string tokenToRevoke = (token.RefreshToken != null) ? token.RefreshToken : token.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
public async Task<ActionResult> PlusMinus(string searchString) { var service = new PlusService(new BaseClientService.Initializer { ApplicationName = this.ApplicationName, ApiKey = this.ApiKey, }); var request = service.Activities.Search(searchString).ExecuteAsync(); var activityFeed = await request; return View(activityFeed); }
/// <summary> /// Either: /// 1. Create a user for the given ID and credential /// 2. Or, update the existing user with the existing credential /// /// If 2, then ask Google for the user's public profile information to store. /// </summary> /// <param name="authState">The OAuth v2 state for authorizing the user.</param> /// <returns>A User object that represents the created user.</returns> public User SaveTokenForUser(IAuthorizationState authState) { // Set the auth state in a the superclass for the authorization call. _authState = authState; var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator <WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(authenticator); Person me = ps.People.Get("me").Fetch(); // Load the user model from the DB if the user already exists. bool userExists = false; User user = new User(); PhotohuntContext db = new PhotohuntContext(); User existing = db.Users.FirstOrDefault(u => u.googleUserId.Equals(me.Id)); if (existing != null) { user = existing; userExists = true; } if (!userExists) { // Save the new user. user.googleAccessToken = authState.AccessToken; user.googleRefreshToken = authState.RefreshToken == null ? "" : authState.RefreshToken; user.googleExpiresIn = (int)(authState.AccessTokenExpirationUtc.Value - authState.AccessTokenIssueDateUtc.Value).TotalSeconds; user.googleExpiresAt = authState.AccessTokenExpirationUtc.Value; user.googleUserId = me.Id; user.googleDisplayName = me.DisplayName; user.googlePublicProfilePhotoUrl = me.Image.Url; user.googlePublicProfileUrl = me.Url; user.email = me.Emails == null ? "" : me.Emails[0].Value; db.Users.Add(user); db.SaveChanges(); db.Entry(user); // Use the FriendsHelper to generate this user's list of friends // who also use this app. PhotoHunt.utils.FriendsHelper.GenerateFriends(user, ps); } else { // Update the existing user's authorization state. Note that we aren't updating the // refresh token because it is only returned the first time the user authorizes the // app. user.googleAccessToken = authState.AccessToken; user.googleExpiresIn = (int)(authState.AccessTokenExpirationUtc.Value - authState.AccessTokenIssueDateUtc.Value).TotalSeconds; user.googleExpiresAt = authState.AccessTokenExpirationUtc.Value; db.SaveChanges(); } return(user); }
/// <summary> /// 验证authcode和userid是否正确 /// </summary> /// <param name="userid"></param> /// <returns></returns> public static bool VerifyAuthCode() { InitProvider(); OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); PlusService service = new PlusService(auth); Person person = service.People.Get(userid).Fetch(); return person.DisplayName!=null && person.DisplayName.Length>0; }