using System; using Newtonsoft.Json.Linq; /// /// Contains static methods that allow to extract user's information from a /// instance retrieved from Google after a successful authentication process. /// public static class GoogleHelper { /// /// Gets the Google user ID. /// public static string GetId(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value("id"); } /// /// Gets the user's name. /// public static string GetName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value("displayName"); } /// /// Gets the user's given name. /// public static string GetGivenName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetValue(user, "name", "givenName"); } /// /// Gets the user's family name. /// public static string GetFamilyName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetValue(user, "name", "familyName"); } /// /// Gets the user's profile link. /// public static string GetProfile(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value("url"); } /// /// Gets the user's email. /// public static string GetEmail(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetFirstValue(user, "emails", "value"); } // Get the given subProperty from a property. private static string TryGetValue(JObject user, string propertyName, string subProperty) { JToken value; if (user.TryGetValue(propertyName, out value)) { var subObject = JObject.Parse(value.ToString()); if (subObject != null && subObject.TryGetValue(subProperty, out value)) { return value.ToString(); } } return null; } #if GoogleApisAuthOAuth2 public static ServiceAccountCredential GetGoogleApiCredentials (string[] scopes) { String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE"; string private_key = Startup.GoogleSettings.Account.private_key; string secret = Startup.GoogleSettings.ClientSecret; var certificate = new X509Certificate2(@"key.p12", secret, X509KeyStorageFlags.Exportable); return new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); } #endif // Get the given subProperty from a list property. private static string TryGetFirstValue(JObject user, string propertyName, string subProperty) { JToken value; if (user.TryGetValue(propertyName, out value)) { var array = JArray.Parse(value.ToString()); if (array != null && array.Count > 0) { var subObject = JObject.Parse(array.First.ToString()); if (subObject != null) { if (subObject.TryGetValue(subProperty, out value)) { return value.ToString(); } } } } return null; } }