public void ReInit() { if (Service != null) { Service.Dispose(); } Credential = null; using (var stream = Assembly .GetExecutingAssembly() .GetManifestResourceStream("GTranslator.GTranslator_OAuth2.json")) { Credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, Settings.AppName, CancellationToken.None, new FileDataStore(Settings.FileStore, true)).Result; } Service = new PeopleServiceService( new BaseClientService.Initializer { HttpClientInitializer = Credential, ApplicationName = Settings.AppName }); }
public Attendee() { ExceptionHandler <Attendee> handlerAttendee = new ExceptionHandler <Attendee>(); peopleService = GService.peopleService; uuidMaster = new UUID(); }
private Person GetAccountData(Account account) { Person person; try { this._provider.ClientIdentifier = (base.Application.ApplicationKey); this._provider.ClientSecret = (base.Application.ApplicationSecret); this.auth = this.GetAuthState(account.AccessTokenSecret); var request = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = GoogleCredential.FromAccessToken(this.auth.AccessToken), }).People.Get("people/me"); request.RequestMaskIncludeField = "person.names,person.emailAddresses,person.metadata"; person = request.Execute(); //person = new PeopleServiceService(new OAuth2Authenticator<NativeApplicationClient>(this._provider, new Func<NativeApplicationClient, IAuthorizationState>(this.GetAuthentication))).People.Get("me").Fetch(); } catch (Exception exception) { new GooglePlusExceptionAnalyzer().Analyze(exception); return(null); } return(person); }
/// <summary> /// Get Google Access Tokens /// </summary> /// <param name="userId"></param> /// <returns></returns> public async Task <string> GetGoogleAccessToken(string userId) { string accessToken = null; User user = await GetUser(userId); foreach (Identity userIdentity in user?.Identities) { if (userIdentity.Provider == "google-oauth2") { accessToken = userIdentity.AccessToken; string refreshToken = userIdentity.RefreshToken; PeopleServiceService peopleService = new PeopleServiceService(new BaseClientService.Initializer() { ApplicationName = "Pizza42", }); peopleService.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> connections = connectionsResponse.Connections; int connectionCount = connections.Count; } } return(accessToken); }
//PeopleService Service; public Attendee() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "admin", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create the service. peopleService = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); }
/// <summary> /// OAuth2 service /// </summary> public GooglePeopleService(UserCredential credentials) { peopleService = new PeopleServiceService(new Google.Apis.Services.BaseClientService.Initializer { HttpClientInitializer = credentials }); }
public GooglePeople(string accessToken) { _peopleService = new PeopleServiceService(new BaseClientService.Initializer() { ApplicationName = "Pizza42", }); _peopleService.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); }
public ActionResult GetAuthenticationToken(string code) { if (String.IsNullOrEmpty(code)) { return(View("Error")); } string redirectUrl = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.GetAuthenticationToken)).TrimStart('/')}"; var scopes = new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" }; string path = Server.MapPath("~/client_secrets.json"); ClientSecrets Secrets = null; using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read)) { Secrets = GoogleClientSecrets.Load(filestream).Secrets; } var initializer = new GoogleAuthorizationCodeFlow.Initializer() { ClientSecrets = Secrets, Scopes = new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" }, }; int UserIdPersona = 0; int.TryParse(Session["IdUsuario"].ToString(), out UserIdPersona); var googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer); var token = googleCodeFlow.ExchangeCodeForTokenAsync(UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), code, redirectUrl, CancellationToken.None).Result; //var resultMVC = new AuthorizationCodeWebApp(googleCodeFlow, redirectUrl, redirectUrl).AuthorizeAsync(UserId.ToString(), CancellationToken.None).Result; UserCredential credential = new UserCredential(googleCodeFlow, UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), token); PeopleServiceService PeopleS = new PeopleServiceService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = Application_Name, ApiKey = "AIzaSyBtEx9nIXbv-C-jEj45iIUZvs-HUP8SCc8" }); var tokenJson = JsonConvert.SerializeObject(token); var RequestListado = PeopleS.People.Connections.List("people/me"); RequestListado.PersonFields = "names,emailAddresses,phoneNumbers"; var response = RequestListado.Execute(); IList <Person> ListadoContactos = response.Connections; if (ListadoContactos != null) { ListadoContactos = ListadoContactos.Where(x => x.PhoneNumbers != null && x.EmailAddresses != null && x.Names != null).ToList(); } Session["TokenPeople"] = tokenJson; Session["ListadoContactos"] = ListadoContactos; return(RedirectToAction("Index", "Authorize")); }
/// <summary> /// Service account that uses .p12 key and service mail /// </summary> /// <param name="keyFilePath"> .p12 key obtained from dev.google.com service accounts </param> /// <param name="googleScope"> type of scope from google api </param> public GooglePeopleService(string keyFilePath, string googleScope, string serviceAccEmail) { ServiceCredential credentials; var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); credentials = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccEmail) { Scopes = new[] { googleScope }, }.FromCertificate(certificate)); peopleService = new PeopleServiceService(new Google.Apis.Services.BaseClientService.Initializer { HttpClientInitializer = credentials }); }
public async Task <Person> GetUserData(IGoogleAuthProvider authProvider) { var credential = await authProvider.GetCredentialAsync(); var service = new PeopleServiceService(new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = "Disco", HttpClientInitializer = credential }); var response = service.People.Get("people/me").Execute(); return(response); }
/// <summary> /// We exit from the Google account. /// Moreover, if the token is not empty, we update it and then reset it. /// We also check if the token has expired. /// </summary> public void LogOut() { if (_service != null) { var credential = GetUserCredential(); if (credential.Token.IsExpired(SystemClock.Default)) { var refresh = credential.RefreshTokenAsync(CancellationToken.None).Result; } var revoke = credential.RevokeTokenAsync(CancellationToken.None).Result; } _service = null; }
public GoogleContacts() { // Create OAuth credential. UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = m_client_id, ClientSecret = m_client_secret }, new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" }, "me", CancellationToken.None).Result; // Create the service. var service = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "My App", }); // Groups list //////////// ContactGroupsResource groupsResource = new ContactGroupsResource(service); ContactGroupsResource.ListRequest listRequest = groupsResource.List(); ListContactGroupsResponse response = listRequest.Execute(); // eg to show name of each group List <string> groupNames = new List <string>(); foreach (ContactGroup group in response.ContactGroups) { groupNames.Add(group.FormattedName); } /////////////// // Contact list //////////// PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses"; peopleRequest.SortOrder = (PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum) 1; ListConnectionsResponse people = peopleRequest.Execute(); // eg to show display name of each contact List <string> contacts = new List <string>(); foreach (var person in people.Connections) { contacts.Add(person.Names[0].DisplayName); } /////////////// }
public void Authorize() { var userCredential = GetUserCredential(); if (userCredential.Token.IsExpired(SystemClock.Default)) { var refresh = userCredential.RefreshTokenAsync(CancellationToken.None).Result; } var service = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = "NetTest", }); _service = service; }
/// <summary> /// Create people service. /// </summary> private void CreateService() { // Create OAuth credential. var credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "812699070892-9qfj0cpq2s76hgidon5rrjq90lernd19.apps.googleusercontent.com", ClientSecret = "db4chSxaRCg-xvLERQspSFLV" }, new[] { "profile", "https://www.googleapis.com/auth/contacts" }, "admin", CancellationToken.None).Result; // Create the service. PeopleService = new PeopleServiceService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "ContactsClient2" }); }
private async Task AuthenticateAsync(IEnumerable <string> scopes) { if (service != null) { return; } credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new Uri("ms-appx:///Assets/client_secrets.json"), scopes, "user", CancellationToken.None); var initializer = new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "BloggerApp", }; service = new PeopleServiceService(initializer); }
private async Task <UserInfo> GetUserInfoGoogleAsync(bool forTesting) { var peopleService = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = UserCredential, ApplicationName = App.kGoogleServicesAppName, }); var meRequest = peopleService.People.Get("people/me"); meRequest.PersonFields = "names,emailAddresses,photos"; var me = await meRequest.ExecuteAsync(); UserInfo user = new UserInfo(); user.id = me.ResourceName; user.name = me.Names.FirstOrDefault()?.DisplayName ?? "Unknown Name"; user.email = me.EmailAddresses.FirstOrDefault(x => x.Metadata.Primary ?? false)?.Value ?? ""; user.isGoogle = true; string iconUri = me.Photos.FirstOrDefault()?.Url; if (string.IsNullOrEmpty(iconUri)) { Debug.LogException(new UserInfoError("Returned UserInfo contained no icon URI.")); } else if (!forTesting) // Not necessary yet when unit-testing { user.icon = await ImageUtils.DownloadTextureAsync(SetImageUrlOptions(iconUri)); } // Assume if the texture is 8x8 that the texture couldn't be decoded, and put our own in. // See b/62269743. Also use this texture if there is no user icon. if (user.icon == null || user.icon.width == 8 && user.icon.height == 8) { user.icon = m_LoggedInTexture; } return(user); }
public override async Task <ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode, CancellationToken taskCancellationToken) { if (string.IsNullOrEmpty(authorizationCode.Code)) { var errorResponse = new TokenErrorResponse(authorizationCode); Logger.Info("Received an error. The response is: {0}", errorResponse); return(OnTokenError(errorResponse)); } Logger.Debug("Received \"{0}\" code", authorizationCode.Code); var returnUrl = Request.Url.ToString(); returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?")); //Asynchronously exchanges code with a token. var token = await Flow.ExchangeCodeForTokenAsync(UserId, authorizationCode.Code, returnUrl, taskCancellationToken).ConfigureAwait(false); //Constructs a new credential instance with access token var credential = new UserCredential(Flow, UserId, token); try { var peopleService = new PeopleServiceService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "< YOUR APP NAME >", }); #region Contacts PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "addresses,ageRanges,biographies,birthdays,calendarUrls," + "clientData,coverPhotos,emailAddresses,events,externalIds,genders,imClients," + "interests,locales,locations,memberships,metadata,miscKeywords,names,nicknames," + "occupations,organizations,phoneNumbers,photos,relations,sipAddresses,skills,urls,userDefined"; peopleRequest.SortOrder = PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum.LASTMODIFIEDDESCENDING; peopleRequest.PageSize = 1000; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); List <Person> connections = connectionsResponse.Connections as List <Person>; // get all pages while (!string.IsNullOrEmpty(connectionsResponse.NextPageToken)) { peopleRequest.PageToken = connectionsResponse.NextPageToken; connectionsResponse = peopleRequest.Execute(); connections.AddRange(connectionsResponse.Connections); } #endregion var model = connections.Where(x => x.EmailAddresses != null && x.EmailAddresses.Any()); return(View(model)); } catch (Exception exp) { Logger.Info("Received an error. The response is: {0}", exp.Message); return(View("Error")); } }
public async Task Login() { if (isAlreadyInLoginProcess || credential != null) { CancelLogin(); } else { isAlreadyInLoginProcess = true; source = new CancellationTokenSource(new TimeSpan(0, 1, 0)); token = source.Token; FileStream stream = new FileStream(System.Windows.Forms.Application.StartupPath + "credentials.json", FileMode.Open, FileAccess.Read); string credPath = "token.json"; await Task.Run(() => { try { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "NotesieveDesktopUser", token, new FileDataStore(credPath, true)).Result; } catch (System.AggregateException e) { if (token.IsCancellationRequested) { //Операция прервана } else { OnError?.Invoke(e.InnerException + " " + e.Message); } isAlreadyInLoginProcess = false; } catch (System.Net.Http.HttpRequestException e) { isAlreadyInLoginProcess = false; OnSyncStateChanged?.Invoke(gSyncState.eFailed); OnError?.Invoke("Проблема с интрнєт-соединением.\nВы можете продолжать использовать Notesieve но временно, не сможете его синхронизировать."); } }); if (credential == null) { isAlreadyInLoginProcess = false; OnLoginFailed?.Invoke(); } else { try { isAlreadyInLoginProcess = false; PeopleServiceService peopleService = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); isLogin = true; PeopleResource.GetRequest peopleRequest = peopleService.People.Get("people/me"); peopleRequest.PersonFields = "names,photos"; Person profile = peopleRequest.Execute(); string name = profile.Names[0].DisplayName; string photo = profile.Photos[0].Url; OnLoginSuccsesfull?.Invoke(name, photo); } catch (System.Net.Http.HttpRequestException e) { isAlreadyInLoginProcess = false; OnSyncStateChanged?.Invoke(gSyncState.eLostConnection); OnError?.Invoke("Проблема с интрнєт-соединением.\nВы можете продолжать использовать Notesieve но временно, не сможете его синхронизировать."); } } } }
public async Task <IActionResult> Contact() { string gCode = TempData["code"].ToString(); string ClientSecret = _config.GetValue <string>("GooglePoepleAPI:ClientSecret"); string ClientId = _config.GetValue <string>("GooglePoepleAPI:ClientId"); string userId = "userId"; const string dataStoreFolder = "googleApiStorageFile"; // create authorization code flow with clientSecrets GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore(dataStoreFolder), ClientSecrets = new ClientSecrets() { ClientId = ClientId, ClientSecret = ClientSecret } }); FileDataStore fileStore = new FileDataStore(dataStoreFolder); TokenResponse tokenResponse = await fileStore.GetAsync <TokenResponse>(userId); if (tokenResponse == null) { // token data does not exist for this user tokenResponse = await authorizationCodeFlow.ExchangeCodeForTokenAsync( userId, // user for tracking the userId on our backend system gCode, "http://localhost:5000/people/", // redirect_uri can not be empty. Must be one of the redirects url listed in your project in the api console CancellationToken.None); } UserCredential userCredential = new UserCredential(authorizationCodeFlow, userId, tokenResponse); var service = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = "VAapps", }); ContactGroupsResource groupsResource = new ContactGroupsResource(service); ContactGroupsResource.ListRequest listRequest = groupsResource.List(); ListContactGroupsResponse response = listRequest.Execute(); List <string> listOnView = new List <string>(); foreach (ContactGroup group in response.ContactGroups) { listOnView.Add("Groups: " + group.FormattedName); } Google.Apis.PeopleService.v1.PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses,phoneNumbers"; peopleRequest.SortOrder = (Google.Apis.PeopleService.v1.PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum) 1; peopleRequest.PageSize = 1999; ListConnectionsResponse people = peopleRequest.Execute(); // are: * addresses * ageRanges * biographies * birthdays * braggingRights * coverPhotos // * emailAddresses * events * genders * imClients * interests * locales * memberships // * metadata * names * nicknames * occupations * organizations * phoneNumbers * // photos * relations * relationshipInterests * relationshipStatuses * residences // * sipAddresses * skills * taglines * urls * userDefined var me = service.People.Get("people/me"); me.PersonFields = "names,emailAddresses,phoneNumbers,birthdays,coverPhotos,metadata,events"; var aboutMe = me.Execute(); ViewBag.AboutMe = aboutMe; ViewBag.ContactList = people.Connections; return(View()); }
/* * public GService() * { * try * { * // Get active credential * string credPath = "credentials.json"; * * var json = File.ReadAllText(credPath); * PersonalServiceAccountCred cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json); // "personal" service account credential * * // Create an explicit ServiceAccountCredential credential * var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email) * { * Scopes = Scopes * }.FromPrivateKey(cr.private_key)); * * * * GService.service = new CalendarService(new BaseClientService.Initializer() * { * HttpClientInitializer = xCred, * ApplicationName = ApplicationName, * * }); * * peopleService = new PeopleServiceService(new BaseClientService.Initializer() * { * HttpClientInitializer = xCred, * ApplicationName = ApplicationName, * }); * * Attendee a = new Attendee(); * Calendarss c = new Calendarss(); * Eventss e = new Eventss(); * } * catch (Exception e) * { * Console.Write(e.Message); * } * } */ public GService() { //initiation of services UserCredential credential; /* * using (var stream = new FileStream(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "credentials.json"), FileMode.Open, FileAccess.Read)) * { * // The file token.json stores the user's access and refresh tokens, and is created * // automatically when the authorization flow completes for the first time. * string credPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "token.json"); * credential = GoogleWebAuthorizationBroker.AuthorizeAsync( * GoogleClientSecrets.Load(stream).Secrets, * Scopes, * "admin", * CancellationToken.None, * new FileDataStore(credPath, true)).Result; * Console.WriteLine("Credential file saved to: " + credPath); * }*/ using (var stream = new FileStream(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "credentials.json"), FileMode.Open, FileAccess.Read)) { var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GoogleClientSecrets.Load(stream).Secrets, Scopes = Scopes, }); var token = new TokenResponse { AccessToken = ConfigurationManager.AppSettings["g_access_token"].ToString(), RefreshToken = ConfigurationManager.AppSettings["g_refresh_token"].ToString() }; credential = new UserCredential(flow, Environment.UserName, token); } GService.service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); peopleService = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //accolating services to classes Attendee a = new Attendee(); Calendarss c = new Calendarss(); Eventss e = new Eventss(); service.CalendarList.Watch(new Channel() { Id = "calendar.watch.", Type = "web_hook", Address = "http://dtsl.ehb.be/~bo.bracquez/webhook.php", }); }