/// <summary>Get a full email address, if not already provided.</summary>
        protected string GetFullEmailAddress(string account, AuthenticatedUserInfo authInfo)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return(null);
            }

            //assume an address already containing the @ symbol is already a full email address
            if (account.Contains("@"))
            {
                return(account);
            }
            else
            {
                var domain = string.Empty;

                //we don't have a domain. first try the originally provided domain
                if (!string.IsNullOrWhiteSpace(authInfo.originalDomain))
                {
                    domain = authInfo.originalDomain;
                }
                else if (!string.IsNullOrWhiteSpace(authInfo.domain))
                {
                    domain = authInfo.domain;
                }
                else
                {
                    domain = OAuth2Base.CheckDomain();
                }

                //will return null if acct or domain is blank
                return(Utils.GetFullEmailAddress(account, domain));
            }
        }
 protected override void ProcessRecord()
 {
     if (ShouldProcess(ServiceAccountId, "Set-GShellServiceAccount"))
     {
         OAuth2Base.SetServiceAccount(Domain, ServiceAccountId, CertificatePath, KeyPassword);
     }
 }
        /// <summary>
        /// Store a token.
        /// </summary>
        /// <remarks>
        /// This will occur as a result of either one of two scenarios. First, it will occur when first authorizing
        /// a user against Google in which case a brand new token is returned. Second, when a service attempts to
        /// use a token to make an API call and fails due to the token being expired.
        ///
        /// While this overall class is a requirement for the Google APIs, it does not allow for enough information
        /// to store tokens in gShell (three strings - Domain, User, Api). As such, we must store that information
        /// elsewhere for use when storing. Similarly, if the Domain or User is missing, we must make a call to the
        /// OAuth service to gather that from the authenticating user's account.
        ///
        /// We can also be almost 100% sure that T is going to be a TokenResponse, at least at the time of writing.
        /// </remarks>
        public Task StoreAsync <T>(string key, T value)
        {
            TokenResponse tokenResponse = value as TokenResponse; //null if not actually a TokenResponse

            //If we're authenticating we have to delay storing the token so that we can get the user info from google,
            // which uses information that is only created once authentication finishes. So, we toggle this off after
            // and then call this again.
            if (OAuth2Base.IsAuthenticating)
            {
                OAuth2Base.AuthTokenTempSwap = tokenResponse;
            }
            else
            {
                if (tokenResponse != null)
                {
                    string tokenString = NewtonsoftJsonSerializer.Instance.Serialize(value);

                    //This should only matter when authenticating; if no tokens were able to be prefetched, these will
                    // be blank. When called from a service, we will have authenticated already.
                    if (OAuth2Base.currentAuthInfo.domain == null || OAuth2Base.currentAuthInfo.userName == null)
                    {
                        OAuth2Base.SetAuthenticatedUserInfo();
                    }

                    OAuth2Base.SaveToken(tokenString, tokenResponse);
                }
                else
                {
                    throw (new FormatException(string.Format(
                                                   "The API Authorization Token was received in an unexpected format: {0}.", typeof(T).ToString())));
                }
            }

            return(TaskEx.Delay(0));
        }
 public UserOAuthMapping GetUserOauthMapping(OAuth2Base current, int id)
 {
     return(new UserOAuthMapping()
     {
         UserId = id,
         AppId = current.openID,
         IsDeleted = false
     });
 }
 public UserInfo GetUser(OAuth2Base current, string pwd)
 {
     return(new UserInfo()
     {
         Avatar = current.headUrl.TryToString().Replace(@"\/", @"/"),
         UserName = current.nickName,
         NickName = current.nickName,
         CreateTime = DateTime.Now,
         RoleId = PubEnum.RoleType.User.TryToInt(),
         Password = pwd
     });
 }
        protected string GetFullEmailAddress(string account, string domain)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                domain = OAuth2Base.CheckDomain();
                if (string.IsNullOrWhiteSpace(domain))
                {
                    return(null);
                }
            }

            return(Utils.GetFullEmailAddress(account, domain));
        }
Exemple #7
0
        public static OAuth2Base CreateProvider(SNSProvider provider)
        {
            OAuth2Base oAuth2 = null;

            switch (provider)
            {
            case SNSProvider.Kakao:
                oAuth2 = KakaoOAuth2.Instance;
                break;
            }

            return(oAuth2);
        }
        public bool LoginWithSNS(SNSProvider provider)
        {
            try
            {
                oAuth2 = OAuth2ProviderFactory.CreateProvider(provider);

                var authenticator = new OAuth2Authenticator(
                    oAuth2.ClientId,
                    oAuth2.ClientSecret,
                    oAuth2.Scope,
                    oAuth2.AuthorizationUri,
                    oAuth2.RedirectUri,
                    oAuth2.RequestTokenUri,
                    null,
                    oAuth2.IsUsingNativeUI);

                authenticator.Completed += async(s, e) =>
                {
                    //var auth2Authenticator = s as OAuth2Authenticator;
                    if (e.IsAuthenticated)
                    {
                        // If the user is authenticated, request their basic user data from Google
                        // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
                        var user = await oAuth2.GetUserInfoAsync(e.Account);

                        //AppSettings.User = user;
                        user.SaveUserInfo();
                        MessagingCenter.Send(user, MessengerKeys.AuthenticationRequested, true);
                        //Debug.WriteLine("Authentication Success");
                    }
                };
                authenticator.Error += (s, e) =>
                {
                    //Debug.WriteLine("Authentication error: " + e.Message);
                };

                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);
            }
            catch (Exception ex)
            {
                //Debug.WriteLine("Login Error : " + ex.Message);

                return(false);
            }

            return(true);
        }
        public async Task <bool> UserIsAuthenticatedAndValidAsync()
        {
            if (!IsAuthenticated)
            {
                return(false);
            }
            else if (!AuthenticatedUser.LoggedInWithSNSAccount)
            {
                return(true);
            }
            else
            {
                bool refreshSucceded = false;

                oAuth2 = OAuth2ProviderFactory.CreateProvider(AuthenticatedUser.Provider);

                try
                {
                    var utcNow = DateTime.UtcNow.AddMinutes(30);

                    if (AuthenticatedUser.ExpiresIn < utcNow)
                    {
                        var(isRefresh, user) = await oAuth2.RefreshTokenAsync(AuthenticatedUser);

                        if (isRefresh)
                        {
                            user.SaveUserInfo();
                        }
                        else
                        {
                            UserInfo.RemoveUserInfo();
                        }

                        refreshSucceded = isRefresh;
                    }
                    else
                    {
                        refreshSucceded = true;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Error with refresh attempt: {ex}");
                }

                return(refreshSucceded);
            }
        }
Exemple #10
0
        public static OAuth2Base CreateProvider(SNSProvider provider)
        {
            OAuth2Base oAuth2 = KakaoOAuth2.Instance;;

            /*
             * 카카오 이외에 다른 OAuth2 형태의 인증 철차시 사용
             * switch (provider)
             * {
             *  case SNSProvider.Kakao:
             *      oAuth2 = KakaoOAuth2.Instance;
             *      break;
             * }
             */

            return(oAuth2);
        }
Exemple #11
0
        /// <summary>
        /// Build the service and return the domain the service is working on.
        /// </summary>
        public AuthenticatedUserInfo BuildService(AuthenticatedUserInfo authInfo, string serviceAccountUser = null)
        {
            if (authInfo == null) {return null;}

            if (string.IsNullOrWhiteSpace(serviceAccountUser))
            {
                if (!services.ContainsKey(authInfo))
                {
                    //this sets the OAuth2Base current domain and default domain, if necessary
                    T service = CreateNewService(OAuth2Base.GetAppName(apiNameAndVersion), authInfo);

                    //current domain should be set at this point 
                    if (authInfo.domain == "gmail.com" && !worksWithGmail)
                    {
                        throw new Exception("This Google API is not available for a Gmail account.");
                    }
                    else
                    {
                        services.Add(authInfo, service);
                    }
                }
            }
            else
            {
                if (!serviceAccountServices.ContainsKey(authInfo))
                {
                    serviceAccountServices.Add(authInfo, new Dictionary<string,T>());
                }

                if (!serviceAccountServices[authInfo].ContainsKey(serviceAccountUser))
                {
                    T service = CreateNewService(OAuth2Base.GetAppName(apiNameAndVersion), authInfo, serviceAccountUser);

                    if (authInfo.domain == "gmail.com" && !worksWithGmail)
                    {
                        throw new Exception("This Google API is not available for a Gmail account.");
                    }
                    else
                    {
                        serviceAccountServices[authInfo].Add(serviceAccountUser, service);
                    }
                }
            }

            return authInfo;
        }
Exemple #12
0
        public AuthenticatedUserInfo ChooseScopesAndAuthenticate(string api, string version, ClientSecrets secrets)
        {
            var info = new AuthenticatedUserInfo()
            {
                apiNameAndVersion = api + ":" + version,
                scopes            = ChooseScopes(api, version)
            };

            string script = "Read-Host '\nYou will now authenticate for this API. Press any key to continue'";
            Collection <PSObject> results = invokablePSInstance.InvokeCommand.InvokeScript(script);

            //Now, authenticate.
            info = OAuth2Base.GetAuthTokenFlow(info, secrets, force: true);

            PrintPretty(string.Format("{0}:{1} has been authenticated and saved.", api, version), "green");

            return(info);
        }
        private void ImgBtn_facebookLogin_Clicked(object sender, EventArgs e)
        {
            OAuth2Base oAuth2 = null;

            oAuth2 = FacebookOAuth2.Instance;

            var authenticator = new OAuth2Authenticator(
                oAuth2.ClientId,
                oAuth2.ClientSecret,
                oAuth2.Scope,
                oAuth2.AuthorizationUri,
                oAuth2.RedirectUri,
                oAuth2.RequestTokenUri,
                null,
                oAuth2.IsUsingNativeUI);

            authenticator.Completed += async(s, ee) =>
            {
                if (ee.IsAuthenticated)
                {
                    var user = await oAuth2.GetUserInfoAsync(ee.Account);

                    string name  = user.Name;
                    string email = user.email;
                    string Id    = user.Id;

                    RegisterResultCheck(name, email, "facebook_" + Id);

                    //await Navigation.PushAsync(new TabPage());

                    Debug.WriteLine("Authentication Success");
                }
            };
            authenticator.Error += (s, ee) =>
            {
                Debug.WriteLine("Authentication error: " + ee.Message);
            };

            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();

            presenter.Login(authenticator);
        }
        public Task LoginWithSNSAsync(SNSProvider provider)
        {
            try
            {
                oAuth2 = OAuth2ProviderFactory.CreateProvider(provider);
                var authenticator = new OAuth2Authenticator(
                    oAuth2.ClientId,
                    oAuth2.ClientSecret,
                    oAuth2.Scope,
                    oAuth2.AuthorizationUri,
                    oAuth2.RedirectUri,
                    oAuth2.RequestTokenUri,
                    null,
                    oAuth2.IsUsingNativeUI);

                authenticator.Completed += async(s, e) =>
                {
                    if (e.IsAuthenticated)
                    {
                        var user = await oAuth2.GetUserInfoAsync(e.Account);

                        AppSettings.User = user;
                        MessagingCenter.Send(user, MessengerKey.AuthenticationRequested, true);
                        Debug.WriteLine("Authentication Success");
                    }
                };
                authenticator.Error += (s, e) =>
                {
                    Debug.WriteLine("Authentication error: " + e.Message);
                };

                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Login Error : " + ex.Message);
                return(Task.FromResult(false));
            }
            return(Task.FromResult(true));
        }
        public static OAuth2Base CreateProvider(SNSProvider provider)
        {
            OAuth2Base oAuth2 = null;

            switch (provider)
            {
            case SNSProvider.Kakao:
                oAuth2 = KakaoOAuth2.Instance;
                break;

            case SNSProvider.Line:
                //oAuth2 = LineOAuth2.Instance;
                break;

            case SNSProvider.Facebook:
                //oAuth2 = FacebookOAuth2.Instance;
                break;
            }

            return(oAuth2);
        }
Exemple #16
0
        public AuthenticatedUserInfo AuthenticatePreChosenScopes(string api, string version, ClientSecrets secrets,
                                                                 ScopeSelectionTypes PreSelectScopes = ScopeSelectionTypes.None)
        {
            if (PreSelectScopes == ScopeSelectionTypes.None)
            {
                return(ChooseScopesAndAuthenticate(api, version, secrets));
            }
            else
            {
                Data.RestDescription restDescription = apis.RestData(api, version);

                HashSet <string> scopes = new HashSet <string>();

                switch (PreSelectScopes)
                {
                case ScopeSelectionTypes.ReadOnly:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys.Where(x => x.Contains("readonly")));
                    break;

                case ScopeSelectionTypes.ReadWrite:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys.Where(x => !x.Contains("readonly")));
                    break;

                default:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys);
                    break;
                }

                var authUserInfo = new AuthenticatedUserInfo()
                {
                    apiNameAndVersion = api + ":" + version,
                    scopes            = CheckForRequiredScope(scopes)
                };

                AuthenticatedUserInfo info = OAuth2Base.GetAuthTokenFlow(authUserInfo, secrets, force: true);

                return(info);
            }
        }
Exemple #17
0
 /// <summary>
 /// Authenticates the given domain and creates a service for it, if necessary. 
 /// The process of authenticating will update the default and current domains.
 /// </summary>
 public AuthenticatedUserInfo Authenticate(AuthenticatedUserInfo authUserInfo, ClientSecrets secrets)
 {
     return OAuth2Base.Authenticate(authUserInfo, secrets);
 }
        /// <summary>Creates a new reports_v1.Reports service.</summary>
        /// <param name="domain">The domain to which this service will be authenticated.</param>
        /// <param name="authInfo">The authenticated AuthInfo for this user and domain.</param>
        /// <param name="gShellServiceAccount">The optional email address the service account should impersonate.</param>

        protected override reports_v1.ReportsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
        {
            return(new reports_v1.ReportsService(OAuth2Base.GetInitializer(domain, authInfo)));
        }
 protected override emailsettings_v1.EmailsettingsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
 {
     return(new emailsettings_v1.EmailsettingsService(OAuth2Base.GetGdataInitializer(domain, authInfo)));
 }
        /// <summary>Creates a new v1.GroupsMigration service.</summary>
        /// <param name="domain">The domain to which this service will be authenticated.</param>
        /// <param name="authInfo">The authenticated AuthInfo for this user and domain.</param>
        /// <param name="gShellServiceAccount">The optional email address the service account should impersonate.</param>

        protected override v1.GroupsMigrationService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
        {
            return(new v1.GroupsMigrationService(OAuth2Base.GetInitializer(domain, authInfo)));
        }
        /// <summary>Determines if the user needs to be prompted to select the scopes.</summary>
        /// <remarks>
        /// Api is derived from the class that inherits this. User is the domain's default user. Returns null if scopes
        /// already exist since they'll be pulled up during authentication anyways.
        /// </remarks>
        public AuthenticatedUserInfo EnsureScopesExist(string GAuthId, HashSet <string> forcedScopes = null)
        {
            var results = new AuthenticatedUserInfo();

            string domain = null;
            string user   = null;

            bool gauthProvided = false;

            if (!string.IsNullOrWhiteSpace(GAuthId))
            {
                gauthProvided = true;

                if (GAuthId.Contains("@")) //user probably specified a full email address
                {
                    string gauthUser = GetUserFromEmail(GAuthId);
                    results.originalUser = gauthUser;

                    string gauthDomain = GetDomainFromEmail(GAuthId);
                    results.originalDomain = gauthDomain;

                    if (OAuth2Base.infoConsumer.DomainExists(gauthDomain))
                    {
                        domain = gauthDomain;

                        if (OAuth2Base.infoConsumer.UserExists(gauthDomain, gauthUser))
                        {
                            user = gauthUser; //else leave null - make them auth for that user since they specified it
                        }
                    }
                }
                else //either just a domain, or a user
                {
                    //check if it is a domain
                    if (OAuth2Base.infoConsumer.DomainExists(GAuthId))
                    {
                        domain = GAuthId;
                        results.originalDomain = GAuthId;
                        user = OAuth2Base.infoConsumer.GetDefaultUser(GAuthId); //could be null
                    }
                    else //not a domain that is saved
                    {
                        //try the default domain's users first, as a matter of best practice
                        string defaultDomain = OAuth2Base.infoConsumer.GetDefaultDomain();

                        if (!string.IsNullOrWhiteSpace(defaultDomain))
                        {
                            var users = OAuth2Base.infoConsumer.GetAllUsers(defaultDomain);

                            if (users.Select(x => x.userName).Contains(GAuthId))
                            {
                                domain = defaultDomain;
                                user   = GAuthId;
                                results.originalUser = GAuthId;
                            }
                            else //check other domains, if any
                            {
                                var domains = OAuth2Base.infoConsumer.GetAllDomains();

                                foreach (var domainObj in domains)
                                {
                                    users = OAuth2Base.infoConsumer.GetAllUsers(domainObj.domain);

                                    if (users.Select(x => x.userName).Contains(GAuthId))
                                    {
                                        domain = domainObj.domain;
                                        user   = GAuthId;
                                        results.originalUser = GAuthId;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //****************//

            if (string.IsNullOrWhiteSpace(domain) && !gauthProvided)
            {
                //If the domain or user are missing, see if we can fill it in using the defaults
                domain = OAuth2Base.CheckDomain(domain);
                if (domain != null)
                {
                    user = OAuth2Base.CheckUser(domain, user);
                }
            }

            //now find out if that domain has a parent domain if we don't have a user provided even by default
            if (!string.IsNullOrWhiteSpace(domain) && string.IsNullOrWhiteSpace(user) &&
                !string.IsNullOrWhiteSpace(OAuth2Base.infoConsumer.GetDomain(domain).parentDomain))
            {
                var domainParent = OAuth2Base.infoConsumer.GetDomainMainParent(domain);
                if (domainParent != domain)
                {
                    domain = domainParent;
                    user   = OAuth2Base.infoConsumer.GetDefaultUser(domain);
                }
            }

            //****************//

            results.userName = user;
            results.domain   = domain;

            //if no domain is returned, none was provided or none was found as default.
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(user) ||
                !OAuth2Base.infoConsumer.TokenAndScopesExist(domain, user, apiNameAndVersion))
            {
                string domainText = null;

                if (!string.IsNullOrWhiteSpace(domain))
                {
                    domainText = "is for domain (" + domain + "), which ";
                }

                WriteWarning(string.Format("The Cmdlet you've just started {0}doesn't"
                                           + " seem to have any saved authentication for this API ({1}). In order to continue you'll need to"
                                           + " choose which permissions gShell can use for this API.", domainText, apiNameAndVersion));

                string chooseApiNowScript = "Read-Host '\nWould you like to choose your API scopes now? y or n'";
                Collection <PSObject> chooseApiNowResults = this.InvokeCommand.InvokeScript(chooseApiNowScript);
                string result = chooseApiNowResults[0].ToString().Substring(0, 1).ToLower();
                if (result == "y")
                {
                    ScopeHandlerBase scopeBase = new ScopeHandlerBase(this);

                    results.scopes = scopeBase.ChooseScopes(
                        apiNameAndVersion.Split(':')[0],
                        apiNameAndVersion.Split(':')[1],
                        forcedScopes);

                    if (!string.IsNullOrWhiteSpace(GAuthId))
                    {
                        results.domain         = GetDomainFromEmail(GAuthId);
                        results.originalDomain = results.domain;
                    }

                    return(results);
                }
                else
                {
                    WriteWarning("No scopes were chosen. You can run this process manually with Invoke-ScopeManager later.");
                }
            }
            else
            {
                results.scopes = OAuth2Base.infoConsumer.GetTokenInfo(domain, user, apiNameAndVersion).scopes;
                return(results);
            }

            return(results);
        }
Exemple #22
0
 /// <summary>
 /// Initialize and return a new DiscoveryService
 /// </summary>
 protected override discovery_v1.DiscoveryService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string serviceAcctUser)
 {
     return(new discovery_v1.DiscoveryService(OAuth2Base.GetInitializer()));
 }
Exemple #23
0
        /// <summary>Creates a new adminsettings_v1.Adminsettings service.</summary>
        /// <param name="domain">The domain to which this service will be authenticated.</param>
        /// <param name="authInfo">The authenticated AuthInfo for this user and domain.</param>
        /// <param name="gShellServiceAccount">The optional email address the service account should impersonate.</param>

        protected override adminsettings_v1.AdminsettingsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string serviceAccountUser = null)
        {
            return(new adminsettings_v1.AdminsettingsService(OAuth2Base.GetGdataInitializer(domain, authInfo)));
        }
Exemple #24
0
 protected override sharedcontacts_v3.SharedcontactsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
 {
     return(new sharedcontacts_v3.SharedcontactsService(OAuth2Base.GetGdataInitializer(domain, authInfo)));
 }
        /// <summary>Creates a new datatransfer_v1.DataTransfer service.</summary>
        /// <param name="domain">The domain to which this service will be authenticated.</param>
        /// <param name="authInfo">The authenticated AuthInfo for this user and domain.</param>
        /// <param name="gShellServiceAccount">The optional email address the service account should impersonate.</param>

        protected override datatransfer_v1.DataTransferService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
        {
            return(new datatransfer_v1.DataTransferService(OAuth2Base.GetInitializer(domain, authInfo)));
        }