// called from game thread
        public void Authenticate(System.Action <bool> callback, bool silent)
        {
            if (mAuthState != AuthState.NoAuth)
            {
                Logger.w("Authenticate() called while an authentication process was active. " +
                         mAuthState);
                mAuthCallback = callback;
                return;
            }

            // make sure the helper GameObject is ready (we use it for the auth callback)
            Logger.d("Making sure PlayGamesHelperObject is ready.");
            PlayGamesHelperObject.CreateObject();
            Logger.d("PlayGamesHelperObject created.");

            mSilentAuth = silent;
            Logger.d("AUTH: starting auth process, silent=" + mSilentAuth);
            RunOnUiThread(() => {
                switch (mGHManager.State)
                {
                case GameHelperManager.ConnectionState.Connected:
                    Logger.d("AUTH: already connected! Proceeding to achievement load phase.");
                    mAuthCallback = callback;
                    DoInitialAchievementLoad();
                    break;

                case GameHelperManager.ConnectionState.Connecting:
                    Logger.d("AUTH: connection in progress; auth now pending.");
                    mAuthCallback = callback;
                    mAuthState    = AuthState.AuthPending;
                    // we'll do the right thing in OnSignInSucceeded/Failed
                    break;

                default:
                    mAuthCallback = callback;
                    if (mSilentAuth)
                    {
                        Logger.d("AUTH: not connected and silent=true, so failing.");
                        mAuthState = AuthState.NoAuth;
                        InvokeAuthCallback(false);
                    }
                    else
                    {
                        Logger.d("AUTH: not connected and silent=false, so starting flow.");
                        mAuthState = AuthState.InProgress;
                        mGHManager.BeginUserInitiatedSignIn();
                        // we'll do the right thing in OnSignInSucceeded/Failed
                    }
                    break;
                }
            });
        }
Example #2
0
        public AuthResponse <string> Login(string password)
        {
            string    token     = _WebServer.CreateToken(password);
            AuthState authState = _WebServer.Login(Context.ConnectionId, token);

            if (authState == AuthState.Authenticated)
            {
                Groups.Add(Context.ConnectionId, GROUP_AUTHED);
                return(AuthResponse <string> .Authenticated(token));
            }
            Groups.Remove(Context.ConnectionId, GROUP_AUTHED);
            return(AuthResponse <string> .NotAuthenticated(authState));
        }
        public Uri AuthenticationUri(string redirectUri, IList<string> scopes)
        {
            var uriBuilder = new StringBuilder();
            uriBuilder.Append(redirectUri);

            uriBuilder.Append("?code=FakeCode&");

            var state = new AuthState { Scopes = scopes };
            uriBuilder.Append("&state=");
            uriBuilder.Append(state.ToUrlEncoded());

            return new Uri(uriBuilder.ToString());
        }
        private Task <CodeResponse> RequestToken(AuthResponse response, AuthState state)
        {
            // TODO: review the specs
            return(HandleErrors(nameof(RequestToken), async() =>
            {
                var request = await RequestBuilder.CreateCodeRequest(state, response);
                var httpResponse = await HttpClient.PostAsync(request.Url, request.Content);
                var content = await httpResponse.Content.ReadAsStringAsync();

                return httpResponse.IsSuccessStatusCode
                    ? Json.Deserialize <CodeResponse>(content, "code token response")
                    : throw Logger.Exception(FormatCodeErrors(content, httpResponse));
            }));
Example #5
0
        private AuthResponse Authenticate(string token, Action callback)
        {
            AuthState authState = _WebServer.CheckAuth(Context.ConnectionId, token);

            if (authState == AuthState.Authenticated)
            {
                Groups.Add(Context.ConnectionId, GROUP_AUTHED);
                callback.Invoke();
                return(AuthResponse.Authenticated);
            }
            Groups.Remove(Context.ConnectionId, GROUP_AUTHED);
            return(AuthResponse.NotAuthenticated(authState));
        }
        public ClientState(AuthStateProvider authStateProvider, IStateFactory stateFactory)
        {
            AuthStateProvider = authStateProvider;
            SessionResolver   = AuthStateProvider.SessionResolver;

            User = stateFactory.NewLive <User>(
                o => o.WithUpdateDelayer(0, 1),
                async(_, cancellationToken) => {
                var authState = await AuthState.UseAsync(cancellationToken).ConfigureAwait(false);
                return(authState.User);
            });
            ChatUser = stateFactory.NewMutable(Result.Value <ChatUser?>(null));
        }
Example #7
0
 private void ToUnauthenticated()
 {
     lock (AuthStateLock)
     {
         mUser         = null;
         mFriends      = null;
         mAchievements = null;
         mAuthState    = AuthState.Unauthenticated;
         mTokenClient  = clientImpl.CreateTokenClient(true);
         PlayGamesHelperObject.RunOnGameThread(mOnSignOutCallback);
         mAuthGeneration++;
     }
 }
Example #8
0
        public AuthState Login(string connectionId, string token)
        {
            var conn = Clients.FirstOrDefault(c => c.Id == connectionId);

            if (conn == null)
            {
                return(AuthState.InvalidConnection);
            }

            AuthState authState = AuthState.Authenticated;

            // Check password
            string requiredPassword = Settings.Default.RequiredPassword;

            if (!string.IsNullOrEmpty(requiredPassword))
            {
                if (string.IsNullOrEmpty(token))
                {
                    authState |= AuthState.NoPassword;
                }
                else
                {
                    try
                    {
                        var payload = _JwtDecoder.DecodeToObject <TokenPayload>(token);
                        if (payload.Key != requiredPassword)
                        {
                            authState |= AuthState.NoPassword;
                        }
                    }
                    catch (SignatureVerificationException)
                    {
                        authState |= AuthState.NoPassword;
                    }
                }
            }

            // Check connection index against max connections
            if (Settings.Default.MaxSessions > 0 && Clients.IndexOf(conn) > Settings.Default.MaxSessions - 1)
            {
                authState |= AuthState.ExceedsMaxConnections;
            }

            // Check connection remote IP address against whitelist
            if (Settings.Default.IPWhitelist != null && Settings.Default.IPWhitelist.Count > 0 && !Settings.Default.IPWhitelist.Contains(conn.RemoteEndpoint.Address.ToString()))
            {
                authState |= AuthState.IPNotAllowed;
            }

            return(conn.AuthState = authState);
        }
Example #9
0
        private void InitializeGameServices()
        {
            lock (GameServicesLock) {
                if (mServices != null)
                {
                    return;
                }

                using (var builder = GameServicesBuilder.Create()) {
                    using (var config = CreatePlatformConfiguration(builder)) {
                        // We need to make sure that the invitation delegate is registered before the
                        // services object is initialized - otherwise we might miss a callback if
                        // the game was opened because of a user accepting an invitation through
                        // a system notification.
                        RegisterInvitationDelegate(mConfiguration.InvitationDelegate);

                        builder.SetOnAuthFinishedCallback(HandleAuthTransition);
                        builder.SetOnTurnBasedMatchEventCallback((eventType, matchId, match)
                                                                 => mTurnBasedClient.HandleMatchEvent(eventType, matchId, match));
                        builder.SetOnMultiplayerInvitationEventCallback(HandleInvitation);
                        if (mConfiguration.EnableSavedGames)
                        {
                            builder.EnableSnapshots();
                        }
                        mServices        = builder.Build(config);
                        mTurnBasedClient =
                            new NativeTurnBasedMultiplayerClient(this, new TurnBasedManager(mServices));

                        mTurnBasedClient.RegisterMatchDelegate(mConfiguration.MatchDelegate);

                        mRealTimeClient =
                            new NativeRealtimeMultiplayerClient(this, new RealtimeManager(mServices));

                        if (mConfiguration.EnableSavedGames)
                        {
                            mSavedGameClient =
                                new NativeSavedGameClient(new SnapshotManager(mServices));
                        }
                        else
                        {
                            mSavedGameClient = new UnsupportedSavedGamesClient(
                                "You must enable saved games before it can be used. " +
                                "See PlayGamesClientConfiguration.Builder.EnableSavedGames.");
                        }

                        mAppStateClient = CreateAppStateClient();
                        mAuthState      = AuthState.SilentPending;
                    }
                }
            }
        }
Example #10
0
        /// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(IHttpRequest request, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            AuthCache authCache = clientContext.GetAuthCache();

            if (authCache == null)
            {
                this.log.Debug("Auth cache not set in the context");
                return;
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return;
            }
            RouteInfo route  = clientContext.GetHttpRoute();
            HttpHost  target = clientContext.GetTargetHost();

            if (target.GetPort() < 0)
            {
                target = new HttpHost(target.GetHostName(), route.GetTargetHost().GetPort(), target
                                      .GetSchemeName());
            }
            AuthState targetState = clientContext.GetTargetAuthState();

            if (targetState != null && targetState.GetState() == AuthProtocolState.Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(target);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(target, authScheme, targetState, credsProvider);
                }
            }
            HttpHost  proxy      = route.GetProxyHost();
            AuthState proxyState = clientContext.GetProxyAuthState();

            if (proxy != null && proxyState != null && proxyState.GetState() == AuthProtocolState
                .Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(proxy);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
                }
            }
        }
Example #11
0
        private AuthState GetAuthState()
        {
            var pref      = _context.GetSharedPreferences(nameof(AuthService), FileCreationMode.Private);
            var stateJson = pref.GetString(nameof(AuthState), null);

            if (stateJson != null)
            {
                return(AuthState.JsonDeserialize(stateJson));
            }
            else
            {
                return(new AuthState());
            }
        }
Example #12
0
 /// <summary>
 /// Sends a request to the Keycloak server to perform token exchange.
 /// On successfully completing the token exchange the callback is invoked with the `openid` credentials for the user.
 /// Otherwise the callback is invoked with the error that occured during token exchange.
 /// </summary>
 /// <returns>The authorization flow.</returns>
 /// <param name="request">an openid authorisation request.</param>
 /// <param name="presentingViewController">The view controller from which to present the SafariViewController.</param>
 /// <param name="callback">a callback function that will be invoked when the token exchange is completed.</param>
 private IAuthorizationFlowSession startAuthorizationFlow(AuthorizationRequest request, UIViewController presentingViewController, OIDAuthFlowCallback callback)
 {
     return(AuthState.PresentAuthorizationRequest(request, presentingViewController, (authState, error) =>
     {
         if (authState == null || error != null)
         {
             callback(null, error);
         }
         else
         {
             callback(new OIDCCredential(authState), null);
         }
     }));
 }
Example #13
0
        async public static void updateUserInfo()
        {
            CloudBaseApp app   = CloudBaseApp.Init("59eb4700a3c34", 3000);
            AuthState    state = await app.Auth.GetAuthStateAsync();

            if (state == null)
            {
                // 匿名登录
                state = await app.Auth.SignInAnonymouslyAsync();
            }

            // 调用云函数
            FunctionResponse res = await app.Function.CallFunctionAsync("updateUserInfo", _userInfo);
        }
        private static void SuccessCallback(string token)
        {
            mAuthState = AuthState.None;

            // Clear action before calling, in case a callback results in overwriting these actions
            Action <string> toCall = mOnSuccess;

            mOnSuccess = null;

            if (toCall != null)
            {
                toCall(token);
            }
        }
        private static Principal GetAuthPrincipal(AuthState authState)
        {
            AuthScheme scheme = authState.GetAuthScheme();

            if (scheme != null && scheme.IsComplete() && scheme.IsConnectionBased())
            {
                Credentials creds = authState.GetCredentials();
                if (creds != null)
                {
                    return(creds.GetUserPrincipal());
                }
            }
            return(null);
        }
Example #16
0
 public void SignOut()
 {
     Logger.d("AndroidClient.SignOut");
     mSignOutInProgress = true;
     RunWhenConnectionStable(() => {
         Logger.d("Calling GHM.SignOut");
         mGHManager.SignOut();
         mAuthState         = AuthState.NoAuth;
         mUserId            = null;
         mUserDisplayName   = null;
         mSignOutInProgress = false;
         Logger.d("Now signed out.");
     });
 }
Example #17
0
        public async Task <ulong?> GetId()
        {
            if (AuthState == null)
            {
                return(null);
            }
            if (Info != null)
            {
                return(Info.Id);
            }
            Info = await AuthState.GetUserInfo();

            return(Info.Id);
        }
Example #18
0
        /// <summary>
        /// Authenticates the user using the Web Authentication Broker
        /// </summary>
        public async Task <bool> Authenticate()
        {
            // If we have an session key already no need to do anything
            if (State == AuthState.Authenticated)
            {
                return(true);
            }

            // request token and secret
            IRestResponse requestResponse = await RequestToken();

            // Parse oauth token and token secret
            var querystring = requestResponse.Content.ParseQueryString();

            if (querystring == null || querystring.Count != 2)
            {
                return(false);
            }

            MyShelfSettings.Instance.OAuthToken       = querystring["oauth_token"];
            MyShelfSettings.Instance.OAuthTokenSecret = querystring["oauth_token_secret"];

            // authenticate
            string goodreadsURL            = String.Format(Urls.AuthUrl, MyShelfSettings.Instance.OAuthToken);
            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(goodreadsURL), WebAuthenticationBroker.GetCurrentApplicationCallbackUri());

            if (result == null || result.ResponseStatus != WebAuthenticationStatus.Success)
            {
                return(false);
            }

            // request access token and secret
            IRestResponse accessResponse = await RequestAccessToken();

            // parse oauth access token and token secrets
            var querystring2 = accessResponse.Content.ParseQueryString();

            if (querystring2 == null || querystring2.Count != 2)
            {
                return(false);
            }

            MyShelfSettings.Instance.OAuthAccessToken       = querystring2["oauth_token"];
            MyShelfSettings.Instance.OAuthAccessTokenSecret = querystring2["oauth_token_secret"];

            State = AuthState.Authenticated;

            return(true);
        }
Example #19
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.state = AuthState.Generate();
            var builder = new UriBuilder("https", "id.twitch.tv");

            builder.Path = "oauth2/authorize";
            builder.AddQuery("client_id", client_id);
            builder.AddQuery("redirect_uri", redirect_uri);
            builder.AddQuery("response_type", useAuthFlow ? "code" : "token");
            builder.AddQuery("scope", "chat:read chat:edit whispers:read whispers:edit");
            builder.AddQuery("force_verify", "true");
            builder.AddQuery("state", this.state);
            Console.WriteLine(builder.Uri);
            this.Browser.Navigate(builder.Uri);
        }
Example #20
0
        async public static void UploadMgobeUserInfo(string gameId)
        {
            CloudBaseApp app   = CloudBaseApp.Init("59eb4700a3c34", 3000);
            AuthState    state = await app.Auth.GetAuthStateAsync();

            if (state == null)
            {
                // 匿名登录
                state = await app.Auth.SignInAnonymouslyAsync();
            }
            // 调用云函数
            FunctionResponse res = await app.Function.CallFunctionAsync("uploadServiceUser", new Dictionary <string, dynamic> {
                { "gameId", gameId }, { "serviceType", "mgobe" }
            });
        }
Example #21
0
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                var userData = await AuthState.GetAuthenticationStateAsync();

                string userName = userData?.User?.Identity?.Name;
                if (userData?.User?.Identity?.IsAuthenticated ?? false)
                {
                    var user = await PublicClient.GetOrAddUser(userName);

                    AppState.CurrentUser = user;
                }
            }
            await base.OnAfterRenderAsync(firstRender);
        }
Example #22
0
 public async Task <TokenRequest> CreateCodeRequest(AuthState state, AuthResponse response)
 {
     return(new TokenRequest
     {
         Url = await Metadata.TokenEndpoint(),
         Content = new FormUrlEncodedContent(new Dictionary <string, string>
         {
             ["grant_type"] = "authorization_code",
             ["client_id"] = state.ClientId,
             ["client_secret"] = Settings.ClientSecret, // TODO: should this be in the AthenticationParameters?
             ["code_verifier"] = state.CodeVerifier,
             ["code"] = response.Code,
             ["redirect_uri"] = state.RedirectUri
         })
     });
 }
Example #23
0
        public bool IsValidUser()
        {
            if (AuthState.IsLogin)
            {
                if (IsSet)
                {
                    return(Level == (AuthLevel)AuthState.User().Permission);
                }
                else
                {
                    return(true);
                }
            }

            return(false);
        }
Example #24
0
        private static AuthState GetAuthStateFromIntent(Intent intent)
        {
            if (!intent.HasExtra(EXTRA_AUTH_STATE))
            {
                throw new InvalidOperationException("The AuthState instance is missing in the intent.");
            }

            try
            {
                return(AuthState.JsonDeserialize(intent.GetStringExtra(EXTRA_AUTH_STATE)));
            }
            catch (JSONException ex)
            {
                throw new InvalidOperationException("The AuthState instance is missing in the intent.", ex);
            }
        }
Example #25
0
 // called (on the UI thread) by GameHelperManager to notify us that sign in failed
 internal void OnSignInFailed()
 {
     Logger.d("AndroidClient got OnSignInFailed.");
     if (mAuthState == AuthState.AuthPending)
     {
         // we have yet to start the auth flow
         if (mSilentAuth)
         {
             Logger.d("AUTH: Auth flow was pending, but silent=true, so failing.");
             mAuthState = AuthState.NoAuth;
             InvokeAuthCallback(false);
         }
         else
         {
             Logger.d("AUTH: Auth flow was pending and silent=false, so doing noisy auth.");
             mAuthState = AuthState.InProgress;
             mGHManager.BeginUserInitiatedSignIn();
         }
     }
     else if (mAuthState == AuthState.InProgress)
     {
         // authentication was in progress, but failed: notify callback
         Logger.d("AUTH: FAILED!");
         mAuthState = AuthState.NoAuth;
         InvokeAuthCallback(false);
     }
     else if (mAuthState == AuthState.LoadingAchs)
     {
         // we were loading achievements and got disconnected: notify callback
         Logger.d("AUTH: FAILED (while loading achievements).");
         mAuthState = AuthState.NoAuth;
         InvokeAuthCallback(false);
     }
     else if (mAuthState == AuthState.NoAuth)
     {
         // we will hit this case during the normal lifecycle (for example, Activity
         // was brought to the foreground and sign in has failed).
         Logger.d("Normal OnSignInFailed received.");
     }
     else if (mAuthState == AuthState.Done)
     {
         // we lost authentication (for example, the token might have expired,
         // or the user revoked it)
         Logger.e("Authentication has been lost!");
         mAuthState = AuthState.NoAuth;
     }
 }
            /**
             *                  http response rooting of boot.
             */
            private void OnBootResult(string tokenConnectionId, Dictionary <string, string> responseHeader, int responseCode, string resultData, string errorReason)
            {
                if (forceFailFirstBoot)
                {
                    responseCode = AuthSettings.FORCE_FAIL_FIRSTBOOT_CODE;
                    errorReason  = "failed by forceFailFirstBoot = true.";
                }

                autoya.HttpResponseHandling(
                    tokenConnectionId,
                    responseHeader,
                    responseCode,
                    resultData,
                    errorReason,
                    (succeededConId, succeededData) =>
                {
                    var tokenData = succeededData as string;

                    mainthreadDispatcher.Commit(OnBootSucceeded(responseHeader, tokenData));
                },
                    (failedConId, failedCode, failedReason, autoyaStatus) =>
                {
                    /*
                     *                              maintenance or auth failed is already handled.
                     */
                    if (autoyaStatus.inMaintenance || autoyaStatus.isAuthFailed)
                    {
                        return;
                    }

                    // other errors.

                    // reached to the max retry for boot access.
                    if (bootRetryCount == AuthSettings.AUTH_FIRSTBOOT_MAX_RETRY_COUNT)
                    {
                        Debug.Log("retry maxで死んでる");
                        authState = AuthState.BootFailed;
                        onBootFailed(failedCode, failedReason);
                        return;
                    }

                    bootRetryCount++;
                    mainthreadDispatcher.Commit(BootRetryCoroutine());
                }
                    );
            }
Example #27
0
        public void EnsureValidState(AuthResponse response, AuthState state)
        {
            if (response.State.IsEmpty())
            {
                throw Logger.Exception("No authentication state in response");
            }
            if (state == null)
            {
                throw Logger.Exception("Storage does not contain the authentication state");
            }
            if (state.State != response.State)
            {
                throw Logger.Exception("Authentication state does not match with response");
            }

            Logger.LogDebug("Authentication state is valid");
        }
Example #28
0
        static AuthState GetAuthStateFromIntent(Intent intent)
        {
            if (!intent.HasExtra(EXTRA_AUTH_STATE))
            {
                throw new InvalidOperationException("The AuthState instance is missing in the intent.");
            }

            try
            {
                return(AuthState.JsonDeserialize(intent.GetStringExtra(EXTRA_AUTH_STATE)));
            }
            catch (JSONException ex)
            {
                Console.WriteLine("Malformed AuthState JSON saved: " + ex);
                throw new InvalidOperationException("The AuthState instance is missing in the intent.", ex);
            }
        }
Example #29
0
            /// <exception cref="Apache.Http.HttpException"></exception>
            /// <exception cref="System.IO.IOException"></exception>
            public void Process(HttpWebRequest request, HttpContext context)
            {
                AuthState authState = (AuthState)context.GetAttribute(ClientContext.TargetAuthState
                                                                      );
                CredentialsProvider credsProvider = (CredentialsProvider)context.GetAttribute(ClientContext
                                                                                              .CredsProvider);
                HttpHost targetHost = (HttpHost)context.GetAttribute(ExecutionContext.HttpTargetHost
                                                                     );

                if (authState.GetAuthScheme() == null)
                {
                    AuthScope authScope = new AuthScope(targetHost.GetHostName(), targetHost.GetPort(
                                                            ));
                    authState.SetAuthScheme(new BasicScheme());
                    authState.SetCredentials(creds);
                }
            }
Example #30
0
        public async Task GetAuthorizationCode()
        {
            var issuer      = new NSUrl(kIssuer);
            var redirectURI = new NSUrl(kRedirectURI);

            Console.WriteLine($"Fetching configuration for issuer: {issuer}");

            try
            {
                // discovers endpoints
                var configuration = await AuthorizationService.DiscoverServiceConfigurationForIssuerAsync(issuer);

                Console.WriteLine($"Got configuration: {configuration}");

                string codeMethod    = @"plain";
                string code_verifier = AuthorizationRequest.GenerateCodeVerifier();
                string state         = AuthorizationRequest.GenerateState();

                // builds authentication request
                AuthorizationRequest request = new AuthorizationRequest(configuration, kClientID, null, Scope.OpenId, redirectURI, ResponseType.Code, state, code_verifier, code_verifier, codeMethod, null);

                // performs authentication request
                var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
                Console.WriteLine($"Initiating authorization request with scope: {request.Scope}");

                appDelegate.CurrentAuthorizationFlow = AuthState.PresentAuthorizationRequest(request, UIApplication.SharedApplication.KeyWindow.RootViewController, (authState, error) =>
                {
                    if (authState != null)
                    {
                        AuthState = authState;
                        Console.WriteLine($"Got authorization tokens. Access token: {authState.LastTokenResponse.AccessToken}");
                    }
                    else
                    {
                        Console.WriteLine($"Authorization error: {error.LocalizedDescription}");
                        AuthState = null;
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error retrieving discovery document: {ex}");
                AuthState = null;
            }
        }
Example #31
0
        private void HandleAuthTransition(Types.AuthOperation operation, Status.AuthStatus status)
        {
            GooglePlayGames.OurUtils.Logger.d("Starting Auth Transition. Op: " + operation + " status: " + status);
            lock (AuthStateLock)
            {
                switch (operation)
                {
                case Types.AuthOperation.SIGN_IN:
                    if (status == Status.AuthStatus.VALID)
                    {
                        uint currentAuthGeneration = mAuthGeneration;
                        mServices.AchievementManager().FetchAll(
                            results => PopulateAchievements(currentAuthGeneration, results));
                        mServices.PlayerManager().FetchSelf(
                            results => PopulateUser(currentAuthGeneration, results));
                    }
                    else
                    {
                        // Auth failed
                        // The initial silent auth failed - take note of that and
                        // notify any pending silent-auth callbacks. If there are
                        // additional non-silent auth callbacks pending, attempt to auth
                        // by popping the Auth UI.
                        mAuthState = AuthState.Unauthenticated;
                        GooglePlayGames.OurUtils.Logger.d(
                            "AuthState == " + mAuthState +
                            " calling auth callbacks with failure");

                        // Noisy sign-in failed - report failure.
                        Action <bool, string> localCallbacks = mPendingAuthCallbacks;
                        mPendingAuthCallbacks = null;
                        InvokeCallbackOnGameThread(localCallbacks, false, "Authentication failed");
                    }
                    break;

                case Types.AuthOperation.SIGN_OUT:
                    ToUnauthenticated();
                    break;

                default:
                    GooglePlayGames.OurUtils.Logger.e("Unknown AuthOperation " + operation);
                    break;
                }
            }
        }
        public Uri AuthenticationUri(string redirectUri, IList<string> scopes)
        {
            var uriBuilder = new StringBuilder();
            uriBuilder.Append("https://accounts.google.com/o/oauth2/auth");
            uriBuilder.Append("?scope=");
            var scopeSsv = string.Join(" ", scopes);
            uriBuilder.Append(HttpUtility.UrlEncode(scopeSsv));

            uriBuilder.Append("&redirect_uri=");
            uriBuilder.Append(HttpUtility.UrlEncode(redirectUri));

            uriBuilder.Append("&response_type=code");
            uriBuilder.Append("&client_id=");
            uriBuilder.Append(_clientId);

            var state = new AuthState { RedirectUri = redirectUri, Scopes = scopes };
            uriBuilder.Append("&state=");
            uriBuilder.Append(state.ToUrlEncoded());

            return new Uri(uriBuilder.ToString());
        }
 private void ToUnauthenticated() {
     lock (AuthStateLock) {
         mUser = null;
         mAchievements = null;
         mAuthState = AuthState.Unauthenticated;
         mAuthGeneration++;
     }
 }
    private void HandleAuthTransition(Types.AuthOperation operation, Status.AuthStatus status) {
        Logger.d("Starting Auth Transition. Op: " + operation + " status: " + status);
        lock (AuthStateLock) {
            switch (operation) {
                case Types.AuthOperation.SIGN_IN:
                    if (status == Status.AuthStatus.VALID) {
                        // If sign-in succeeded, treat any silent auth callbacks the same way
                        // we would treat loud ones.
                        if (mSilentAuthCallbacks != null) {
                            mPendingAuthCallbacks += mSilentAuthCallbacks;
                            mSilentAuthCallbacks = null;
                        }

                        uint currentAuthGeneration = mAuthGeneration;
                        mServices.AchievementManager().FetchAll(
                            results => PopulateAchievements(currentAuthGeneration, results));
                        mServices.PlayerManager().FetchSelf(
                            results => PopulateUser(currentAuthGeneration, results));
                    } else {
                        // Auth failed
                        if (mAuthState == AuthState.SilentPending) {
                            // The initial silent auth failed - take note of that and
                            // notify any pending silent-auth callbacks. If there are
                            // additional non-silent auth callbacks pending, attempt to auth
                            // by popping the Auth UI.
                            mSilentAuthFailed = true;
                            mAuthState = AuthState.Unauthenticated;
                            var silentCallbacks = mSilentAuthCallbacks;
                            mSilentAuthCallbacks = null;
                            InvokeCallbackOnGameThread(silentCallbacks, false);
                            if (mPendingAuthCallbacks != null) {
                                GameServices().StartAuthorizationUI();
                            }
                        } else {
                            // Noisy sign-in failed - report failure.
                            Action<bool> localCallbacks = mPendingAuthCallbacks;
                            mPendingAuthCallbacks = null;
                            InvokeCallbackOnGameThread(localCallbacks, false);
                        }
                    }
                    break;
                case Types.AuthOperation.SIGN_OUT:
                    mAuthState = AuthState.Unauthenticated;
                    break;
                default:
                    Logger.e("Unknown AuthOperation " + operation);
                    break;
            }
        }
    }
    void MaybeFinishAuthentication() {
        Action<bool> localCallbacks = null;

        lock (AuthStateLock) {
            // Only proceed if both the fetch-self and fetch-achievements callback have
            // completed.
            if (mUser == null || mAchievements == null) {
                Logger.d("Auth not finished. User="******" achievements=" + mAchievements);
                return;
            }

            Logger.d("Auth finished. Proceeding.");
            // Null out the pending callbacks - we will be invoking any pending ones.
            localCallbacks = mPendingAuthCallbacks;
            mPendingAuthCallbacks = null;
            mAuthState = AuthState.Authenticated;
        }

        if (localCallbacks != null) {
            Logger.d("Invoking Callbacks: " + localCallbacks);
            InvokeCallbackOnGameThread(localCallbacks, true);
        }
    }
    private void InitializeGameServices() {
        lock (GameServicesLock) {
            if (mServices != null) {
                return;
            }

            using (var builder = GameServicesBuilder.Create()) {
                using (var config = CreatePlatformConfiguration(builder)) {
                    // We need to make sure that the invitation delegate is registered before the
                    // services object is initialized - otherwise we might miss a callback if
                    // the game was opened because of a user accepting an invitation through
                    // a system notification.
                    RegisterInvitationDelegate(mConfiguration.InvitationDelegate);

                    builder.SetOnAuthFinishedCallback(HandleAuthTransition);
                    builder.SetOnTurnBasedMatchEventCallback((eventType, matchId, match)
                        => mTurnBasedClient.HandleMatchEvent(eventType, matchId, match));
                    builder.SetOnMultiplayerInvitationEventCallback(HandleInvitation);
                    if (mConfiguration.EnableSavedGames) {
                        builder.EnableSnapshots();
                    }
                    mServices = builder.Build(config);
                    mTurnBasedClient =
                        new NativeTurnBasedMultiplayerClient(this, new TurnBasedManager(mServices));

                    mTurnBasedClient.RegisterMatchDelegate(mConfiguration.MatchDelegate);

                    mRealTimeClient =
                        new NativeRealtimeMultiplayerClient(this, new RealtimeManager(mServices));

                    if (mConfiguration.EnableSavedGames) {
                        mSavedGameClient =
                            new NativeSavedGameClient(new SnapshotManager(mServices));
                    } else {
                        mSavedGameClient = new UnsupportedSavedGamesClient(
                            "You must enable saved games before it can be used. " +
                            "See PlayGamesClientConfiguration.Builder.EnableSavedGames.");
                    }

                    mAppStateClient = CreateAppStateClient();
                    mAuthState = AuthState.SilentPending;
                }
            }
        }
    }
 public void SignOut()
 {
     Logger.d("AndroidClient.SignOut");
     mSignOutInProgress = true;
     RunWhenConnectionStable(() => {
         Logger.d("Calling GHM.SignOut");
         mGHManager.SignOut();
         mAuthState = AuthState.NoAuth;
         mSignOutInProgress = false;
         Logger.d("Now signed out.");
     });
 }
 public GlobalState()
 {
     Auth = new AuthState();
     ExternalLogin = new ExternalLoginState();
 }
Example #39
0
    private void InitializeGameServices() {
        lock (GameServicesLock) {
            if (mServices != null) {
                return;
            }

            using (var builder = GameServicesBuilder.Create()) {
                using (var config = CreatePlatformConfiguration(builder)) {
                    builder.SetOnAuthFinishedCallback(HandleAuthTransition);
                    builder.SetOnTurnBasedMatchEventCallback((eventType, matchId, match)
                        => mTurnBasedClient.HandleMatchEvent(eventType, matchId, match));
                    builder.SetOnMultiplayerInvitationEventCallback(HandleInvitation);
                    mServices = builder.Build(config);
                    mTurnBasedClient =
                        new NativeTurnBasedMultiplayerClient(this, new TurnBasedManager(mServices));
                    mRealTimeClient =
                        new NativeRealtimeMultiplayerClient(this, new RealtimeManager(mServices));
                    mAppStateClient = CreateAppStateClient();
                    mAuthState = AuthState.SilentPending;
                }
            }
        }
    }
 public void SignOut() {
     Logger.d("AndroidClient.SignOut");
     RunWhenConnectionStable(() => {
         Logger.d("Calling GHM.SignOut");
         mGameHelperManager.SignOut();
         mAuthState = AuthState.NoAuth;
         Logger.d("Now signed out.");
     });
 }
 // called (on the UI thread) by GameHelperManager to notify us that sign in failed
 internal void OnSignInFailed()
 {
     Logger.d("AndroidClient got OnSignInFailed.");
     if (mAuthState == AuthState.AuthPending) {
         // we have yet to start the auth flow
         if (mSilentAuth) {
             Logger.d("AUTH: Auth flow was pending, but silent=true, so failing.");
             mAuthState = AuthState.NoAuth;
             InvokeAuthCallback(false);
         } else {
             Logger.d("AUTH: Auth flow was pending and silent=false, so doing noisy auth.");
             mAuthState = AuthState.InProgress;
             mGHManager.BeginUserInitiatedSignIn();
         }
     } else if (mAuthState == AuthState.InProgress) {
         // authentication was in progress, but failed: notify callback
         Logger.d("AUTH: FAILED!");
         mAuthState = AuthState.NoAuth;
         InvokeAuthCallback(false);
     } else if (mAuthState == AuthState.LoadingAchs) {
         // we were loading achievements and got disconnected: notify callback
         Logger.d("AUTH: FAILED (while loading achievements).");
         mAuthState = AuthState.NoAuth;
         InvokeAuthCallback(false);
     } else if (mAuthState == AuthState.NoAuth) {
         // we will hit this case during the normal lifecycle (for example, Activity
         // was brought to the foreground and sign in has failed).
         Logger.d("Normal OnSignInFailed received.");
     } else if (mAuthState == AuthState.Done) {
         // we lost authentication (for example, the token might have expired,
         // or the user revoked it)
         Logger.e("Authentication has been lost!");
         mAuthState = AuthState.NoAuth;
     }
 }
        // called from game thread
        public void Authenticate(System.Action<bool> callback, bool silent)
        {
            if (mAuthState != AuthState.NoAuth) {
                Logger.w("Authenticate() called while an authentication process was active. " +
                        mAuthState);
                mAuthCallback = callback;
                return;
            }

            // make sure the helper GameObject is ready (we use it for the auth callback)
            Logger.d("Making sure PlayGamesHelperObject is ready.");
            PlayGamesHelperObject.CreateObject();
            Logger.d("PlayGamesHelperObject created.");

            mSilentAuth = silent;
            Logger.d("AUTH: starting auth process, silent=" + mSilentAuth);
            RunOnUiThread(() => {
                switch (mGHManager.State) {
                    case GameHelperManager.ConnectionState.Connected:
                        Logger.d("AUTH: already connected! Proceeding to achievement load phase.");
                        mAuthCallback = callback;
                        DoInitialAchievementLoad();
                        break;
                    case GameHelperManager.ConnectionState.Connecting:
                        Logger.d("AUTH: connection in progress; auth now pending.");
                        mAuthCallback = callback;
                        mAuthState = AuthState.AuthPending;
                        // we'll do the right thing in OnSignInSucceeded/Failed
                        break;
                    default:
                        mAuthCallback = callback;
                        if (mSilentAuth) {
                            Logger.d("AUTH: not connected and silent=true, so failing.");
                            mAuthState = AuthState.NoAuth;
                            InvokeAuthCallback(false);
                        } else {
                            Logger.d("AUTH: not connected and silent=false, so starting flow.");
                            mAuthState = AuthState.InProgress;
                            mGHManager.BeginUserInitiatedSignIn();
                            // we'll do the right thing in OnSignInSucceeded/Failed
                        }
                        break;
                }
            });
        }
        // UI thread
        private void OnAchievementsLoaded(int statusCode, AndroidJavaObject buffer)
        {
            if (mAuthState == AuthState.LoadingAchs) {
                Logger.d("AUTH: Initial achievement load finished.");

                if (statusCode == JavaConsts.STATUS_OK || statusCode == JavaConsts.STATUS_STALE_DATA) {
                    // successful load (either from network or local cache)
                    Logger.d("Processing buffer.");
                    mAchievementBank.ProcessBuffer(buffer);
                    Logger.d("AUTH: Auth process complete!");
                    mAuthState = AuthState.Done;
                    InvokeAuthCallback(true);
                } else {
                    Logger.w("AUTH: Failed to load achievements, status code " + statusCode);
                    mAuthState = AuthState.NoAuth;
                    InvokeAuthCallback(false);
                }
            } else {
                Logger.w("OnAchievementsLoaded called unexpectedly in auth state " + mAuthState);
            }
        }
 // call from UI thread only!
 private void DoInitialAchievementLoad()
 {
     Logger.d("AUTH: Now performing initial achievement load...");
     mAuthState = AuthState.LoadingAchs;
     mGHManager.CallGmsApiWithResult("games.Games", "Achievements", "load",
             new OnAchievementsLoadedResultProxy(this), false);
     Logger.d("AUTH: Initial achievement load call made.");
 }
 // call from UI thread only!
 private void DoInitialAchievementLoad() {
     Logger.d("AUTH: Now performing initial achievement load...");
     mAuthState = AuthState.LoadingAchs;
     mGameHelperManager.GetGamesClient().Call("loadAchievements",
         new OnAchievementsLoadedListenerProxy(this), false);
     Logger.d("AUTH: Initial achievement load call made.");
 }
        // UI thread
        private void OnAchievementsLoaded(int statusCode, AndroidJavaObject buffer) {
            if (mAuthState == AuthState.LoadingAchs) {
                Logger.d("AUTH: Initial achievement load finished.");

                if (statusCode == JavaConsts.STATUS_OK || 
                        statusCode == JavaConsts.STATUS_STALE_DATA ||
                        statusCode == JavaConsts.STATUS_DEFERRED) {
                    // successful load (either from network or local cache)
                    Logger.d("Processing achievement buffer.");
                    mAchievementBank.ProcessBuffer(buffer);
                    
                    Logger.d("Closing achievement buffer.");
                    buffer.Call("close");
                    
                    Logger.d("AUTH: Auth process complete!");
                    mAuthState = AuthState.Done;
                    InvokeAuthCallback(true);
                    
                    // inform the RTMP client and TBMP clients that sign in suceeded
                    CheckForConnectionExtras();
                    mRtmpClient.OnSignInSucceeded();
                    mTbmpClient.OnSignInSucceeded();
                } else {
                    Logger.w("AUTH: Failed to load achievements, status code " + statusCode);
                    mAuthState = AuthState.NoAuth;
                    InvokeAuthCallback(false);
                }
            } else {
                Logger.w("OnAchievementsLoaded called unexpectedly in auth state " + mAuthState);
            }
        }