コード例 #1
0
        public void TwitterSteps(string Token, string way)
        {
            TwitterGetBack obj = JsonAuthorizeData <TwitterGetBack> .FromJson(Token.ToString());

            AGConnectAuthCredential credential =
                TwitterAuthProvider.credentialWithToken(obj.Token, obj.Secret);

            thirdPartySignIn(way, credential);
        }
        public async Task GetAccessTokenTest()
        {
            Settings.TenantId = "tenant123";
            restApiRepositoryMock.Setup(x => x.PostRequestAsync <Dictionary <string, string>, string>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <Dictionary <string, string> >(), CancellationToken.None))
            .ReturnsAsync("access_token");
            var    twitterAuthprovider = new TwitterAuthProvider(restApiRepositoryMock.Object, azureTableProvider);
            string access_token        = await twitterAuthprovider.GetAccessToken("ACCESS_CODE", "REDIRECT_URL", new Dictionary <string, string>());

            Assert.AreEqual("access_token", access_token);
            restApiRepositoryMock.Verify(x => x.PostRequestAsync <Dictionary <string, string>, string>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <Dictionary <string, string> >(), CancellationToken.None), Times.Once);
        }
コード例 #3
0
        private void TwitterAuthComplete(object sender, AuthenticatorCompletedEventArgs e)
        {
            Log.Debug(Tag, "TwitterAuthComplete:" + e.IsAuthenticated);

            if (e.IsAuthenticated)
            {
                var token  = e.Account.Properties["oauth_token"];
                var secret = e.Account.Properties["oauth_token_secret"];

                AuthCredential credential = TwitterAuthProvider.GetCredential(token, secret);
                mAuth.SignInWithCredential(credential);
            }
        }
        public async Task GetOAuthUrlTest()
        {
            Settings.TenantId = "tenant123";
            var tokenResponse = "oauth_token=TOKEN&oauth_token_secret=SECRET&oauth_callback_confirmed=true";

            restApiRepositoryMock.Setup(x => x.PostRequestAsync <string, string>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <string>(), CancellationToken.None))
            .ReturnsAsync(tokenResponse);
            var twitterAuthProvider = new TwitterAuthProvider(restApiRepositoryMock.Object, azureTableProvider);
            var tokenString         = await twitterAuthProvider.GetOAuthToken();

            Assert.AreEqual(tokenResponse, tokenString);
            restApiRepositoryMock.Verify(x => x.PostRequestAsync <string, string>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <string>(), CancellationToken.None), Times.Once);
        }
コード例 #5
0
 public void SignInWithTwitter(string token, string secret, Action <FirebaseUserResult> callback)
 {
     if ((Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) && !Application.isEditor)
     {
         Credential credential = TwitterAuthProvider.GetCredential(token, secret);
         targetBehaviour.StartCoroutine(ProcessFirebaseUserTaskRoutine(auth.SignInWithCredentialAsync(credential), callback));
     }
     else
     {
         WWWForm form = new WWWForm();
         form.AddField("token", token);
         form.AddField("secret", secret);
         WWW www = new WWW(serviceUrl + "/signInWithTwitter", form);
         targetBehaviour.StartCoroutine(ProcessWebServiceUserRoutine(www, callback));
     }
 }
        public void GetUserTokenForjobIdTest()
        {
            SourceInfoTwitter sourceinfo = new SourceInfoTwitter();

            sourceinfo.ClientSecret = "CLIENT_SECRET";
            sourceinfo.ClientToken  = "CLIENT_TOKEN";
            PageJobEntity pageJobEntity = new PageJobEntity()
            {
                PartitionKey = "123",
                RowKey       = "abc",
                SourceInfo   = JsonConvert.SerializeObject(sourceinfo),
            };
            var twitterAuthProvider = new TwitterAuthProvider(restApiRepositoryMock.Object, azureTableProvider);
            var token = twitterAuthProvider.GetUserTokenForjobId(pageJobEntity);

            Assert.IsTrue(token.Contains("CLIENT_TOKEN"));
        }
        public async Task getAuthorizedAccountTest()
        {
            Settings.TenantId = "tenant123";
            var twitterAccount = new AccountTwitter()
            {
                Id       = "123",
                Name     = "test_acc",
                EmaildId = "*****@*****.**"
            };

            restApiRepositoryMock.Setup(x => x.GetRequestAsync <AccountTwitter>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <Dictionary <string, string> >(), CancellationToken.None))
            .ReturnsAsync(twitterAccount);
            var twitterAuthProvider = new TwitterAuthProvider(restApiRepositoryMock.Object, azureTableProvider);
            var entities            = await twitterAuthProvider.GetAuthorizedAccount(It.IsAny <string>());

            Assert.AreEqual(twitterAccount, entities);
            restApiRepositoryMock.Verify(x => x.GetRequestAsync <AccountTwitter>(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <Dictionary <string, string> >(), CancellationToken.None), Times.Once);
        }
コード例 #8
0
        protected override void OnElementChanged(ElementChangedEventArgs <Page> e)
        {
            base.OnElementChanged(e);
            // check if the user is signed in
            FirebaseAuth mAuth2      = FirebaseAuth.Instance;
            FirebaseUser currentUser = mAuth2.CurrentUser;

            if (currentUser != null)
            {
                silentSignIn = true;
                // signed into Firebase, so get the token and save it in user object
                if (AppManager.User == null)
                {
                    AppManager.User        = new UserDetails();
                    AppManager.User.UserId = currentUser.Uid;
                    var tokenResult = currentUser.GetToken(false);
                    tokenResult.AddOnSuccessListener(this);
                }
                else
                {
                    if (!publishLoginDone)
                    {
                        Xamarin.Forms.MessagingCenter.Send("NavigateToNextPage", "LoginDone");
                        publishLoginDone = true;
                    }

                    AppManager.GetFavoritesFromFirebase(AppManager.User.UserId);
                }
            }
            else
            {
                try
                {
                    var                    credential   = TwitterAuthProvider.GetCredential(App.token, App.tokensecret);
                    FirebaseAuth           mAuth        = FirebaseAuth.Instance;
                    Android.Gms.Tasks.Task signedInTask = mAuth.SignInWithCredential(credential);
                    signedInTask.AddOnCompleteListener(this);
                }
                catch (Exception ex)
                {
                    string j = ex.Message;
                }
            }
        }
コード例 #9
0
 private void Auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
 {
     if (e.IsAuthenticated)
     {
         string  defaultToken  = "";
         string  defaultSecret = "";
         Account account       = e.Account;
         if (account.Properties.TryGetValue("oauth_token", out defaultToken) && account.Properties.TryGetValue("oauth_token_secret", out defaultSecret))
         {
             Log.Info(TAG, "Twitter login success. Accesstoken: " + defaultToken);
             IAGConnectAuthCredential twitterCredential = TwitterAuthProvider.CredentialWithToken(defaultToken, defaultSecret);
             SignIn(twitterCredential);
         }
         else
         {
             Log.Error(TAG, "Cannot find value of oauth_token or oauth_token_secret");
         }
     }
 }
コード例 #10
0
        public static string PostToUrl(TwitterAuthProvider oAuthProvider, string url, string accessToken, string accessTokenSecret, Dictionary <string, string> args, string acceptType = MimeTypes.Json)
        {
            var uri    = new Uri(url);
            var webReq = (HttpWebRequest)WebRequest.Create(uri);

            webReq.Accept = acceptType;
            webReq.Method = HttpMethods.Post;

            string data = null;

            if (args != null)
            {
                var sb = new StringBuilder();
                foreach (var arg in args)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append("&");
                    }
                    sb.AppendFormat("{0}={1}", arg.Key, OAuthUtils.PercentEncode(arg.Value));
                }
                data = sb.ToString();
            }

            webReq.Headers[HttpRequestHeader.Authorization] = OAuthAuthorizer.AuthorizeRequest(
                oAuthProvider, accessToken, accessTokenSecret, "POST", uri, data);

            if (data != null)
            {
                webReq.ContentType = MimeTypes.FormUrlEncoded;
                using (var writer = new StreamWriter(webReq.GetRequestStream()))
                    writer.Write(data);
            }

            using (var webRes = webReq.GetResponse())
            {
                return(webRes.ReadToEnd());
            }
        }
コード例 #11
0
        /// <summary>
        /// Perform Authorization
        /// </summary>
        public async Task <WinRtAuthorizer> AuthorizeAsync()
        {
            await LoadCredentials();

            var twitAuthentication = new TwitterAuthProvider(Credentials.ConsumerKey, Credentials.ConsumerSecret, Callback);

            var user = await twitAuthentication.AuthenticateAsync();

            if (twitAuthentication.OAuthToken != null && twitAuthentication.OAuthTokenSecret != null)
            {
                OAuthTwitter.OAuthToken       = twitAuthentication.OAuthToken;
                OAuthTwitter.OAuthTokenSecret = twitAuthentication.OAuthTokenSecret;
                Credentials.ScreenName        = user.UserName;
                Credentials.UserId            = user.Id;
                Credentials.OAuthToken        = twitAuthentication.OAuthToken;
                Credentials.AccessToken       = twitAuthentication.OAuthTokenSecret;

                await SaveCredentials();
            }

            return(this);
        }
コード例 #12
0
        /// <summary>
        /// Attaches the given Twitter credentials to the user. This allows the user to sign in to this account in the future with credentials for such provider.
        /// </summary>
        /// <param name="token">The Twitter OAuth token.</param>
        /// <param name="secret">The Twitter OAuth secret.</param>
        /// <returns>Updated current account</returns>
        public IObservable <IFirebaseAuthResult> LinkWithTwitter(string token, string secret)
        {
            AuthCredential credential = TwitterAuthProvider.GetCredential(token, secret);

            return(LinkWithCredentialAsync(credential).ToObservable());
        }
コード例 #13
0
        /// <summary>
        /// Attaches the given Twitter credentials to the user. This allows the user to sign in to this account in the future with credentials for such provider.
        /// </summary>
        /// <param name="token">The Twitter OAuth token.</param>
        /// <param name="secret">The Twitter OAuth secret.</param>
        /// <returns>Task of IUserWrapper</returns>
        public async Task <IFirebaseAuthResult> LinkWithTwitterAsync(string token, string secret)
        {
            AuthCredential credential = TwitterAuthProvider.GetCredential(token, secret);

            return(await LinkWithCredentialAsync(credential));
        }
コード例 #14
0
        /// <inheritdoc/>
        public IObservable <Unit> SignInWithTwitter(string token, string secret)
        {
            AuthCredential credential = TwitterAuthProvider.GetCredential(token, secret);

            return(SignInAsync(credential).ToObservable().Select(_ => Unit.Default));
        }
コード例 #15
0
    /// <summary>
    /// Login using an auth method. Note: Only 1 auth type can be linked at a time! You'll need to call UnLinkAuth if you want to UnLink an auth type
    /// </summary>
    /// <returns><c>true</c>, if login was successful, <c>false</c> otherwise.</returns>
    /// <param name="type">Auth type</param>
    public static void AuthLogin(AuthType type)
    {
        Credential credential = default(Credential);                 // For some reason if this is null instead of default Unity will just crash (even though the default seems to be null anyway ??)

        if (auth != null)
        {
            ProjectManager.Log("[Firebase AuthLogin] " + type.ToString());

            switch (type)
            {
            case AuthType.Google:
                                                #if google
                if (Social.localUser == null || !Social.localUser.authenticated)
                {
                    GoogleLogin();
                    return;
                }
                else
                {
                    credential = GoogleAuthProvider.GetCredential(PlayGamesPlatform.Instance.GetIdToken(), PlayGamesPlatform.Instance.GetServerAuthCode());
                }
                                                #else
                Debug.LogError("Google auth login called but the Google Play Games Services plugin is now active in this project!");
                                                #endif
                break;

            case AuthType.Facebook:
                                                #if facebook
                if (!FB.IsLoggedIn || staticRef.activeFacebookAccessToken == null)
                {
                    FacebookLogin();                                              // We need to wait for the facebook login callback before trying to auth again
                    return;
                }
                else
                {
                    credential = FacebookAuthProvider.GetCredential(staticRef.activeFacebookAccessToken.TokenString);
                }
                                                #else
                Debug.LogError("Facebook auth login called but the facebook plugin in not active in this project!");
                                                #endif
                break;

            case AuthType.Twitter:
                                                #if twitter
                if (Twitter.Session == null || Twitter.Session.authToken == null)
                {
                    TwitterLogin();                                             // We need to wait for the twitter login callback before trying to auth again
                    return;
                }
                else
                {
                    credential = TwitterAuthProvider.GetCredential(Twitter.Session.authToken.token, Twitter.Session.authToken.secret);
                }
                                                #else
                Debug.LogError("Twitter auth login called but the twitter plugin is not active in this project!");
                                                #endif
                break;
            }

            if (credential != null)
            {
                auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
                    if (task.IsCanceled)
                    {
                        Analytics.LogError("Firebase AuthLogin " + type.ToString(), "AuthLogin was canceled!");
                        return;
                    }

                    if (task.IsFaulted)
                    {
                        // Firebase for Unity is pretty undocumented for doing more than simply adding the plugins into projects..
                        // Error handling doesn't seem great either, as of building this there's no error enum or error codes
                        // So we just have strings to work with if we want to do actions on specific errors happening
                        foreach (Exception e in task.Exception.InnerExceptions)
                        {
                            Analytics.LogError("Firebase AuthLogin", e.Message);                                     // This string only includes the firebase error, no information about the exception type

                            OnLoginFailed(ConvertToAuthError(e.Message));
                        }
                        return;
                    }

                    // Auth login was successful
                    if (task.IsCompleted)
                    {
                        staticRef.OnLogin();

                        // Attempt to link these auth'd credentials with firebase

                        /*task.Result.LinkWithCredentialAsync (credential).ContinueWith (linkTask => {
                         *      if (linkTask.IsCanceled) {
                         *              Analytics.LogError ("Firebase Credential Link " + type.ToString (), "Link with credentials was canceled!");
                         *              return;
                         *      }
                         *
                         *      if (linkTask.IsFaulted) {
                         *              Analytics.LogError ("Firebase Credential Link " + type.ToString (), "Error: " + task.Exception);
                         *              return;
                         *      }
                         *
                         *      // Link with credentials was a success, firebase will now keep track of this auth across games >:0
                         * });*/
                    }
                });
            }
        }
        else
        {
            Analytics.LogError("Firebase AuthLogin", "Auth was null!");
        }
    }
コード例 #16
0
        public IAuthCredential GetCredential(string token, string secret)
        {
            var credential = TwitterAuthProvider.GetCredential(token, secret);

            return(new AuthCredentialWrapper(credential));
        }