Exemplo n.º 1
2
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret = credentials.ClientSecret;
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var service = new TasksService(auth);

            // Execute request: Create sample list.
            if (!ListExists(service, SampleListName) &&
                CommandLine.RequestUserChoice("Do you want to create a sample list?"))
            {
                CreateSampleTasklist(service);
            }
            CommandLine.WriteLine();

            // Execute request: List task-lists.
            ListTaskLists(service);

            CommandLine.PressAnyKeyToExit();
        }
Exemplo n.º 2
1
		void LoginToFacebook (object sender, EventArgs e)
		{
			var auth = new OAuth2Authenticator (
				clientId: "346691492084618",
				scope: "",
				authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
				redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

			// If authorization succeeds or is canceled, .Completed will be fired.
			auth.Completed += (s, ee) => {
				if (!ee.IsAuthenticated) {
					this.facebookStatus.Text = "Not Authenticated";
					return;
				}

				// Now that we're logged in, make a OAuth2 request to get the user's info.
				var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, ee.Account);
				request.GetResponseAsync().ContinueWith (t => {
					if (t.IsFaulted)
						this.facebookStatus.Text = "Error: " + t.Exception.InnerException.Message;
					else if (t.IsCanceled)
						this.facebookStatus.Text = "Canceled";
					else
					{
						var obj = JsonValue.Parse (t.Result.GetResponseText());
						this.facebookStatus.Text = "Logged in as " + obj["name"];
					}
				}, uiScheduler);
			};

			var intent = auth.GetUI (this);
			StartActivityForResult (intent, 42);
		}
        /// <summary>
        ///     Authenticates the user with the service and saves the refresh token.
        /// </summary>
        /// <param name="request">Http request message</param>
        /// <returns></returns>
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            authenticator = new OAuth2Authenticator(ServiceConstants.MSA_CLIENT_ID,
                ServiceConstants.MSA_CLIENT_SECRET,
                string.Join(",", ServiceConstants.Scopes),
                new Uri(ServiceConstants.AUTHENTICATION_URL),
                new Uri(ServiceConstants.RETURN_URL),
                new Uri(ServiceConstants.TOKEN_URL));

            var protectedData = new ProtectedData();
            var accessToken = string.Empty;
            var refreshToken = protectedData.Unprotect(ServiceConstants.REFRESH_TOKEN);
            if (string.IsNullOrEmpty(refreshToken))
            {
                var result = await ShowWebView();
                if (result != null)
                {
                    // pass access_token to the onedrive sdk
                    accessToken = result[ServiceConstants.ACCESS_TOKEN];
                    
                    // add refresh token to the password vault to enable future silent login
                    new ProtectedData().Protect(ServiceConstants.REFRESH_TOKEN, result[ServiceConstants.REFRESH_TOKEN]);
                }
            }
            else
            {
                accessToken = await authenticator.RequestRefreshTokenAsync(refreshToken);
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
        }
Exemplo n.º 4
0
        public void CheckForValidAccessTokenTest()
        {
            int accessTokenCounter = 1;
            var state = new AuthorizationState();
            var client = new NativeApplicationClient(new Uri("http://example.com"));
            var auth = new OAuth2Authenticator<NativeApplicationClient>(
                client, (clt) =>
                { 
                    // Load a "cached" access token.
                    state.AccessToken = "token" + (accessTokenCounter++);
                    return state;
                });

            // Check that the initial state is null.
            Assert.IsNull(auth.State);

            // Check that the state was set when .LoadAccessToken() is called.
            auth.LoadAccessToken();
            Assert.AreEqual(state, auth.State);
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it wont be set again.
            auth.LoadAccessToken();
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it is set if our state gets invalid.
            state.AccessToken = null;
            auth.LoadAccessToken();
            Assert.AreEqual("token2", auth.State.AccessToken);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Retrieve an IAuthenticator instance using the provided state.
 /// </summary>
 /// <param name="credentials">OAuth 2.0 credentials to use.</param>
 /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns>
 public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials)
 {
     var provider = new StoredStateClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET, credentials);
     var auth = new OAuth2Authenticator<StoredStateClient>(provider, StoredStateClient.GetState);
     auth.LoadAccessToken();
     return auth;
 }
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator (
                clientId: App.Instance.OAuthSettings.ClientId, // your OAuth2 client id
                scope: App.Instance.OAuthSettings.Scope, // The scopes for the particular API you're accessing. The format for this will vary by API.
                authorizeUrl: new Uri (App.Instance.OAuthSettings.AuthorizeUrl), // the auth URL for the service
                redirectUrl: new Uri (App.Instance.OAuthSettings.RedirectUrl)); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated) {
                    App.Instance.SuccessfulLoginAction.Invoke();
                    // Use eventArgs.Account to do wonderful things
                    App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);
                } else {
                    // The user cancelled
                }
            };

            activity.StartActivity (auth.GetUI(activity));
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            var auth = new OAuth2Authenticator(
                           clientId: "",
                           scope: "",
                           authorizeUrl: new Uri(""),
                           redirectUrl: new Uri("")
                       );
            auth.Completed += ( sender, eventArgs) => {
                //We popped the UI, so it's on us to dismiss in iOS....
                App.SuccessfulLoginAction.Invoke();

                if (eventArgs.IsAuthenticated){
                    //Use eventArgs.Account to do good stuff
                    App.SaveToken(eventArgs.Account.Properties["access_token"]);
                }
                else{
                    //User cancelled
                }
            };

            PresentViewController(auth.GetUI(),true,null);
        }
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);

			var auth = new OAuth2Authenticator (
				clientId: App.Instance.OAuthSettings.ClientId, // your OAuth2 client id
				scope: App.Instance.OAuthSettings.Scope, // The scopes for the particular API you're accessing. The format for this will vary by API.
				authorizeUrl: new Uri (App.Instance.OAuthSettings.AuthorizeUrl), // the auth URL for the service
				redirectUrl: new Uri (App.Instance.OAuthSettings.RedirectUrl)); // the redirect URL for the service

				
				

			auth.Completed += (sender, eventArgs) => {
				// We presented the UI, so it's up to us to dimiss it on iOS.
				App.Instance.SuccessfulLoginAction.Invoke();

				if (eventArgs.IsAuthenticated) {
					// Use eventArgs.Account to do wonderful things
					App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);
				} else {
					// The user cancelled
				}
			};

			PresentViewController (auth.GetUI (), true, null);
		}
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            var activity = Context as Activity;

            var auth = new OAuth2Authenticator(
                clientId: "actioncenterapp", // OAuth2 client id
                scope: "actioncenter", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri("https://idsat.nwpsmart.com/identity/connect/authorize"), // the auth URL for the service
                redirectUrl: new Uri("https://actioncenterapp/callback/")); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    App.SaveToken(eventArgs.Account.Properties["access_token"]);
                    var page = Element as LoginPage;
                    page?.NavigateToHome();
                }
                else
                {
                    // The user cancelled
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
        public FacebookPageRenderer()
        {
            var activity = this.Context as Activity;
            var auth = new OAuth2Authenticator(
            clientId: "476292725915235",
            scope: "",
            authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
            redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

            auth.Completed += async (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated)
                {
                    var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                    var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
                    var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);

                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
                    var response = await request.GetResponseAsync();
                    var obj = JObject.Parse(response.GetResponseText());

                    var id = obj["id"].ToString().Replace("\"", "");
                    var name = obj["name"].ToString().Replace("\"", "");

                    App app = new App();
                   await app.NavigateToProfile(string.Format("Olá {0}", name));

                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Alerta", "lOGIN CANCELADO", " OK");

                }
            };
            activity.StartActivity(auth.GetUI(activity));
        }
Exemplo n.º 11
0
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);

			// url : http://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms
			if(	visible == false )
			{
				visible = true;

				var auth = new OAuth2Authenticator (
					clientId: App.OAuthSettings.ClientId, // your OAuth2 client id
					scope: App.OAuthSettings.Scope, // The scopes for the particular API you're accessing. The format for this will vary by API.
					authorizeUrl: new Uri (App.OAuthSettings.AuthorizeUrl), // the auth URL for the service
					redirectUrl: new Uri (App.OAuthSettings.RedirectUrl)); // the redirect URL for the service

				auth.Completed += (sender, eventArgs) => {
					App.SuccessfulLoginAction.Invoke();

					if (eventArgs.IsAuthenticated)
					{
						App.SaveToken(eventArgs.Account.Properties["access_token"]);
					} 
					else 
					{
						// The user cancelled
					}
				};

				PresentViewController (auth.GetUI (), true, null);
			}
		}
		protected override void OnElementChanged (ElementChangedEventArgs<Page> e)
		{
			base.OnElementChanged (e);

			// Retrieve any stored account information
			var accounts = AccountStore.Create (Context).FindAccountsForService (App.AppName);
			var account = accounts.FirstOrDefault ();

			if (account == null) {
				if (!isShown) {
					isShown = true;

					// Initialize the object that communicates with the OAuth service
					var auth = new OAuth2Authenticator (
						           Constants.ClientId,
						           Constants.ClientSecret,
						           Constants.Scope,
						           new Uri (Constants.AuthorizeUrl),
						           new Uri (Constants.RedirectUrl),
						           new Uri (Constants.AccessTokenUrl));

					// Register an event handler for when the authentication process completes
					auth.Completed += OnAuthenticationCompleted;

					// Display the UI
					var activity = Context as Activity;
					activity.StartActivity (auth.GetUI (activity));
				}
			} else {
				if (!isShown) {
					App.User.Email = account.Username;
					App.SuccessfulLoginAction.Invoke ();
				}
			}
		}
Exemplo n.º 13
0
        void LoginToVk()
        {
            var auth = new OAuth2Authenticator (
                clientId: VkSettings.AppID,
                scope: "friends,video,audio",
                //clientSecret: VkSettings.SecureKey,
                authorizeUrl: new Uri ("https://oauth.vk.com/authorize"),
                redirectUrl: new Uri ("https://oauth.vk.com/blank.html"));
            auth.AllowCancel = true;
            auth.Completed += (s, ee) => {
                if (!ee.IsAuthenticated) {
                    return;
                }
                else
                {
                    var token = ee.Account.Properties ["access_token"].ToString ();
                    var userId = ee.Account.Properties ["user_id"].ToString ();
                    var user = App.Container.Resolve<ISession> ().CurrentUser;
                    user.VkUserInfo = new VkUserInfo(token, userId);
                    auth.OnSucceeded (ee.Account);
                    user.Save ();
                    //this.DismissViewController (true, null);
                    page.Navigation.PopAsync ();
                }
            };
            auth.Error += (sender, e) => {
                var a = 4;
            };

            var nav = auth.GetUI () as UINavigationController;
            controller = nav.TopViewController;
            this.AddChildViewController (controller);
            this.View.AddSubview (controller.View);
        }
Exemplo n.º 14
0
        void LoginToVk()
        {
            var auth = new OAuth2Authenticator (
                clientId: "",  // put your id here
                scope: "friends,video,groups",
                authorizeUrl: new Uri ("https://oauth.vk.com/authorize"),
                redirectUrl: new Uri ("https://oauth.vk.com/blank.html"));

            auth.AllowCancel = true;
            auth.Completed += (s, ee) => {
                if (!ee.IsAuthenticated) {
                    var builder = new AlertDialog.Builder (this);
                    builder.SetMessage ("Not Authenticated");
                    builder.SetPositiveButton ("Ok", (o, e) => { });
                    builder.Create().Show();
                    return;
                }
                else
                {
                    token = ee.Account.Properties ["access_token"].ToString ();
                    userId = ee.Account.Properties ["user_id"].ToString ();
                    GetInfo();
                }
            };
            var intent = auth.GetUI (this);
            StartActivity (intent);
        }
Exemplo n.º 15
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            // Fixed the issue that on iOS 8, the modal wouldn't be popped.
            // url : http://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms
            if (!IsShown)
            {
                IsShown = true;

                var auth = new OAuth2Authenticator(Constants.FacebookClientId, // your OAuth2 client id
                    Constants.FaceBookScope,
                    // The scopes for the particular API you're accessing. The format for this will vary by API.
                    new Uri(Constants.FacebookAuthUrl), // the auth URL for the service
                    new Uri(Constants.FacebookRedirect)); // the redirect URL for the service


                auth.Completed += (sender, eventArgs) =>
                {
                    // We presented the UI, so it's up to us to dimiss it on iOS.
                    App.Instance.SuccessfulLoginAction(eventArgs.Account.Properties["access_token"]);

                    if (eventArgs.IsAuthenticated)
                    {
                        // Use eventArgs.Account to do wonderful things
                        //App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);
                    }
                };

                PresentViewController(auth.GetUI(), true, null);
            }
        }
Exemplo n.º 16
0
        // protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged (e);
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator (
                clientId: App.Current.Properties ["clientId"].ToString(),
                scope: App.Current.Properties ["scope"].ToString(),
                authorizeUrl: new Uri( App.Current.Properties ["authorizeUrl"].ToString()),
                redirectUrl: new Uri(App.Current.Properties ["redirectUrl"].ToString())

            );

            auth.Completed += (sender,eventArgs) => {
                if (eventArgs.IsAuthenticated){

                    App.Current.Properties ["access_token"] = eventArgs.Account.Properties ["access_token"].ToString();
                    if(App.Current.Properties ["access_token"].ToString().Length>0)
                    {
                       //use the eventargs to do good stuff
                       AccountStore.Create (activity).Save (eventArgs.Account, "Google");
                       App.Current.MainPage = new ProfilePage();
                    }
                }
                else
                {
                    //User Cancelled
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
Exemplo n.º 17
0
		protected override void OnElementChanged (ElementChangedEventArgs<Page> ee)
		{
			base.OnElementChanged (ee);

		
			var activity = Context as Activity;
		
			if (!string.IsNullOrEmpty (Settings.AccessToken)) {
				return;	
			}

			authenticator = new OAuth2Authenticator (
				clientId: AuthHelpers.ClientId, // your OAuth2 client id
				scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
				authorizeUrl: new Uri (AuthHelpers.AuthoriseUrl), // the auth URL for the service
				redirectUrl: new Uri (AuthHelpers.RedirectUrl)); // the redirect URL for the service

			authenticator.Completed += (sender, e) => {
				//DismissViewController (true, null);
				if (e.IsAuthenticated) {
					const string accessTokenKey = "access_token";
					if (e.IsAuthenticated && e.Account.Properties.ContainsKey (accessTokenKey)) {
						Settings.AccessToken = e.Account.Properties [accessTokenKey];
						AccountStore.Create (Forms.Context).Save (e.Account, "facebook");
					}
				}
			};

			activity.StartActivity (authenticator.GetUI (activity));

		}
Exemplo n.º 18
0
        public JsonResult CheckAuth()
        {
            const string ServiceAccountId = "ServiceAccountId.apps.googleusercontent.com";
            const string ServiceAccountUser = "******";
            X509Certificate2 cert = new X509Certificate2();
            try
            {
                 cert =
                    new X509Certificate2(
                        System.Web.HttpContext.Current.Server.MapPath(
                            "~/Content/key/0eee0d919aaef70bbb5da23b192aede576577058-privatekey.p12"), "notasecret",
                        X509KeyStorageFlags.Exportable);

            }
            catch (Exception ex)
            {
            }

            AssertionFlowClient client = new AssertionFlowClient(
            GoogleAuthenticationServer.Description, cert)
            {

                Scope = Oauth2Service.Scopes.UserinfoProfile.GetStringValue(),
                //  AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

            JsonResult results = Json(authenticator);
              results.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return results;
        }
Exemplo n.º 19
0
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            System.Diagnostics.Debug.WriteLine ("======>Login Page OAuth");
            base.OnElementChanged (e);
            var activity = this.Context as Activity;
            var auth = new OAuth2Authenticator (
                clientId: "621549137987350", // your OAuth2 client id
                scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service
                redirectUrl: new Uri ("http://ihbiproject.azurewebsites.net/api/Users")); // the redirect URL for the service
            auth.Completed += async (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated) {
                    try {
                        var accessToken = eventArgs.Account.Properties ["access_token"].ToString ();
                        App.Instance.SaveToken(accessToken);
                        AccountStore.Create (activity).Save (eventArgs.Account, "WellnessFB");
                        var expiresIn = Convert.ToDouble (eventArgs.Account.Properties ["expires_in"]);
                        var expiryDate = DateTime.Now + TimeSpan.FromSeconds (expiresIn);
                        var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, eventArgs.Account);
                        var response = await request.GetResponseAsync ();
                        var obj = JObject.Parse (response.GetResponseText ());
                        var id = obj ["id"].ToString ().Replace ("\"", "");
                        var name = obj ["name"].ToString ().Replace ("\"","");
                        App.Instance.SuccessfulLoginAction.Invoke();
                    } catch (Exception ex) {
                        System.Diagnostics.Debug.WriteLine("========> Error getting from GraphAPI" +ex);
                    }
                } else {

                }
            };
            System.Diagnostics.Debug.WriteLine ("======>after OAuth");
            activity.StartActivity(auth.GetUI(activity));
        }
Exemplo n.º 20
0
        protected override void OnModelChanged(VisualElement oldModel, VisualElement newModel)
        {
            base.OnModelChanged(oldModel, newModel);

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator(
                clientId: "574134802616730", // your OAuth2 client id
                scope: "email,user_about_me", // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // the auth URL for the service
                redirectUrl: new Uri("https://www.cautom.com/SocialAuth/FBLogin/")); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    //App.SuccessfulLoginAction.Invoke();
                    // Use eventArgs.Account to do wonderful things
                    //App.SaveToken(eventArgs.Account.Properties["access_token"]);
                    string accessToken = eventArgs.Account.Properties["access_token"];
                    new FacebookLoginWebView().fetchUserInfoFromAccessToken(accessToken);
                }
                else
                {
                    // The user cancelled
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
Exemplo n.º 21
0
 public System.IO.Stream DownloadFile(string FileID, string CLIENT_ID, string CLIENT_SECRET, string ConnectionString)
 {
     var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
     var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
     var service = new DriveService(authenticator);
     _ConnectionString = ConnectionString;
     File file = service.Files.Get(FileID).Fetch();
     if (!String.IsNullOrEmpty(file.DownloadUrl))
     {
         try
         {
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(file.DownloadUrl));
             request.Headers.Set("Authorization", "Bearer " + authenticator.State.AccessToken.ToString());
             authenticator.ApplyAuthenticationToRequest(request);
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             if (response.StatusCode == HttpStatusCode.OK)
             {
                 return response.GetResponseStream();
             }
             else
             {
                 throw new Exception("An error occurred: " + response.StatusDescription);
             }
         }
         catch (Exception e)
         {
             throw new Exception("Downloading File Failed: " + e.Message);
         }
     }
     else
     {
         // The file doesn't have any content stored on Drive.
         return null;
     }
 }
Exemplo n.º 22
0
		void LoginByGoogle (bool allowCancel)
		{   
			var auth = new OAuth2Authenticator ( clientId: "847549521106-35dvaoe5jafmc5tuk2ll5054********.apps.googleusercontent.com" ,
				scope: "https://www.googleapis.com/auth/userinfo.email" ,
				authorizeUrl: new Uri ( "https://accounts.google.com/o/oauth2/auth" ) , 
				redirectUrl: new Uri ( "https://www.googleapis.com/plus/v1/people/me" ) , 
				getUsernameAsync: null ); 
			
			auth.AllowCancel = allowCancel;    
			auth.Completed += async (sender , e ) =>
			{  
				if ( !e.IsAuthenticated )
				{ 
					Toast.MakeText(this,"Fail to authenticate!",ToastLength.Short).Show(); 
					return;
				} 
				e.Account.Properties.TryGetValue ( "access_token" , out access_token );  

				if(await fnGetProfileInfoFromGoogle ())
				{
					Toast.MakeText ( this , "Authentcated successfully" , ToastLength.Short ).Show ();
				}
			};  

			var intent = auth.GetUI ( this );
			StartActivity ( intent ); 
		}
Exemplo n.º 23
0
        public void LoginAsync(Action<bool, Dictionary<string, string>> loginCallback)
        {
            var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
            var auth = new OAuth2Authenticator(MeetupService.ClientId, MeetupService.ClientSecret, string.Empty, new Uri(MeetupService.AuthorizeUrl), new Uri(MeetupService.RedirectUrl), new Uri(MeetupService.AccessTokenUrl));

            auth.AllowCancel = true;
            auth.ShowUIErrors = false;
            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += (s, ee) => {
                vc.DismissViewController (true, null);
                if (loginCallback != null)
                    loginCallback (ee.IsAuthenticated, ee.Account == null ? null : ee.Account.Properties);
            };

            auth.Error += (sender, e) =>
            {
                //vc.DismissViewController(true, null);
                //if (loginCallback != null)
                //    loginCallback (false, null);

            };

            vc = auth.GetUI ();
            controller.PresentViewControllerAsync (vc, true);
        }
Exemplo n.º 24
0
        public override void ViewDidAppear(bool animated)
        {
            if (!IsShown)
            {
                IsShown = true;
                base.ViewDidAppear(animated);

                var auth = new OAuth2Authenticator(
                               clientId: "YOUR_OAUTH2_CLIENT_ID",
                               scope: "WHAT_ARE_YOU_ACCESSING_DELIMITED_+_SYMBOLS",
                               authorizeUrl: new Uri("AUTH_URL_FOR_SERVICE"),
                               redirectUrl: new Uri("REDIRECT_URL_FOR_THE_SERVICE")
                           );
                auth.Completed += (sender, eventArgs) =>
                {
                    App.SuccessfulLoginAction.Invoke();
                    if (eventArgs.IsAuthenticated)
                        App.SaveFacebookToken(eventArgs.Account.Properties["access_token"]);
                    else
                    {
                        // cancelled
                    }
                };

                PresentViewController(auth.GetUI(), true, null);
            }
        }
Exemplo n.º 25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            var auth = new OAuth2Authenticator (
                clientId: "1647251678863645",
                scope: "",
                authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

            auth.Completed += (sender, eventArgs) => {

                if (eventArgs.IsAuthenticated) {
                    // Use eventArgs.Account to do wonderful things
                    StartActivity (typeof(DashActivity));

                } else {
                    // The user cancelled
                    StartActivity (typeof(MainActivity));
                }
            };

            StartActivity (auth.GetUI (this));
        }
Exemplo n.º 26
0
        void LoginToVk()
        {
            var auth = new OAuth2Authenticator (
                SecKey: VkSettings.SecureKey,
                clientId: VkSettings.AppID,
                scope: "friends,video,audio",
                authorizeUrl: new Uri ("https://oauth.vk.com/authorize"),
                redirectUrl: new Uri ("https://oauth.vk.com/blank.html"));

            auth.AllowCancel = true;

            auth.Completed += (s, ee) => {
                if (!ee.IsAuthenticated) {
                    //TODO: THINGS IF NOT AUTHORISED
                    return;
                }
                else
                {
                    var token = ee.Account.Properties ["access_token"].ToString ();
                    var uid = ee.Account.Properties ["user_id"].ToString ();
                    _user.VkUserInfo = new VkUserInfo(token, uid);
                }
            };
            //TODO SOMETHING ELSE
            var intent = auth.GetUI (this);
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged (e);

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var activity = this.Context as Activity;

            var auth = new OAuth2Authenticator (
                clientId: "pXQhRdqeGPraG8z85f139g", // your OAuth2 client id
                scope: "", // The scopes for the particular API you're accessing. The format for this will vary by API.
                authorizeUrl: new Uri ("https://www.yammer.com/dialog/oauth"), // the auth URL for the service
                redirectUrl: new Uri ("http://deamon.info/university/330/yammer.php")); // the redirect URL for the service

            auth.Completed += (sender, eventArgs) => {
                //Console.WriteLine("hi");
                //Console.WriteLine(eventArgs);
                if (eventArgs.IsAuthenticated) {
                    App.SuccessfulLoginAction.Invoke();
                    Console.WriteLine("yammer connected");
                    Console.WriteLine(eventArgs.Account);
                    // Use eventArgs.Account to do wonderful things
                    App.SaveToken(eventArgs.Account.Properties["access_token"]);
                } else {
                    // The user cancelled
                    Console.WriteLine("yammer not connected");
                }
                //Console.WriteLine("bye");
                //Console.WriteLine(App.Token);
            };

            activity.StartActivity (auth.GetUI(activity));
        }
        /// <summary>
        /// Return Analytics Service object
        /// </summary>
        /// <returns>Analytics Service object</returns>
        public static AnalyticsService GetAnalyticsService()
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = Settings.ClientIdentifier;
            provider.ClientSecret = Settings.ClientSecret;

            if (string.IsNullOrWhiteSpace(provider.ClientIdentifier))
            {
                throw new Exception("Client identifier not found");
            }
            if (string.IsNullOrWhiteSpace(provider.ClientSecret))
            {
                throw new Exception("Client secret not found");
            }
            string refreshToken = Settings.RefreshToken;
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                throw new Exception("Refresh token not found");
            }

            var request = HttpContext.Current.Request;
            var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, (arg) =>
            {
                IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
                state.Callback = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port));
                state.RefreshToken = refreshToken;
                var result = arg.RefreshToken(state);
                return state;
            });

            return new AnalyticsService(authenticator);
        }
        public OAuth2Authenticator LoginWithProvider(string provider)
        {
            OAuth2Authenticator auth = null;

            switch (provider)
            {
            case "Google":
            {
                auth = new OAuth2Authenticator(
                    // For Google login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    "add your clientid here",
                    "add your client secret here",
                    // Below values do not need changing
                    //"https://www.googleapis.com/auth/userinfo.email",
                    "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
                    new Uri("https://accounts.google.com/o/oauth2/auth"),
                    new Uri("https://parsimoadmin.azurewebsites.net/login"),                // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri("https://accounts.google.com/o/oauth2/token")
                    );

                break;
            }

            case "Facebook":
            {
                auth = new OAuth2Authenticator(
                    clientId: "add your facebook app id here here",                             // For Facebook login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    scope: "email,public_profile",
                    authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),              // These values do not need changing
                    redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html") // These values do not need changing
                    );
                break;
            }

            case "MICROSOFT":
            {
                auth = new OAuth2Authenticator(
                    clientId: "add your clientid here",       // For Micrsoft login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    scope: "bingads.manage",
                    authorizeUrl: new Uri("https://login.live.com/oauth20_authorize.srf?client_id=myid&scope=bingads.manage&response_type=token&redirect_uri=https://login.live.com/oauth20_desktop.srf"),
                    redirectUrl: new Uri("https://adult-wicareerpathways-dev.azurewebsites.net/Account/ExternalLoginCallback")
                    );
                break;
            }

            case "LinkedIn":
            {
                auth = new OAuth2Authenticator(
                    clientId: "add your clientid here",// For LinkedIN login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    clientSecret: "add your clientSecret here",
                    scope: string.Empty,
                    authorizeUrl: new Uri("https://www.linkedin.com/uas/oauth2/authorization"),
                    redirectUrl: new Uri("http://devenvexe.com/"),
                    accessTokenUrl: new Uri("https://www.linkedin.com/uas/oauth2/accessToken")

                    );

                break;
            }

            case "Github":
            {
                auth = new OAuth2Authenticator(
                    // For GITHUB login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    "add your clientid here",
                    "add your clientSecret here",
                    // Below values do not need changing
                    string.Empty,
                    new Uri("https://github.com/login/oauth/authorize"),
                    new Uri("https://www.google.com/"),            // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri("https://github.com/login/oauth/access_token")
                    );

                break;
            }

            case "Flicker":
            {
                auth = new OAuth2Authenticator(
                    // For Flicker login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    "add your clientid here",
                    "add your clientSecret here",
                    // Below values do not need changing
                    string.Empty,
                    new Uri("https://www.flickr.com/services/oauth/request_token"),
                    new Uri("http://www.devenvexe.com"),            // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri("http://www.flickr.com/services/oauth/access_token")
                    );
                break;
            }

            case "Yahoo":
            {
                auth = new OAuth2Authenticator(
                    // For Yahoo login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    "add your clientid here",
                    "add your clientSecret here",
                    // Below values do not need changing
                    string.Empty,
                    new Uri("https://api.login.yahoo.com/oauth2/request_auth"),
                    new Uri("http://www.devenvexe.com"),            // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri("https://api.login.yahoo.com/oauth2/get_token")
                    );
                break;
            }

            case "DropBox":
            {
                auth = new OAuth2Authenticator(
                    // For DROPBOX login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
                    "add your clientid here",
                    "add your clientSecret here",
                    // Below values do not need changing
                    string.Empty,
                    new Uri("https://www.dropbox.com/1/oauth2/authorize"),
                    new Uri("http://www.devenvexe.com"),           // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri("https://api.dropboxapi.com/1/oauth2/token")
                    );
                break;
            }
            }
            return(auth);
        }
Exemplo n.º 30
0
        public void Show(SocialInfo socialInfo)
        {
            // IEnumerable<Account> accounts = AccountStore.Create().FindAccountsForService("Facebook");

            var auth = new OAuth2Authenticator(
                clientId: socialInfo.clientId,         // your OAuth2 client id
                scope: socialInfo.scope,               // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: socialInfo.authorizeUrl, // the auth URL for the service
                redirectUrl: socialInfo.redirectUrl);  // the redirect URL for the service

            auth.ClearCookiesBeforeLogin = false;
            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += async(sender, eventArgs) =>
            {
                if (!eventArgs.IsAuthenticated)
                {
                    Debug.WriteLine("Not Authenticated");
                    return;
                }
                else
                {
                    // Now that we're logged in, make a OAuth2 request to get the user's info.
                    var request = new OAuth2Request("GET", new Uri(socialInfo.userInfoAPI), null, eventArgs.Account);
                    try
                    {
                        Response response = await request.GetResponseAsync();

                        var json = (await response.GetResponseTextAsync());

                        //Debug.WriteLine("Name: " + obj["name"]);



                        if (eventArgs.IsAuthenticated)
                        {
                            // Use eventArgs.Account to do wonderful things
                            //dynamic foo = JsonObject.Parse(json);
                            LoginGear.App.ParseSocial(json, socialInfo);
                            LoginGear.App.SuccessfulLoginAction.Invoke();
                        }
                        else
                        {
                            // The user cancelled
                        }
                    }

                    catch (OperationCanceledException)
                    {
                        Debug.WriteLine("Canceled");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error: " + ex.Message);
                    }
                }
            };

            Uri uri = auth.GetUI();

            App.RootFrame.Navigate(uri);
        }
Exemplo n.º 31
0
        private static OAuth2Authenticator GoogleSignup(bool native_ui)
        {
            var authenticator
                = new OAuth2Authenticator
                  (
                      new Func <string>
                      (
                          () =>
            {
                var retval_client_id = "oops something is wrong!";

                switch (Device.RuntimePlatform)
                {
                case "Android":
                    retval_client_id = Constants.googleClientIdAndroid + ".apps.googleusercontent.com";
                    break;

                case "iOS":
                    retval_client_id = Constants.googleClientIdIOS + ".apps.googleusercontent.com";
                    break;
                }

                return(retval_client_id);
            }
                      ).Invoke(),
                      null,
                      authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
                      accessTokenUrl: new Uri("https://accounts.google.com/o/oauth2/token"),
                      redirectUrl:
                      new Func <Uri>
                      (
                          () =>
            {
                string uri = null;
                switch (Device.RuntimePlatform)
                {
                case "Android":
                    uri = "com.googleusercontent.apps." + Constants.googleClientIdAndroid +
                          ":/oauth2redirect";
                    ;
                    break;

                case "iOS":
                    uri = "com.googleusercontent.apps." + Constants.googleClientIdIOS +
                          ":/oauth2redirect";
                    break;
                }

                return(new Uri(uri));
            }
                      ).Invoke(),
                      scope:
                      //"profile"
                      "https://www.googleapis.com/auth/userinfo.email"
                      ,
                      getUsernameAsync: null,
                      isUsingNativeUI: native_ui
                  )
                {
                ShowErrors  = false,
                AllowCancel = false
                };

            return(authenticator);
        }
Exemplo n.º 32
0
        public LoginFacebookRenderer()
        {
            var oauth = new OAuth2Authenticator(
                clientId: "841136649785658",
                scope: "",
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
                );

            oauth.Completed += async(sender, args) => {
                if (args.IsAuthenticated)
                {
                    var token   = args.Account.Properties["access_token"].ToString();
                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,first_name,last_name,email,birthday,hometown"), null, args.Account);
                    var answerd = await request.GetResponseAsync();

                    dynamic   fbUser = JsonConvert.DeserializeObject(answerd.GetResponseText());
                    ModelUser user   = new ModelUser();
                    user.Name        = fbUser.first_name.ToString().Replace("\"", "");
                    user.Login       = fbUser.name.ToString().Replace("\"", "");
                    user.Login       = user.Login.Replace(" ", "");
                    user.Password    = fbUser.id.ToString().Replace("\"", "");
                    user.EmailAdress = user.Login + "@facebook.com";
                    if (fbUser.last_name != null)
                    {
                        user.LastName = fbUser.last_name.ToString().Replace("\"", "");
                    }
                    if (fbUser.email != null)
                    {
                        user.EmailAdress = fbUser.email.ToString().Replace("\"", "");
                    }
                    if (fbUser.birthday != null)
                    {
                        string[] date = fbUser.birthday.ToString().Replace("\"", "").Split('/');
                        if (date.Length == 1)
                        {
                            user.BirthDay = date[0];
                        }
                        else if (date.Length == 2)
                        {
                            user.BirthDay = date[1] + "/" + date[0];
                        }
                        else if (date.Length == 3)
                        {
                            user.BirthDay = date[1] + "/" + date[0] + "/" + date[2];
                        }
                    }
                    if (fbUser.hometown != null)
                    {
                        user.City = fbUser.hometown.ToString().Replace("\"", "");
                    }
                    ServicesDBUser dbUser = new ServicesDBUser(App.DbPath);
                    if (dbUser.Locale(user.Login))
                    {
                        dbUser.Insert(user);
                    }
                    else
                    {
                        user.Id = dbUser.LocaleByLogin(user.Login).Id;
                    }
                    App.Current.MainPage = new NavigationPage(new Home(user.Id));
                }
                else
                {
                    App.Current.MainPage = new NavigationPage(new LoginPage());
                }
            };
            var activity = this.Context as Activity;

            activity.StartActivity(oauth.GetUI(activity));
        }
Exemplo n.º 33
0
        void LoginToFacebook(bool allowCancel)
        {
            var    loginPage    = Element as FBLoginPage;
            string providername = loginPage.ProviderName;


            OAuth2Authenticator auth = null;

            switch (providername)
            {
            case "Google":
            {
                auth = new OAuth2Authenticator(
                    // For Google login, for configure refer https://code.msdn.microsoft.com/Register-Identity-Provider-41955544
                    App.ClientId,
                    App.ClientSecret,
                    // Below values do not need changing
                    "https://www.googleapis.com/auth/userinfo.email",
                    new Uri(App.url2),
                    new Uri(App.url3),                // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri(App.url4)
                    );

                break;
            }

            case "FaceBook":
            {
                auth = new OAuth2Authenticator(
                    clientId: App.AppId,
                    scope: App.ExtendedPermissions,
                    authorizeUrl: new Uri(App.AuthorizeUrl),
                    redirectUrl: new Uri(App.RedirectUrl));
                break;
            }
            }

            auth.AllowCancel = allowCancel;

            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += async(s, eargs) =>
            {
                if (!eargs.IsAuthenticated)
                {
                    return;
                }
                else
                {
                    //var token = eargs.Account.Properties["access_token"];

                    if (providername.Equals("FaceBook"))
                    {
                        // Now that we're logged in, make a OAuth2 request to get the user's info.
                        var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,picture,email"), null, eargs.Account);
                        var result  = await request.GetResponseAsync();

                        string resultText = result.GetResponseText();
                        var    obj        = JsonValue.Parse(resultText);
                        // Console.WriteLine(token + " -=- " + resultText);

                        App.FacebookId   = obj["id"];
                        App.FacebookName = obj["name"];
                        App.EmailAddress = obj["email"];
                        App.ProfilePic   = obj["picture"]["data"]["url"];
                        //
                        //saveset(obj["id"], obj["name"]);

                        // Get Shared User Defaults
                        var plist = NSUserDefaults.StandardUserDefaults;
                        // Save value
                        plist.SetString(obj["id"], "PrefId");
                        plist.SetString(obj["name"], "PrefName");
                        // Sync changes to database
                        plist.Synchronize();
                    }
                    else
                    {
                        var request = new OAuth2Request("GET", new Uri("https://www.googleapis.com/plus/v1/people/me/openIdConnect"), null, eargs.Account);
                        var result  = await request.GetResponseAsync();

                        string resultText = result.GetResponseText();
                        var    obj        = JsonValue.Parse(resultText);

                        /*string username = (string)obj["name"];
                         * string email = (string)obj["email"];*/



                        App.FacebookId   = obj["sub"];
                        App.FacebookName = obj["name"];
                        App.EmailAddress = obj["email"];
                        App.ProfilePic   = obj["picture"];
                        //
                        // saveset(obj["id"], obj["name"]);

                        // Get Shared User Defaults
                        var plist = NSUserDefaults.StandardUserDefaults;
                        // Save value
                        plist.SetString(obj["id"], "PrefId");
                        plist.SetString(obj["name"], "PrefName");
                        // Sync changes to database
                        plist.Synchronize();
                    }

                    // On Android: store the account
                    //AccountStore.Create(Context).Save(eargs.Account, "Facebook");
                    //AccountStore.Create().Save(eargs.Account, "Facebook");  //Account object is securely saved on the iOS platform

                    //Save as a new user to the database
                    await App.UserManager.SaveTaskAsync
                        (new Models.User {
                        FBID = App.FacebookId, UserName = App.FacebookName, Email = App.EmailAddress, ImgLink = App.ProfilePic
                    }, true);


                    //retreive gcm id
                    // var prefs = Android.App.Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
                    //string id = prefs.GetString("regId", null);

                    //RegisterAsync(id, new string[] { App.FacebookId + "T" }, App.FacebookId);

                    await App.Current.MainPage.Navigation.PopModalAsync();

                    App.IsLoggedIn = true;
                    ((App)App.Current).SaveProfile();
                    ((App)App.Current).PresentMainPage();
                }
            };


            UIViewController vc = (UIViewController)auth.GetUI();

            ViewController.AddChildViewController(vc);
            ViewController.View.Add(vc.View);

            vc.ChildViewControllers[0].NavigationItem.LeftBarButtonItem = new UIBarButtonItem(
                UIBarButtonSystemItem.Cancel, async(o, eargs) => await App.Current.MainPage.Navigation.PopModalAsync()
                );
        }
Exemplo n.º 34
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            // Try to cancel any existing authentication process.
            _taskCompletionSource?.TrySetCanceled();

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            _auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: new Uri(OAuthRedirectUrl))
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            _auth.Completed += (o, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete.
                    InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); });

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    _auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            _auth.Error += (o, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    _taskCompletionSource?.TrySetCanceled();
                }

                // Cancel authentication.
                _auth.OnCancelled();
                _auth = null;
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); });

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Exemplo n.º 35
0
        public void createUserLinkedin()
        {
            CreateUserData udata = new CreateUserData();
            var            auth  = new OAuth2Authenticator(
                clientId: "77c1rz71bj79xe",
                clientSecret: "ixk8ykW2zSTqYLes",
                scope: "r_basicprofile r_emailaddress",
                authorizeUrl: new Uri("https://www.linkedin.com/uas/oauth2/authorization"),
                redirectUrl: new Uri("http://www.i9acao.com.br/"),
                accessTokenUrl: new Uri("https://www.linkedin.com/uas/oauth2/accessToken")
                );

            auth.AllowCancel = true;
            Forms.Context.StartActivity(auth.GetUI(Forms.Context));
            auth.Completed += (sender2, eventArgs) =>
            {
                if (eventArgs.IsAuthenticated)
                {
                    string dd = eventArgs.Account.Username;
                    string imageServerPath;
                    var    values = eventArgs.Account.Properties;

                    var access_token = values["access_token"];
                    try
                    {
                        var request = System.Net.HttpWebRequest.Create(string.Format(@"https://api.linkedin.com/v1/people/~:(firstName,lastName,headline,picture-url,positions,email-address )?oauth2_access_token=" + access_token + "&format=json", ""));
                        request.ContentType = "application/json";
                        request.Method      = "GET";

                        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                        {
                            System.Console.Out.WriteLine("Stautus Code is: {0}", response.StatusCode);

                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();
                                if (!string.IsNullOrWhiteSpace(content))
                                {
                                    System.Console.Out.WriteLine(content);
                                }


                                var result = JsonConvert.DeserializeObject <dynamic>(content);
                                udata.Job          = (string)result["headline"];
                                udata.Email        = (string)result["emailAddress"];
                                udata.Name         = (string)result["firstName"] + " " + (string)result["lastName"];
                                udata.Password     = access_token;
                                udata.Phone        = " ";
                                udata.ProfileImage = (string)result["pictureUrl"];
                                imageServerPath    = (string)result["pictureUrl"];
                                udata.ScorePoints  = 0;

                                //UserController.Instance.RegisterUserLinkedin(udata, imageServerPath);
                                UserController.Instance.GetUserLinkedinPasswd(udata, imageServerPath);
                            }
                        }
                    }
                    catch (Exception exx)
                    {
                        System.Console.WriteLine(exx.ToString());
                    }
                }
            };
        }
Exemplo n.º 36
0
        private void Authenticate(Xamarin.Auth.Helpers.OAuth2 oauth2)
        {
            if (string.IsNullOrEmpty(oauth2.OAuth_SecretKey_ConsumerSecret_APISecret))
            {
                if (oauth2.OAuth_UriAccessToken_UriRequestToken == null)
                {
                    // Step 1.1 Creating and configuring an Authenticator
                    Auth2 = new OAuth2Authenticator
                            (
                        clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                        scope: oauth2.OAuth2_Scope,
                        authorizeUrl: oauth2.OAuth_UriAuthorization,
                        redirectUrl: oauth2.OAuth_UriCallbackAKARedirect,
                        // Native UI API switch
                        //      true    - NEW native UI support
                        //      false   - OLD embedded browser API [DEFAULT]
                        // DEFAULT will be switched to true in the near future 2017-04
                        isUsingNativeUI: test_native_ui

                            )
                    {
                        ShowErrors  = false,
                        AllowCancel = oauth2.AllowCancel,
                    };
                }
                else //if (oauth2.OAuth_UriAccessToken_UriRequestToken != null)
                {
                    // Step 1.1 Creating and configuring an Authenticator
                    Auth2 = new OAuth2Authenticator
                            (
                        clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                        clientSecret: oauth2.OAuth_SecretKey_ConsumerSecret_APISecret,
                        scope: oauth2.OAuth2_Scope,
                        authorizeUrl: oauth2.OAuth_UriAuthorization,
                        redirectUrl: oauth2.OAuth_UriCallbackAKARedirect,
                        accessTokenUrl: oauth2.OAuth_UriAccessToken_UriRequestToken,
                        // Native UI API switch
                        //      true    - NEW native UI support
                        //      false   - OLD embedded browser API [DEFAULT]
                        // DEFAULT will be switched to true in the near future 2017-04
                        isUsingNativeUI: test_native_ui

                            )
                    {
                        ShowErrors  = false,
                        AllowCancel = oauth2.AllowCancel,
                    };
                }
            }
            else
            {
                // Step 1.1 Creating and configuring an Authenticator
                Auth2 = new OAuth2Authenticator
                        (
                    clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                    clientSecret: oauth2.OAuth_SecretKey_ConsumerSecret_APISecret,
                    scope: oauth2.OAuth2_Scope,
                    authorizeUrl: oauth2.OAuth_UriAuthorization,
                    redirectUrl: oauth2.OAuth_UriCallbackAKARedirect,
                    accessTokenUrl: oauth2.OAuth_UriAccessToken_UriRequestToken,
                    // Native UI API switch
                    //      true    - NEW native UI support
                    //      false   - OLD embedded browser API [DEFAULT]
                    // DEFAULT will be switched to true in the near future 2017-04
                    isUsingNativeUI: test_native_ui

                        )
                {
                    ShowErrors  = false,
                    AllowCancel = oauth2.AllowCancel,
                };
            }


            // Step 1.2 Subscribing to Authenticator events
            // If authorization succeeds or is canceled, .Completed will be fired.
            Auth2.Completed         += Auth_Completed;
            Auth2.Error             += Auth_Error;
            Auth2.BrowsingCompleted += Auth_BrowsingCompleted;

            // Step 2.1 Creating Login UI
            global::Android.Content.Intent ui_object = Auth2.GetUI(this);

            if (Auth2.IsUsingNativeUI == true)
            {
                // Step 2.2 Customizing the UI - Native UI [OPTIONAL]
                // In order to access CustomTabs API
                Xamarin.Auth.CustomTabsConfiguration.AreAnimationsUsed          = true;
                Xamarin.Auth.CustomTabsConfiguration.IsShowTitleUsed            = false;
                Xamarin.Auth.CustomTabsConfiguration.IsUrlBarHidingUsed         = false;
                Xamarin.Auth.CustomTabsConfiguration.IsCloseButtonIconUsed      = false;
                Xamarin.Auth.CustomTabsConfiguration.IsActionButtonUsed         = false;
                Xamarin.Auth.CustomTabsConfiguration.IsActionBarToolbarIconUsed = false;
                Xamarin.Auth.CustomTabsConfiguration.IsDefaultShareMenuItemUsed = false;
                Xamarin.Auth.CustomTabsConfiguration.MenuItemTitle = null;
                Xamarin.Auth.CustomTabsConfiguration.ToolbarColor  = global::Android.Graphics.Color.Orange;
            }

            // Step 3 Present/Launch the Login UI
            StartActivity(ui_object);

            return;
        }
Exemplo n.º 37
0
 public static void CreateAuthenticator()
 {
     authenticator = new OAuth2Authenticator(FACEBOOK_APP_ID, scope_facebook, facebookAuthorizeUrl, facebookRedirectUrl);
 }
Exemplo n.º 38
0
        /// <summary>
        /// Processes the request based on the path.
        /// </summary>
        /// <param name="context">Contains the request and response.</param>
        public void ProcessRequest(HttpContext context)
        {
            // Redirect base path to signin.
            if (context.Request.Path.EndsWith("/"))
            {
                context.Response.RedirectPermanent("signin.ashx");
            }


            // This is reached when the root document is passed. Return HTML
            // using index.html as a template.
            if (context.Request.Path.EndsWith("/signin.ashx"))
            {
                String state = (String)context.Session["state"];

                // Store a random string in the session for verifying
                // the responses in our OAuth2 flow.
                if (state == null)
                {
                    Random        random  = new Random((int)DateTime.Now.Ticks);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.Append(Convert.ToChar(
                                           Convert.ToInt32(Math.Floor(
                                                               26 * random.NextDouble() + 65))));
                    }
                    state = builder.ToString();
                    context.Session["state"] = state;
                }

                // Render the templated HTML.
                String templatedHTML = File.ReadAllText(
                    context.Server.MapPath("index.html"));
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID);
                templatedHTML = Regex.Replace(templatedHTML,
                                              "[{]{2}\\s*STATE\\s*[}]{2}", state);

                context.Response.ContentType = "text/html";
                context.Response.Write(templatedHTML);
                return;
            }

            if (context.Session["authState"] == null)
            {
                // The connect action exchanges a code from the sign-in button,
                // verifies it, and creates OAuth2 credentials.
                if (context.Request.Path.Contains("/connect"))
                {
                    // Get the code from the request POST body.
                    StreamReader sr = new StreamReader(
                        context.Request.InputStream);
                    string code = sr.ReadToEnd();

                    string state = context.Request["state"];

                    // Test that the request state matches the session state.
                    if (!state.Equals(context.Session["state"]))
                    {
                        context.Response.StatusCode = 401;
                        return;
                    }

                    // Manually perform the OAuth2 flow for now.
                    var authObject = ManualCodeExchanger.ExchangeCode(code);

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = CreateState(
                        authObject.access_token, authObject.refresh_token,
                        DateTime.UtcNow,
                        DateTime.UtcNow.AddSeconds(authObject.expires_in));

                    string   id_token = authObject.id_token;
                    string[] segments = id_token.Split('.');

                    string base64EncoodedJsonBody = segments[1];
                    int    mod4 = base64EncoodedJsonBody.Length % 4;
                    if (mod4 > 0)
                    {
                        base64EncoodedJsonBody += new string( '=', 4 - mod4 );
                    }
                    byte[] encodedBodyAsBytes =
                        System.Convert.FromBase64String(base64EncoodedJsonBody);
                    string json_body =
                        System.Text.Encoding.UTF8.GetString(encodedBodyAsBytes);
                    IDTokenJsonBodyObject bodyObject =
                        JsonConvert.DeserializeObject <IDTokenJsonBodyObject>(json_body);
                    string gplus_id = bodyObject.sub;
                }
                else
                {
                    // No cached state and we are not connecting.
                    context.Response.StatusCode = 400;
                    return;
                }
            }
            else if (context.Request.Path.Contains("/connect"))
            {
                // The user is already connected and credentials are cached.
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = 200;
                context.Response.Write(JsonConvert.SerializeObject("Current user is already connected."));
                return;
            }
            else
            {
                // Register the authenticator and construct the Plus service
                // for performing API calls on behalf of the user.
                _authState =
                    (IAuthorizationState)context.Session["authState"];
                AuthorizationServerDescription description =
                    GoogleAuthenticationServer.Description;
                var provider = new WebServerClient(description);
                provider.ClientIdentifier = CLIENT_ID;
                provider.ClientSecret     = CLIENT_SECRET;
                var authenticator =
                    new OAuth2Authenticator <WebServerClient>(
                        provider,
                        GetAuthorization)
                {
                    NoCaching = true
                };
                ps = new PlusService(new BaseClientService.Initializer()
                {
                    Authenticator = authenticator
                });
            }

            // Perform an authenticated API request to retrieve the list of
            // people that the user has made visible to the app.
            if (context.Request.Path.Contains("/people"))
            {
                // Get the PeopleFeed for the currently authenticated user.
                PeopleFeed pf = ps.People.List("me", PeopleResource.CollectionEnum.Visible).Fetch();

                // This JSON, representing the people feed, will later be
                // parsed by the JavaScript client.
                string jsonContent =
                    Newtonsoft.Json.JsonConvert.SerializeObject(pf);
                context.Response.ContentType = "application/json";
                context.Response.Write(jsonContent);
                return;
            }

            // Disconnect the user from the application by revoking the tokens
            // and removing all locally stored data associated with the user.
            if (context.Request.Path.Contains("/disconnect"))
            {
                // Perform a get request to the token endpoint to revoke the
                // refresh token.
                _authState =
                    (IAuthorizationState)context.Session["authState"];
                string token = (_authState.RefreshToken != null) ?
                               _authState.RefreshToken : _authState.AccessToken;

                WebRequest request = WebRequest.Create(
                    "https://accounts.google.com/o/oauth2/revoke?token=" +
                    token);

                WebResponse response = request.GetResponse();

                // Remove the cached credentials.
                context.Session["authState"] = null;

                // You could reset the state in the session but you must also
                // reset the state on the client.
                // context.Session["state"] = null;
                context.Response.Write(
                    response.GetResponseStream().ToString().ToCharArray());
                return;
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Authentication in this instance refers to the third party authenticator, not our service.
        /// </summary>
        /// <param name="navigation"></param>
        public void startAuthentication(INavigation navigation)
        {
            Debug.WriteLine("DHB:ThirdPartyAuthentiator:startAuthentication start");
            this.navigation = navigation;

            if (authorizeUrl == null)
            {
                // default to facebook as google doesn't work on all platforms.
                configForFacebook();
            }

            /*
             * if (Device.OS == TargetPlatform.iOS) {
             *  // clientId; clientSecret; permissionsRequest; authorizeUrl; redirectUrl; accessTokenUrl; username; isNativeUI
             *  authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
             * } else if (Device.OS == TargetPlatform.Android) {
             *  authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
             * } else {
             *  return;  // no oauth available.
             * }
             */
            if (method == METHOD_FACEBOOK)
            {
                //authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, null, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, true);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectYrl, usernameAsync, isUsingNativeUI);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl, null, false);
                //authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl, null, true);
                authenticator = new OAuth2Authenticator(clientId, scope, authorizeUrl, redirectUrl);
                //authenticator.Scheme =
            }
            else if (method == METHOD_GOOGLE)
            {
                authenticator = new OAuth2Authenticator(clientId, clientSecret, scope, authorizeUrl, redirectUrl, accessTokenUrl, null, true);
            }
            else
            {
                return;  // no oauth available.
            }

            // hook up listeners for the auth events.
            authenticator.Completed += OnAuthCompleted;
            authenticator.Error     += OnAuthError;

            Device.OnPlatform(iOS: () =>
            {
                // init the ui
                PlatformSpecificCalls.authInit();
                // and launch...
                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator);
            },
                              Android: () =>
            {
                // why does this work??? there's no tie to the authenticator...
                // Note: According to facebook docs, this only works if fbook installed on the device (have not tested).
                //navigation.PushModalAsync(new OAuthLoginPage());

                //navigation.PushModalAsync(new Xamarin.Auth.XamarinForms.AuthenticatorPage()); fail

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

                //PlatformSpecificCalls.authInit();

                /* This produces a blank page...   */

                /*
                 * Xamarin.Auth.XamarinForms.AuthenticatorPage ap;
                 * ap = new Xamarin.Auth.XamarinForms.AuthenticatorPage() {
                 *  Authenticator = authenticator,
                 * };
                 * NavigationPage np = new NavigationPage(ap);
                 * navigation.PushModalAsync(np);
                 * //navigation.PushAsync(np);
                 * // */
            }
                              );
            Debug.WriteLine("DHB:ThirdPartyAuthentiator:startAuthentication end");
        }
Exemplo n.º 40
0
        private void Authenticate(Xamarin.Auth.Helpers.OAuth2 oauth2)
        {
            if (oauth2.OAuth2_UriRequestToken == null || string.IsNullOrEmpty(oauth2.OAuth_SecretKey_ConsumerSecret_APISecret))
            {
                //-------------------------------------------------------------
                // WalkThrough Step 1
                //      setting up Authenticator object
                // Implicit
                Auth2 = new OAuth2Authenticator
                        (
                    clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                    scope: oauth2.OAuth2_Scope,
                    authorizeUrl: oauth2.OAuth_UriAuthorization,
                    redirectUrl: oauth2.OAuth_UriCallbackAKARedirect,
                    // Native UI API switch
                    //      true    - NEW native UI support
                    //      false   - OLD embedded browser API [DEFAULT]
                    // DEFAULT will be switched to true in the near future 2017-04
                    isUsingNativeUI: test_native_ui
                        )
                {
                    ShowErrors  = false,
                    AllowCancel = oauth2.AllowCancel,
                };
                //-------------------------------------------------------------
            }
            else
            {
                //-------------------------------------------------------------
                // WalkThrough Step 1
                //      setting up Authenticator object
                // Explicit
                Auth2 = new OAuth2Authenticator
                        (
                    clientId: oauth2.OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer,
                    clientSecret: oauth2.OAuth_SecretKey_ConsumerSecret_APISecret,
                    scope: oauth2.OAuth2_Scope,
                    authorizeUrl: oauth2.OAuth_UriAuthorization,
                    redirectUrl: oauth2.OAuth_UriCallbackAKARedirect,
                    accessTokenUrl: oauth2.OAuth2_UriRequestToken,
                    // Native UI API switch
                    //      true    - NEW native UI support
                    //      false   - OLD embedded browser API [DEFAULT]
                    // DEFAULT will be switched to true in the near future 2017-04
                    isUsingNativeUI: test_native_ui
                        )
                {
                    ShowErrors  = false,
                    AllowCancel = oauth2.AllowCancel,
                };
                //-------------------------------------------------------------
            }


            // If authorization succeeds or is canceled, .Completed will be fired.
            Auth2.Completed         += Auth_Completed;
            Auth2.Error             += Auth_Error;
            Auth2.BrowsingCompleted += Auth_BrowsingCompleted;



            //=================================================================
            // WalkThrough Step 1.1
            //      Launching UI
            //      [REQUIRED]

            //  add custom schema (App Linking) handling
            //    in AppDelegate.cs
            //         public override bool OpenUrl
            //                                (
            //                                    UIApplication application,
            //                                    NSUrl url,
            //                                    string sourceApplication,
            //                                    NSObject annotation
            //                                )
            //
            //  NOTE[s]
            //  *   custom scheme support only
            //      xamarinauth://localhost
            //      xamarin-auth://localhost
            //      xamarin.auth://localhost
            //  *   no http[s] scheme support


            //#####################################################################
            // WalkThrough Step 2
            //      creating Presenter (UI) for specific platform
            // Xamarin.Auth API - Breaking Change
            //      old API returned UIKit.UIViewController
            // UIViewController ui_controller = auth.GetUI ();
            //      new API returns System.Object
            UIViewController ui_object = Auth2.GetUI();


            if (Auth2.IsUsingNativeUI == true)
            {
                //=================================================================
                // WalkThrough Step 2.1
                //      casting UI object to proper type to work with
                //
                // Xamarin.Auth API - Native UI support
                //      *   Android - [Chrome] Custom Tabs on Android
                //          Android.Support.CustomTabs
                //          and
                //      *   iOS -  SFSafariViewController
                //          SafariServices.SFSafariViewController
                // on 2014-04-20 google (and some other providers) will work only with this API
                //
                //
                //  2017-03-25
                //      NEW UPCOMMING API undocumented work in progress
                //      soon to be default
                //      optional API in the future (for backward compatibility)
                //
                //  required part
                //  add
                //     following code:

                SafariServices.SFSafariViewController c = null;
                c = (SafariServices.SFSafariViewController)ui_object;

                this.UICustomization(c);

                //------------------------------------------------------------
                ui_object = c;
            }

            PresentViewController(ui_object, true, null);
            //=================================================================
            //#####################################################################


            return;
        }
Exemplo n.º 41
0
 public GoogleAuthenticator(OAuth2Authenticator <NativeApplicationClient> authenticator)
 {
     _authenticator = authenticator;
 }
Exemplo n.º 42
0
        //this is from https://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms/24423833#24423833
        //https://forums.xamarin.com/discussion/26374/onmodelchanged-event-not-found-for-android-page-renderer
        //notice the OnModel is outdated you should use OnElementChanged but OnElementChanged is called twice
        protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.Page> e)
        {
            base.OnElementChanged(e);


            if (e.OldElement != null || Element == null)
            {
                return;
            }
            if (!instance)
            {
                Console.WriteLine("Called");
                instance = true;
                return;
            }



            //try to retrive account
            IEnumerable <Account> accounts = AccountStore.Create().FindAccountsForService("Facebook");

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            var activity = this.Context as Activity;


            //for facebook
            var auth = new OAuth2Authenticator(
                clientId: "203538636868958",                                                 // your OAuth2 client id
                scope: "",                                                                   // the scopes for the particular API you're accessing, delimited by "+" symbols
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),               // the auth URL for the service
                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")); // the redirect URL for the service

            //for google // google is non working

            /*   var auth = new OAuth2Authenticator(
             *   clientId: "833412182850-lvl6gh2pprh35dnutrnb61thgcq4efic.apps.googleusercontent.com", // your OAuth2 client id
             *   scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
             *   authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth/"), // the auth URL for the service
             *   redirectUrl: new Uri("https://www.googleapis.com/oauth2/v2/userinfo"),
             *   accessTokenUrl:new Uri("https://www.googleapis.com/oauth2/v4/token"),
             *   getUsernameAsync: null,
             *   clientSecret: "oL9klRrrltzSmmSF8Fd-Jbli"); // the redirect URL for the service
             */

            auth.Completed += (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated)
                {
                    App.SuccessfulLoginActionFacebook.Invoke();
                    // Use eventArgs.Account to do wonderful things
                    var account = eventArgs.Account;
                    var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, account);
                    AccountStore.Create().Save(eventArgs.Account, "Facebook");


                    var x = Task.Run(async() => {
                        return(await request.GetResponseAsync());
                    });
                    x.ContinueWith(
                        t =>
                    {
                        if (t.IsFaulted)
                        {
                            Console.WriteLine("Error: " + t.Exception.InnerException.Message);
                        }
                        else
                        {
                            string json = t.Result.GetResponseText();
                            Console.WriteLine(json);
                        }
                    }
                        ).ConfigureAwait(false);

                    App.SaveToken(eventArgs.Account.Properties["access_token"]);

                    App.MasterDetailPage();
                }
                else
                {
                    Console.WriteLine("User Cancelled");
                    activity.StartActivity(typeof(MainActivity)); //we restart it
                    activity.Finish();                            //we lose the previews activities entirly
                }
            };

            activity.StartActivity(auth.GetUI(activity));
        }
Exemplo n.º 43
0
        //private static readonly TaskScheduler UIScheduler = TaskScheduler.FromCurrentSynchronizationContext();

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            viewModel = new LoginWithGmailViewModel();

            // this is a ViewGroup - so should be able to load an AXML file and FindView<>
            //var activity = this.Context as Activity;

            if (Constant.IsGoogleLogin)
            {
                auth = new OAuth2Authenticator(
                    //clientId: "858089811668-dk50ujvabh8aqr3ek5r60q24p1adep97.apps.googleusercontent.com",
                    clientId: "380694676532-barrtug4jpe6gcmhk7a02odeos1bvnk0.apps.googleusercontent.com",
                    scope: "https://www.googleapis.com/auth/userinfo.email",                // The scopes for the particular API you're accessing. The format for this will vary by API.
                    authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),     // the auth URL for the service
                    redirectUrl: new Uri("https://www.googleapis.com/plus/v1/people/me"));  // the redirect URL for the service


                auth.Completed += async(sender, eventArgs) =>
                {
                    if (eventArgs.IsAuthenticated)
                    {
                        var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                        UserDialogs.Instance.ShowLoading();
                        //App.Instance.SuccessfulLoginAction.Invoke();
                        // Use eventArgs.Account to do wonderful things
                        App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);

                        // Now that we're logged in, make a OAuth2 request to get the user's info.
                        var request = new OAuth2Request("GET", new Uri("https://www.googleapis.com/oauth2/v2/userinfo"), null, eventArgs.Account);
                        //var request = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
                        var response = await request.GetResponseAsync();

                        if (response != null)
                        {
                            string userJson = response.GetResponseText();//All details of User in Json format which can be used further(can be stored in Manager and shown in view).
                            var    obj      = JsonValue.Parse(userJson);
                            viewModel.FirstName   = (string)obj["given_name"];
                            viewModel.LastName    = (string)obj["family_name"];
                            viewModel.Email       = (string)obj["email"];
                            viewModel._Base64_Img = (string)obj["picture"];

                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                viewModel.AccessToken = accessToken;
                                // viewModel.GoogleCommand.Execute(this);
                            }
                            //App.Instance.UserName = viewModel.FirstName + " " + viewModel.LastName;

                            App.baseUser.FirstName   = viewModel.FirstName;
                            App.baseUser.LastName    = viewModel.LastName;
                            App.baseUser.EmailId     = viewModel.Email;
                            App.baseUser.UserImage   = viewModel._Base64_Img;
                            App.baseUser.AccessToken = viewModel.AccessToken;
                            Constant.IsGoogleLogin   = false;
                            App.Instance.SuccessfulLoginAction.Invoke();
                        }
                        else
                        {
                            // The user cancelled
                        }
                    }
                    else
                    {
                        Constant.IsGoogleLogin = false;
                    }
                };
            }
            else if (Constant.IsFacebookLogin)
            {
                auth = new OAuth2Authenticator(
                    clientId: "384018465086414",
                    scope: "email",
                    authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                    redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

                //auth.AllowCancel = allowCancel;

                auth.Completed += async(sender, eventArgs) =>
                {
                    if (eventArgs.IsAuthenticated)
                    {
                        var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                        UserDialogs.Instance.ShowLoading();
                        //App.Instance.SuccessfulLoginAction.Invoke();
                        // Use eventArgs.Account to do wonderful things
                        App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);

                        // Now that we're logged in, make a OAuth2 request to get the user's info.
                        var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me/"), null, eventArgs.Account);
                        //var request = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
                        var response = await request.GetResponseAsync();

                        if (response != null)
                        {
                            string userJson = response.GetResponseText();//All details of User in Json format which can be used further(can be stored in Manager and shown in view).
                            var    obj      = JsonValue.Parse(userJson);

                            viewModel.FirstName   = (string)obj["first_name"];
                            viewModel.LastName    = (string)obj["last_name"];
                            viewModel.Email       = (string)obj["email"];
                            viewModel._Base64_Img = "https://graph.facebook.com/" + (string)obj["id"] + "/picture";

                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                viewModel.AccessToken = accessToken;
                                // viewModel.GoogleCommand.Execute(this);
                            }

                            //App.Instance.UserName = viewModel.FirstName + " " + viewModel.LastName;
                            App.baseUser.FirstName   = viewModel.FirstName;
                            App.baseUser.LastName    = viewModel.LastName;
                            App.baseUser.EmailId     = viewModel.Email;
                            App.baseUser.UserImage   = viewModel._Base64_Img;
                            App.baseUser.AccessToken = viewModel.AccessToken;
                            Constant.IsFacebookLogin = false;
                            App.Instance.SuccessfulLoginAction.Invoke();
                        }
                        else
                        {
                            // The user cancelled
                        }
                    }
                    else
                    {
                        Constant.IsFacebookLogin = false;
                    }
                };
            }

            //activity.StartActivity(auth.GetUI(activity));
        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task.
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Get the current Android Activity.
            Activity activity = (Activity)this;

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
                    activity.FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        activity.FinishActivity(99);
                    }
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
            Android.Content.Intent intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);

            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Exemplo n.º 45
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            /*
             * //Facebook login api
             * var auth = new OAuth2Authenticator(
             *  clientId: "1270606036289960",
             *  scope: "",
             *  authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
             * //                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
             *  redirectUrl: new Uri("http://myjobupwork.com/fblogin/"));
             *
             *
             * //StartActivity (auth.GetUI(Application.Context));
             *
             * auth.Completed += (sender, eventArgs) =>
             * {
             *  // We presented the UI, so it's up to us to dimiss it on iOS.
             *
             *
             *  if (eventArgs.IsAuthenticated)
             *  {
             *      // Use eventArgs.Account to do wonderful things
             *
             *      string access_token;
             *      eventArgs.Account.Properties.TryGetValue("access_token", out access_token);
             *      //Toast.MakeText(this, "Authenticate Token:" + access_token, ToastLength.Short).Show();
             *      var myurl = "https://graph.facebook.com/me?access_token=" + access_token;
             *      Uri uri = new Uri(myurl);
             *      HttpWebRequest request = new HttpWebRequest(uri);
             *      request.Method = "GET";
             *
             *
             *      HttpWebResponse response = request.GetResponse() as HttpWebResponse;
             *      using (StreamReader sr = new StreamReader(response.GetResponseStream()))
             *      {
             *          string responseString = sr.ReadToEnd();
             *          Newtonsoft.Json.Linq.JObject myjObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
             *          var myid = (string)myjObject["id"];
             *          Toast.MakeText(this, "Your Facebook UserId:" + myid, ToastLength.Short).Show();
             *
             *      }
             *      response.Close();
             *  }
             * };
             */
            /*
             * //Google Login
             * var auth = new OAuth2Authenticator(clientId: "544771199531-lfe6dn212h2ch38f5i4uaah5j7c2qs00.apps.googleusercontent.com",
             * scope: "https://www.googleapis.com/auth/userinfo.email",
             * authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
             * redirectUrl: new Uri("http://myjobupwork.com/ggplus/"),
             * getUsernameAsync: null);
             *
             *
             * auth.Completed += async (sender, e) =>
             * {
             *  if (!e.IsAuthenticated)
             *  {
             *      Toast.MakeText(this, "Fail to authenticate!", ToastLength.Short).Show();
             *      return;
             *  }
             *  string access_token;
             *  e.Account.Properties.TryGetValue("access_token", out access_token);
             *
             *  var myurl = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + access_token;
             *  Uri uri = new Uri(myurl);
             *  HttpWebRequest request = new HttpWebRequest(uri);
             *  request.Method = "GET";
             *
             *
             *  HttpWebResponse response = request.GetResponse() as HttpWebResponse;
             *  using (StreamReader sr = new StreamReader(response.GetResponseStream()))
             *  {
             *      string responseString = sr.ReadToEnd();
             *      Newtonsoft.Json.Linq.JObject myjObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
             *      var myid = (string)myjObject["id"];
             *      ISQLiteConnection conn = null;
             *
             *      ISQLiteConnectionFactory factory = new MvxDroidSQLiteConnectionFactory();
             *
             *      var sqlitedir = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
             *      string filenameaction = sqlitedir.Path + "/mysqlitesas.db";
             *
             *      conn = factory.Create(filenameaction);
             *      conn.CreateTable<Azurecon>();
             *      conn.DeleteAll<Azurecon>();
             *      conn.Insert(new Azurecon() { Sastring = "", UserType = "Google", UserId = myid });
             *      Toast.MakeText(this, "Your Google UserId:" + myid, ToastLength.Short).Show();
             *      conn.Close();
             *  }
             *  response.Close();
             * };
             *
             * var intent = auth.GetUI(this);
             * StartActivity(intent);
             *
             * // Set our view from the "main" layout resource
             */
            //login layout xml
            SetContentView(Resource.Layout.Main);
            Button buttonfacelogin   = FindViewById <Button>(Resource.Id.buttonfacebooklogin);
            Button buttongooglelogin = FindViewById <Button>(Resource.Id.buttongooglelogin);

            buttonfacelogin.Click += delegate
            {
                //Facebook login api
                var auth = new OAuth2Authenticator(
                    clientId: "1270606036289960",
                    scope: "email",
                    authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                    //                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
                    redirectUrl: new Uri("http://myjobupwork.com/fblogin/"));


                //StartActivity (auth.GetUI(Application.Context));

                auth.Completed += (sender, eventArgs) =>
                {
                    // We presented the UI, so it's up to us to dimiss it on iOS.
                    if (!eventArgs.IsAuthenticated)
                    {
                        Toast.MakeText(this, "Fail to authenticate!", ToastLength.Short).Show();
                        return;
                    }

                    if (eventArgs.IsAuthenticated)
                    {
                        // Use eventArgs.Account to do wonderful things

                        string access_token;
                        eventArgs.Account.Properties.TryGetValue("access_token", out access_token);
                        //Toast.MakeText(this, "Authenticate Token:" + access_token, ToastLength.Short).Show();
                        var myurl = "https://graph.facebook.com/me?fields=id,email&access_token=" + access_token;

                        Uri            uri     = new Uri(myurl);
                        HttpWebRequest request = new HttpWebRequest(uri);
                        request.Method = "GET";


                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = sr.ReadToEnd();
                            Newtonsoft.Json.Linq.JObject myjObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
                            var myid    = (string)myjObject["id"];
                            var myemail = (string)myjObject["email"];
                            var myurlui = "https://graph.facebook.com/me/permissions" + "?fields=id,email" + "&access_token=" + access_token;



                            ISQLiteConnection conn = null;

                            ISQLiteConnectionFactory factory = new MvxDroidSQLiteConnectionFactory();

                            var    sqlitedir      = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
                            string filenameaction = sqlitedir.Path + "/mysqlitesas.db";
                            string myuseridfb     = "fb" + myid;
                            if (myemail.Length < 3)
                            {
                                myemail = myuseridfb;
                            }

                            conn = factory.Create(filenameaction);
                            conn.CreateTable <Azurecon>();
                            //conn.CreateCommand("Delete from Azurecon").ExecuteNonQuery();
                            int countrow = 0;
                            foreach (var eu in conn.Table <Azurecon>().Where(eu => eu.UserType == "Facebook"))
                            {
                                countrow++;
                            }
                            if (countrow > 0)
                            {
                                conn.CreateCommand("Update Azurecon set Sastring = '' where UserType='Google'").ExecuteNonQuery();
                                conn.CreateCommand("Update Azurecon set UserId = '" + myemail + "' where UserType='Facebook'").ExecuteNonQuery();
                            }
                            else
                            {
                                conn.Insert(new Azurecon()
                                {
                                    Sastring = "", UserType = "Facebook", UserId = myemail
                                });
                            }

                            //conn.Insert(new Azurecon() { Sastring = "", UserType = "Facebook", UserId = myemail });
                            Toast.MakeText(this, "Your Facebook UserId:" + myemail, ToastLength.Short).Show();
                            //Create new container for Google userid
                            var myemailtrim = myemail.Replace("@", "");
                            myemailtrim = myemailtrim.Replace(".", "");
                            string myauzreafaceusercon = "http://93.118.34.239:8888/createcon/" + myemailtrim;
                            var    browser             = new WebView(Application.Context);
                            browser.LoadUrl(myauzreafaceusercon);

                            conn.Close();
                        }
                        response.Close();
                        SetContentView(Resource.Layout.Main1);
                        Button button         = FindViewById <Button>(Resource.Id.button);
                        Button showlistbutton = FindViewById <Button>(Resource.Id.mylist);
                        //Button uploadtoazure = FindViewById<Button>(Resource.Id.);
                        button.Click         += (s, e) => doTakePhotoAction();
                        showlistbutton.Click += delegate
                        {
                            StartActivity(typeof(MyListviewActivity));
                        };
                        Button showauzreimagebutton = FindViewById <Button>(Resource.Id.azureimagelist);
                        showauzreimagebutton.Click += delegate
                        {
                            StartActivity(typeof(AzureActivity));
                        };
                    }
                };
                ISQLiteConnection connch = null;

                ISQLiteConnectionFactory factorych = new MvxDroidSQLiteConnectionFactory();

                var    sqlitedirch      = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
                string filenameactionch = sqlitedirch.Path + "/mysqlitesas.db";
                connch = factorych.Create(filenameactionch);
                connch.CreateTable <Azurecon>();
                //conn.CreateCommand("Delete from Azurecon").ExecuteNonQuery();
                int countrowch = 0;
                foreach (var euch in connch.Table <Azurecon>().Where(euch => euch.UserType == "Facebook"))
                {
                    countrowch++;
                }
                if (countrowch > 0)
                {
                    connch.CreateCommand("Update Azurecon set Sastring = '' where UserType='Google'").ExecuteNonQuery();
                    connch.CreateCommand("Update Azurecon set Sastring = 'using' where UserType='Facebook'").ExecuteNonQuery();
                    SetContentView(Resource.Layout.Main1);
                    Button button         = FindViewById <Button>(Resource.Id.button);
                    Button showlistbutton = FindViewById <Button>(Resource.Id.mylist);
                    //Button uploadtoazure = FindViewById<Button>(Resource.Id.);
                    button.Click         += (s, e) => doTakePhotoAction();
                    showlistbutton.Click += delegate
                    {
                        StartActivity(typeof(MyListviewActivity));
                    };
                    Button showauzreimagebutton = FindViewById <Button>(Resource.Id.azureimagelist);
                    showauzreimagebutton.Click += delegate
                    {
                        StartActivity(typeof(AzureActivity));
                    };
                }
                else
                {
                    var intent = auth.GetUI(this);
                    StartActivity(intent);
                }
            };
            buttongooglelogin.Click += delegate
            {
                //Google Login
                var auth = new OAuth2Authenticator(clientId: "544771199531-lfe6dn212h2ch38f5i4uaah5j7c2qs00.apps.googleusercontent.com",
                                                   scope: "https://www.googleapis.com/auth/userinfo.email",
                                                   authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
                                                   redirectUrl: new Uri("http://myjobupwork.com/ggplus/"),
                                                   getUsernameAsync: null);


                auth.Completed += async(sender, e) =>
                {
                    if (!e.IsAuthenticated)
                    {
                        Toast.MakeText(this, "Fail to authenticate!", ToastLength.Short).Show();
                        return;
                        //SetContentView(Resource.Layout.Main);
                    }
                    else
                    {
                        string access_token;
                        e.Account.Properties.TryGetValue("access_token", out access_token);

                        var            myurl   = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + access_token;
                        Uri            uri     = new Uri(myurl);
                        HttpWebRequest request = new HttpWebRequest(uri);
                        request.Method = "GET";


                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string responseString = sr.ReadToEnd();
                            Newtonsoft.Json.Linq.JObject myjObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
                            var myid               = (string)myjObject["id"];
                            var myemail            = (string)myjObject["email"];
                            ISQLiteConnection conn = null;

                            ISQLiteConnectionFactory factory = new MvxDroidSQLiteConnectionFactory();

                            var    sqlitedir      = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
                            string filenameaction = sqlitedir.Path + "/mysqlitesas.db";
                            conn = factory.Create(filenameaction);
                            conn.CreateTable <Azurecon>();
                            int countrow = 0;
                            foreach (var eu in conn.Table <Azurecon>().Where(eu => eu.UserType == "Google"))
                            {
                                countrow++;
                            }
                            if (countrow > 0)
                            {
                                conn.CreateCommand("Update Azurecon set Sastring = '' where UserType='Facebook'").ExecuteNonQuery();
                                conn.CreateCommand("Update Azurecon set Sastring = 'using',UserId = '" + myemail + "' where UserType='Google'").ExecuteNonQuery();
                            }
                            else
                            {
                                conn.Insert(new Azurecon()
                                {
                                    Sastring = "", UserType = "Google", UserId = myemail
                                });
                            }

                            //get googleuser email

                            Toast.MakeText(this, "Your Google UserId:" + myemail, ToastLength.Short).Show();
                            //Create new container for Google userid
                            var myemailtrim = myemail.Replace("@", "");
                            myemailtrim = myemailtrim.Replace(".", "");
                            string myauzregoogleusercon = "http://93.118.34.239:8888/createcon/" + myemailtrim;
                            var    browser = new WebView(Application.Context);
                            browser.LoadUrl(myauzregoogleusercon);

                            conn.Close();
                        }
                        response.Close();

                        SetContentView(Resource.Layout.Main1);
                        Button button         = FindViewById <Button>(Resource.Id.button);
                        Button showlistbutton = FindViewById <Button>(Resource.Id.mylist);
                        //Button uploadtoazure = FindViewById<Button>(Resource.Id.);
                        button.Click         += (s, ea) => doTakePhotoAction();
                        showlistbutton.Click += delegate
                        {
                            StartActivity(typeof(MyListviewActivity));
                        };
                        Button showauzreimagebutton = FindViewById <Button>(Resource.Id.azureimagelist);
                        showauzreimagebutton.Click += delegate
                        {
                            StartActivity(typeof(AzureActivity));
                        };
                    }
                };

                ISQLiteConnection connch = null;

                ISQLiteConnectionFactory factorych = new MvxDroidSQLiteConnectionFactory();

                var    sqlitedirch      = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto");
                string filenameactionch = sqlitedirch.Path + "/mysqlitesas.db";
                connch = factorych.Create(filenameactionch);
                connch.CreateTable <Azurecon>();
                //conn.CreateCommand("Delete from Azurecon").ExecuteNonQuery();
                int countrowch = 0;
                foreach (var euch in connch.Table <Azurecon>().Where(euch => euch.UserType == "Google"))
                {
                    countrowch++;
                }
                if (countrowch > 0)
                {
                    connch.CreateCommand("Update Azurecon set Sastring = '' where UserType='Facebook'").ExecuteNonQuery();
                    connch.CreateCommand("Update Azurecon set Sastring = 'using' where UserType='Google'").ExecuteNonQuery();
                    SetContentView(Resource.Layout.Main1);
                    Button button         = FindViewById <Button>(Resource.Id.button);
                    Button showlistbutton = FindViewById <Button>(Resource.Id.mylist);
                    //Button uploadtoazure = FindViewById<Button>(Resource.Id.);
                    button.Click         += (s, e) => doTakePhotoAction();
                    showlistbutton.Click += delegate
                    {
                        StartActivity(typeof(MyListviewActivity));
                    };
                    Button showauzreimagebutton = FindViewById <Button>(Resource.Id.azureimagelist);
                    showauzreimagebutton.Click += delegate
                    {
                        StartActivity(typeof(AzureActivity));
                    };
                }
                else
                {
                    var intent = auth.GetUI(this);
                    StartActivity(intent);
                }
            };
            // Get our button from the layout resource,
            // and attach an event to it

            /*
             * SetContentView(Resource.Layout.Main1);
             * Button buttonmain = FindViewById<Button>(Resource.Id.button);
             * Button showlistbuttonmain = FindViewById<Button>(Resource.Id.mylist);
             * //Button uploadtoazure = FindViewById<Button>(Resource.Id.);
             * buttonmain.Click += (s, e) => doTakePhotoAction();
             * showlistbuttonmain.Click += delegate
             * {
             *  StartActivity(typeof(MyListviewActivity));
             * };
             * Button showauzreimagebuttonmain = FindViewById<Button>(Resource.Id.azureimagelist);
             * showauzreimagebuttonmain.Click += delegate
             * {
             *  StartActivity(typeof(AzureActivity));
             * };
             * */
        }
Exemplo n.º 46
0
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // Create a task completion source
            var taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            var authenticator = new OAuth2Authenticator(
                clientId: Configuration.AppClientID,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri);

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // hide error messages (Xamarin bug)
            authenticator.ShowErrors = false;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete
                    this.DismissViewController(true, null);

                    // Throw an exception if the user could not be authenticated
                    if (!authArgs.IsAuthenticated)
                    {
                        throw new Exception("Unable to authenticate user.");
                    }

                    // If authorization was successful, get the user's account
                    Account authenticatedAccount = authArgs.Account;

                    // Set the result (Credential) for the TaskCompletionSource
                    taskCompletionSource.SetResult(authenticatedAccount.Properties);
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    taskCompletionSource.SetException(ex);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // Dismiss the OAuth UI when complete
                this.DismissViewController(true, null);

                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else if (errArgs.Message == "OAuth Error = The user denied your request." && taskCompletionSource.Task.Status != TaskStatus.Faulted)
                {
                    authenticator.OnCancelled();
                }
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            InvokeOnMainThread(() =>
            {
                this.PresentViewController(authenticator.GetUI(), true, null);
            });

            // Return completion source task so the caller can await completion
            return(taskCompletionSource.Task);
        }
Exemplo n.º 47
0
 public void SetAuth(OAuth2Authenticator authenticator)
 {
     Authenticator = authenticator;
 }
Exemplo n.º 48
0
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            page = e.NewElement as AuthLoginPage;
            auth = page.authenticator;

            auth.Completed += (sender, eventArgs) => {
                if (eventArgs.IsAuthenticated)
                {
                    if (eventArgs.Account.Properties.Count == 3)
                    {
                        Settings.FacebookUsername = eventArgs.Account.Username;

                        Settings.FacebookState       = eventArgs.Account.Properties["state"];
                        Settings.FacebookAccessToken = eventArgs.Account.Properties["access_token"];
                        Settings.FacebookExpiresIn   = eventArgs.Account.Properties["expires_in"];

                        Dictionary <string, string> _properties = new Dictionary <string, string>();

                        _properties.Add("state", Settings.FacebookState);
                        _properties.Add("access_token", Settings.FacebookAccessToken);
                        _properties.Add("expires_in", Settings.FacebookExpiresIn);

                        Account _account = new Account(Settings.FacebookUsername, _properties);
                        AccountData.FacebookAccount = _account;

                        page.FacebookLoginAction.Invoke();
                    }
                    else if (eventArgs.Account.Properties.Count == 4)
                    {
                        Settings.GoogleUsername = eventArgs.Account.Username;

                        Settings.GoogleAccessToken = eventArgs.Account.Properties["access_token"];
                        Settings.GoogleExpiresIn   = eventArgs.Account.Properties["expires_in"];
                        Settings.GoogleIDToken     = eventArgs.Account.Properties["id_token"];
                        Settings.GoogleTokenType   = eventArgs.Account.Properties["token_type"];

                        Dictionary <string, string> _properties = new Dictionary <string, string>();

                        _properties.Add("access_token", Settings.GoogleAccessToken);
                        _properties.Add("expires_in", Settings.GoogleExpiresIn);
                        _properties.Add("id_token", Settings.GoogleIDToken);
                        _properties.Add("token_type", Settings.GoogleTokenType);

                        Account _account = new Account(Settings.GoogleUsername, _properties);
                        AccountData.GoogleAccount = _account;

                        page.GoogleLoginAction.Invoke();
                    }
                    else
                    {
                        page.FailedLoginAction.Invoke();
                    }

                    DismissViewController(true, null);
                }
                else
                {
                    page.FailedLoginAction.Invoke();
                }
            };
        }
Exemplo n.º 49
0
        private void OAuth_Clicked(object sender, EventArgs e)
        {
            try
            {
                var    socialMediaButton           = (Button)sender;
                var    socialMediaName             = socialMediaButton.Text;
                string clientId                    = null;
                string redirectUri                 = null;
                string authorizeURL                = null;
                string accessTokenURL              = null;
                OAuth2Authenticator authenticator_ = null;

                SocialMedia = socialMediaName.ToLower().Contains("google") ? "google" : "facebook";


                switch (SocialMedia)
                {
                case "facebook":
                    authenticator_ = new OAuth2Authenticator

                                     (
                        clientId: Constants.fbClientID,
                        scope: "email",
                        authorizeUrl: new Uri(Constants.FacebookOAuthURL),
                        redirectUrl: new Uri(Constants.redirectURI)

                                     )


                    ;
                    break;

                case "google":

                    switch (Xamarin.Forms.Device.RuntimePlatform)
                    {
                    case Xamarin.Forms.Device.iOS:
                        clientId    = Constants.iOSClientId;
                        redirectUri = Constants.iOSRedirectUrl;
                        break;

                    case Xamarin.Forms.Device.Android:
                        clientId    = Constants.AndroidClientId;
                        redirectUri = Constants.AndroidRedirectUrl;
                        break;
                    }


                    authorizeURL   = Constants.AuthorizeUrl;
                    accessTokenURL = Constants.AccessTokenUrl;

                    authenticator_ = new OAuth2Authenticator(
                        clientId,
                        null,
                        Constants.Scope,
                        new Uri(Constants.AuthorizeUrl),
                        new Uri(redirectUri),
                        new Uri(Constants.AccessTokenUrl),
                        null,
                        true);
                    break;

                default:
                    break;
                }



                authenticator_.Completed += OnAuthCompleted;
                authenticator_.Error     += OnAuthError;

                AuthenticationState.Authenticator = authenticator_;

                var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
                presenter.Login(authenticator_);
            }
            catch (Exception ex)
            {
                var log = ex;
                LogService.LogErrors(log.ToString());
            }
        }
        static App()
        {
            try
            {
                Container = new Container();
                var analyticsSvc    = DependencyService.Get <IAnalyticsService>();
                var userService     = new CurrentUserService();
                var orderService    = new AzureOrderService(new HttpClient(), _orderEndpoint, _apiKey);
                var propertyService = new PropertyService(new HttpClient(), _propertyEndpoint, new AnalyticsLogger <PropertyService>(analyticsSvc, userService));
                var imageService    = new BlobImageService(new HttpClient(), _blobEndpoint, new AnalyticsLogger <BlobImageService>(analyticsSvc, userService));
                var subService      = new SubscriptionService(new HttpClient(), _subEndpoint, new AnalyticsLogger <SubscriptionService>(analyticsSvc, userService));
                var prService       = new PurchasedReportService(new HttpClient(), _purchasedReportsEndpoint, new AnalyticsLogger <PurchasedReportService>(analyticsSvc, userService));
                var authenticator   = new OAuth2Authenticator(Configuration.ClientId,
                                                              null,
                                                              Configuration.Scope,
                                                              new Uri(GoogleAuthorizeUrl),
                                                              new Uri(Configuration.RedirectNoPath + ":" + Configuration.RedirectPath),
                                                              new Uri(GoogleAccessTokenUrl),
                                                              null,
                                                              true);
                var notifyService       = new NotificationService(new HttpClient(), _notifyEndpoint, _apiKey);
                var purchaseEmailLogger = new EmailLogger <PurchasingService>(notifyService, userService);
                var purchaseService     = new PurchasingService(CrossInAppBilling.Current, purchaseEmailLogger);
                authenticator.Completed += (s, e) =>
                {
                    if (e.IsAuthenticated)
                    {
                        userService.LogIn(e.Account);
                    }
                };

                // Setup caches and begin process of filling them.
                var dbBasePath    = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var propertyCache = new LocalSqlCache <PropertyModel>(Path.Combine(dbBasePath, "property.db3"),
                                                                      new AnalyticsLogger <LocalSqlCache <PropertyModel> >(analyticsSvc, userService));
                var orderCache = new LocalSqlCache <Models.Order>(Path.Combine(dbBasePath, "order.db3"),
                                                                  new AnalyticsLogger <LocalSqlCache <Models.Order> >(analyticsSvc, userService));
                var imageCache = new LocalSqlCache <ImageModel>(Path.Combine(dbBasePath, "images.db3"),
                                                                new AnalyticsLogger <LocalSqlCache <ImageModel> >(analyticsSvc, userService));
                var subCache = new LocalSqlCache <SubscriptionModel>(Path.Combine(dbBasePath, "subs.db3"),
                                                                     new AnalyticsLogger <LocalSqlCache <SubscriptionModel> >(analyticsSvc, userService));
                var settingsCache = new LocalSqlCache <SettingsModel>(Path.Combine(dbBasePath, "sets.db3"),
                                                                      new AnalyticsLogger <LocalSqlCache <SettingsModel> >(analyticsSvc, userService));
                var prCache = new LocalSqlCache <PurchasedReportModel>(Path.Combine(dbBasePath, "purchasedreports.db3"),
                                                                       new AnalyticsLogger <LocalSqlCache <PurchasedReportModel> >(analyticsSvc, userService));

                var    startUpLogger = new AnalyticsLogger <App>(analyticsSvc, userService);
                Action ClearCaches   = () =>
                {
                    try
                    {
                        orderCache.Clear();
                        propertyCache.Clear();
                        imageCache.Clear();
                        subCache.Clear();
                        prCache.Clear();
                    }
                    catch { }
                };
                Func <AccountModel, Task> RefreshCaches = user =>
                {
                    var userId = user.UserId;
                    var prTask = Task.Run(() =>
                    {
                        try
                        {
                            var prs = prService.GetPurchasedReports(userId);
                            prCache.Put(prs.ToDictionary(x => x.PurchaseId, x => x));
                        }
                        catch (Exception ex)
                        {
                            startUpLogger.LogError("Failed to get purchased reports on refresh.", ex);
                        }
                    });
                    var orderTask = Task.Run(async() =>
                    {
                        try
                        {
                            var orders   = await orderService.GetMemberOrders(userId);
                            var unCached = orders.Except(orderCache.GetAll().Select(x => x.Value).ToList(), new OrderEqualityComparer()).ToList();
                            orderCache.Put(orders.ToDictionary(x => x.OrderId, x => x));
                            var subTask = Task.Run(() =>
                            {
                                try
                                {
                                    DependencyService.Get <IMessagingSubscriber>().Subscribe(orders.Select(x => $"{(Device.RuntimePlatform == Device.Android ? App.TopicPrefix : "")}{x.OrderId}").ToList());
                                }
                                catch { }
                            });
                            var propTask = Task.Run(async() =>
                            {
                                if (!orders.Any())
                                {
                                    propertyCache.Clear();
                                    return;
                                }
                                var properties = await propertyService.GetProperties(unCached.Select(x => x.OrderId).ToList());
                                propertyCache.Update(properties);
                            });
                            var imgTask = Task.Run(() =>
                            {
                                if (!orders.Any())
                                {
                                    imageCache.Clear();
                                    return;
                                }
                                var images = imageService.GetImages(unCached.Select(x => x.OrderId).ToList());
                                imageCache.Update(images);
                            });
                            var subscriptionTask = Task.Run(async() =>
                            {
                                try
                                {
                                    // TODO: Refactor this so it can be tested.
                                    var allSubs              = subService.GetSubscriptions(userId).OrderBy(x => x.StartDateTime).ToList();
                                    var recentSub            = allSubs.LastOrDefault();
                                    var purchases            = new List <InAppBillingPurchase>();
                                    SubscriptionModel newSub = null;

                                    // Check app store purchases to see if they auto-renewed
                                    if (recentSub != null && !SubscriptionUtility.SubscriptionActive(recentSub))
                                    {
                                        try
                                        {
                                            purchases = (await purchaseService.GetPurchases(ItemType.Subscription)).ToList();
                                        }
                                        catch (Exception ex)
                                        {
                                            purchaseEmailLogger.LogError($"Error occurred while getting purchases.", ex);
                                        }
                                        var mostRecent = purchases.OrderBy(x => x.TransactionDateUtc)?.LastOrDefault();
                                        if (mostRecent != null)
                                        {
                                            newSub = SubscriptionUtility.GetModelFromIAP(mostRecent, user, recentSub);
                                            if (newSub != null)
                                            {
                                                allSubs.Add(newSub);
                                                subService.AddSubscription(newSub);
                                            }
                                        }
                                    }
                                    if (!allSubs.Any())
                                    {
                                        subCache.Clear();
                                    }
                                    else
                                    {
                                        subCache.Put(allSubs.ToDictionary(x => x.PurchaseId, x => x));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    startUpLogger.LogError("Failed to get subscriptions on refresh.", ex);
                                }
                            });
                            await Task.WhenAll(new[] { propTask, imgTask, subTask, subscriptionTask });
                        }
                        catch (Exception ex)
                        {
                            startUpLogger.LogError($"Failed to fill caches.\n{ex.ToString()}", ex);
                        }
                    });
                    return(Task.WhenAll(new[] { prTask, orderTask }));
                };

                var refresher = new CacheRefresher(new AnalyticsLogger <CacheRefresher>(analyticsSvc, userService), RefreshCaches);
                refresher.Invalidate();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                refresher.RefreshCaches(userService.GetLoggedInAccount());
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                userService.OnLoggedIn += async(s, e) =>
                {
                    ClearCaches();
                    await refresher.RefreshCaches(e.Account);
                };
                userService.OnLoggedOut += (s, e) => ClearCaches();

                // Register services
                Container.Register <IOrderService>(() => orderService, Lifestyle.Singleton);
                Container.Register <IPropertyService>(() => propertyService, Lifestyle.Singleton);
                Container.Register <IImageService>(() => imageService, Lifestyle.Singleton);
                Container.Register <INotificationService>(() => notifyService, Lifestyle.Singleton);
                Container.Register <ILogger <SingleReportPurchaseViewModel> >(() =>
                                                                              new EmailLogger <SingleReportPurchaseViewModel>(notifyService, userService), Lifestyle.Singleton);
                Container.RegisterConditional(typeof(ILogger <>), typeof(AnalyticsLogger <>), c => !c.Handled);
                Container.Register <OAuth2Authenticator>(() => authenticator, Lifestyle.Singleton);
                Container.Register <AccountStore>(() => AccountStore.Create(), Lifestyle.Singleton);
                Container.Register <ICurrentUserService>(() => userService, Lifestyle.Singleton);
                Container.Register <IPurchasingService>(() => purchaseService, Lifestyle.Singleton);
                Container.Register <ICacheRefresher>(() => refresher, Lifestyle.Singleton);
                Container.Register <ISubscriptionService>(() => subService, Lifestyle.Singleton);
                Container.Register <IOrderValidationService, OrderValidationService>();
                Container.Register <IPageFactory, PageFactory>(Lifestyle.Singleton);
                Container.Register <IToastService>(() => DependencyService.Get <IToastService>(), Lifestyle.Singleton);
                Container.Register <IMessagingSubscriber>(() => DependencyService.Get <IMessagingSubscriber>(), Lifestyle.Singleton);
                Container.Register <IMessagingCenter>(() => MessagingCenter.Instance, Lifestyle.Singleton);
                Container.Register <IPurchasedReportService>(() => prService, Lifestyle.Singleton);
                Container.Register <IAnalyticsService>(() => analyticsSvc, Lifestyle.Singleton);
                Container.Register <LaunchedFromPushModel>(() => App.PushModel ?? new LaunchedFromPushModel(), Lifestyle.Singleton);

                // Finish registering created caches
                Container.Register <ICache <PropertyModel> >(() => propertyCache, Lifestyle.Singleton);
                Container.Register <ICache <Models.Order> >(() => orderCache, Lifestyle.Singleton);
                Container.Register <ICache <ImageModel> >(() => imageCache, Lifestyle.Singleton);
                Container.Register <ICache <SubscriptionModel> >(() => subCache, Lifestyle.Singleton);
                Container.Register <ICache <SettingsModel> >(() => settingsCache, Lifestyle.Singleton);
                Container.Register <ICache <PurchasedReportModel> >(() => prCache, Lifestyle.Singleton);
                Container.RegisterConditional(typeof(ICache <>), typeof(MemoryCache <>), c => !c.Handled);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                throw;
            }
        }
Exemplo n.º 51
0
        private void BtnLogin_Clicked(object sender, EventArgs e)
        {
            checkConnectivity();

            var authenticator = new OAuth2Authenticator
                                (
                "623999391750-8cep3ajgrnh26gdnmlbjq3376im2gcui.apps.googleusercontent.com",
                "email profile",
                new System.Uri("https://accounts.google.com/o/oauth2/auth"),
                new System.Uri("https://localhost:44312/signin-google")
                                );

            authenticator.AllowCancel = true;

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

            presenter.Login(authenticator);

            authenticator.Completed += async(senders, obj) =>
            {
                if (obj.IsAuthenticated)
                {
                    Debug.WriteLine("Dit doet iets");
                    var clientData = new HttpClient();

                    //call google api to fetch logged in user profile info
                    token = obj.Account.Properties["access_token"];
                    var resData = await clientData.GetAsync("https://www.googleapis.com/oauth2/v3/userinfo?access_token=" + obj.Account.Properties["access_token"]);

                    var jsonData = await resData.Content.ReadAsStringAsync();

                    //deserlize the jsondata and intilize in GoogleAuthClass
                    GoogleLogin googleObject = JsonConvert.DeserializeObject <GoogleLogin>(jsonData);

                    //you can access following property after login
                    string email = googleObject.email;
                    string name  = googleObject.name;

                    GebruikerV2 gebruikerInfo = await LoginRepository.CheckLogin(googleObject);

                    if (gebruikerInfo != null)
                    {
                        Navigation.PushAsync(new RondeOverzichtPage(gebruikerInfo));
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                        Debug.WriteLine($"Email:{gebruikerInfo.Email}, Gebruikersnaam: {gebruikerInfo.name}, GebruikersId: {gebruikerInfo.GebruikerId}");
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                    }
                    else
                    {
                        Navigation.PopAsync();
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                        Debug.WriteLine("Failed for some reason");
                        Debug.WriteLine("-----------------------------------------------------------------------------------------");
                    }
                }
                else
                {
                    //Authentication fail
                    //write the code to handle when auth failed
                    //De gebruiker wordt al terug naar de login pagina gestuurd als het inloggen mislukt is
                }
            };
            authenticator.Error += onAuthError;
        }
Exemplo n.º 52
0
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (done)
            {
                return;
            }

            var auth = new OAuth2Authenticator(
                clientId: "168703917051703",
                scope: "",
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

            auth.Completed += async(sender, eventArgs) => {
                if (eventArgs.IsAuthenticated)
                {
                    var accessToken = eventArgs.Account.Properties["access_token"].ToString();
                    var expiresIn   = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
                    var expiryDate  = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
                    var request     = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,cover,age_range,picture"), null, eventArgs.Account);
                    var response    = await request.GetResponseAsync();

                    var obj  = JObject.Parse(response.GetResponseText());
                    var objs = JsonConvert.DeserializeObject <FacebookProfile>(response.GetResponseText());

                    Usuarios usuario   = new Usuarios(objs);
                    Usuario  usuariobd = new Usuario(objs);

                    ObtenerResul obtenerResul = new ObtenerResul();
                    string       nombreuser   = usuario.Name;
                    var          contador     = await obtenerResul.GetList <ClasesBd>("http://tools.agorafranquicias.com/APP/Consultas/getUsuarios.php?Name='" + nombreuser + "'");

                    int total;
                    foreach (Total t in contador.Total)
                    {
                        total = t.Contador;
                    }

                    /*   if (total == 0)
                     * {
                     *     obtenerResul.SaveUser(usuariobd, token);
                     * }
                     * else
                     * {
                     *     obtenerResul.UpdateUser(usuariobd, token);
                     * }*/
                    obtenerResul.SaveUser(usuariobd, null);

                    using (var datos = new DataAccess())
                    {
                        datos.InserUsuario(usuario);
                    }
                    await App.NavigateToProfile(objs);
                }
                else
                {
                    await App.VueltaAtras();
                }
            };

            done = true;
            PresentViewController(auth.GetUI(), true, null);
        }
Exemplo n.º 53
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation.
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled.
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task.
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source.
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();
#if __ANDROID__ || __IOS__
#if __ANDROID__
            // Get the current Android Activity.
            Activity activity = (Activity)ArcGISRuntime.Droid.MainActivity.Instance;
#endif
#if __IOS__
            // Get the current iOS ViewController.
            UIViewController viewController = null;
            Device.BeginInvokeOnMainThread(() =>
            {
                viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            });
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in.
            OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false,
                // Allow the user to cancel the OAuth attempt.
                AllowCancel = true
            };

            // Define a handler for the OAuth2Authenticator.Completed event.
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete.
                    viewController.DismissViewController(true, null);
#endif

                    // Check if the user is authenticated.
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account.
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource.
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource.
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication.
                    authenticator.OnCancelled();
                }
                finally
                {
                    // Dismiss the OAuth login.
#if __ANDROID__
                    activity.FinishActivity(99);
#endif
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource.
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first.
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login.
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
#if __ANDROID__
                        activity.FinishActivity(99);
#endif
                    }
                }

                // Cancel authentication.
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password.
#if __ANDROID__
            Android.Content.Intent intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password.
            Device.BeginInvokeOnMainThread(() =>
            {
                viewController.PresentViewController(authenticator.GetUI(), true, null);
            });
#endif
#endif // (If Android or iOS)
            // Return completion source task so the caller can await completion.
            return(_taskCompletionSource.Task);
        }
Exemplo n.º 54
0
        private void FacebookButton_TouchUpInside(object sender, EventArgs e)
        {
            OAuth2Authenticator oauth2authenticator = LoginHelper.GetFacebook2Authenticator(this);

            PresentViewController(oauth2authenticator.GetUI(), true, null);
        }
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization is in progress
            if (_taskCompletionSource != null)
            {
                // Allow only one authorization process at a time
                throw new Exception();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator authenticator = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri);

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Check if the user is authenticated
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.SetException(ex);
                }
                finally
                {
                    // End the OAuth login activity
                    this.FinishActivity(99);
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.SetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: end the OAuth login activity
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
                        this.FinishActivity(99);
                    }
                }
            };

            // Present the OAuth UI (Activity) so the user can enter user name and password
            var intent = authenticator.GetUI(this);

            this.StartActivityForResult(intent, 99);

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
Exemplo n.º 56
0
        void LoginToFacebook(bool allowCancel)
        {
            var    loginPage    = Element as FBLoginPage;
            string providername = loginPage.ProviderName;
            var    activity     = this.Context as Activity;


            OAuth2Authenticator auth = null;

            switch (providername)
            {
            case "Google":
            {
                auth = new OAuth2Authenticator(
                    // For Google login, for configure refer https://code.msdn.microsoft.com/Register-Identity-Provider-41955544
                    App.ClientId,
                    App.ClientSecret,
                    // Below values do not need changing
                    "https://www.googleapis.com/auth/userinfo.email",
                    new Uri(App.url2),
                    new Uri(App.url3),                // Set this property to the location the user will be redirected too after successfully authenticating
                    new Uri(App.url4)
                    //,isUsingNativeUI: true
                    );

                break;
            }

            case "FaceBook":
            {
                auth = new OAuth2Authenticator(
                    clientId: App.AppId,
                    scope: App.ExtendedPermissions,
                    authorizeUrl: new Uri(App.AuthorizeUrl),
                    redirectUrl: new Uri(App.RedirectUrl));
                break;
            }
            }

            auth.AllowCancel = allowCancel;

            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += async(s, eargs) =>
            {
                if (!eargs.IsAuthenticated)
                {
                    return;
                }
                else
                {
                    //var token = eargs.Account.Properties["access_token"];

                    if (providername.Equals("FaceBook"))
                    {
                        // Now that we're logged in, make a OAuth2 request to get the user's info.
                        var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=id,name,picture,email"), null, eargs.Account);
                        var result  = await request.GetResponseAsync();

                        string resultText = result.GetResponseText();
                        var    obj        = JsonValue.Parse(resultText);
                        // Console.WriteLine(token + " -=- " + resultText);

                        App.FacebookId   = obj["id"];
                        App.FacebookName = obj["name"];
                        App.EmailAddress = obj["email"];
                        App.ProfilePic   = obj["picture"]["data"]["url"];
                        //
                        saveset(obj["id"], obj["name"]);
                    }
                    else
                    {
                        string url1     = "https://www.googleapis.com/oauth2/v2/userinfo";
                        var    request  = new OAuth2Request("GET", new Uri(url1), null, eargs.Account);
                        var    response = await request.GetResponseAsync();

                        if (response != null)
                        {
                            HttpClient client1 = new HttpClient();
                            client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                            client1.MaxResponseContentBufferSize = 256000;

                            //var data = client.SendAsync(request).Result;
                            string url  = response.ResponseUri.ToString();
                            var    data = client1.GetStringAsync(url).Result;

                            //var obj = JsonValue.Parse(data);
                            var obj = JsonConvert.DeserializeObject <UserM>(data);

                            App.FacebookId   = obj.Id;
                            App.FacebookName = obj.Name;
                            App.EmailAddress = obj.Email;
                            App.ProfilePic   = obj.Picture;
                            //
                            saveset(obj.Id, obj.Name);
                        }
                    }

                    // On Android: store the account
                    AccountStore.Create(Context).Save(eargs.Account, "Facebook");
                    //Save as a new user to the database
                    await App.UserManager.SaveTaskAsync
                        (new Models.User
                    {
                        FBID     = App.FacebookId,
                        UserName = App.FacebookName,
                        Email    = App.EmailAddress,
                        ImgLink  = App.ProfilePic
                    },
                        true);

                    /* GPSLocation gpsloc = new GPSLocation();
                     * var position = await gpsloc.getLocationAsync();
                     * App.UserManager.saveUserLocation(new Models.Location
                     * {
                     *   FBID = App.FacebookId,
                     *   UserName = App.FacebookName,
                     *   Latitude = position.Latitude.ToString(),
                     *   Longitude = position.Longitude.ToString(),
                     *   Distance = null
                     * });
                     */
                    //retreive gcm id
                    var    prefs = Android.App.Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
                    string id    = prefs.GetString("regId", null);

                    RegisterAsync(id, new string[] { App.FacebookId + "T" }, App.FacebookId);

                    await App.Current.MainPage.Navigation.PopModalAsync();

                    App.IsLoggedIn = true;
                    ((App)App.Current).SaveProfile();
                    ((App)App.Current).PresentMainPage();
                }
            };


            Intent intent = (Intent)auth.GetUI(activity);

            activity.StartActivity(intent);
        }
Exemplo n.º 57
0
        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be cancelled
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication process
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >();

            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator auth = new OAuth2Authenticator(
                clientId: AppClientId,
                scope: "",
                authorizeUrl: new Uri(AuthorizeUrl),
                redirectUrl: new Uri(OAuthRedirectUrl))
            {
                ShowErrors = false
            };

            // Allow the user to cancel the OAuth attempt
            auth.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            auth.Completed += (sender, authArgs) =>
            {
                try
                {
                    // Dismiss the OAuth UI when complete
                    this.DismissViewController(true, null);

                    // Throw an exception if the user could not be authenticated
                    if (!authArgs.IsAuthenticated)
                    {
                        throw(new Exception("Unable to authenticate user."));
                    }

                    // If authorization was successful, get the user's account
                    Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                    // Set the result (Credential) for the TaskCompletionSource
                    _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication
                    auth.OnCancelled();
                }
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            auth.Error += (sndr, errArgs) =>
            {
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    _taskCompletionSource.TrySetException(new Exception(errArgs.Message));
                }

                // Cancel authentication
                auth.OnCancelled();
            };

            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            InvokeOnMainThread(() =>
            {
                this.PresentViewController(auth.GetUI(), true, null);
            });

            // Return completion source task so the caller can await completion
            return(_taskCompletionSource.Task);
        }
        void LoginToFacebook(bool allowCancel)
        {
            var auth = new OAuth2Authenticator(
                         //Below is Facebook App id which we created on fb developer
                         clientId: Constants.ID,
                         scope: "", //By Default it is public..
                         authorizeUrl: new Uri(Constants.authorize),
                         redirectUrl: new Uri(Constants.reDirect));
            //We should give redirectUrl in redirect URl option in products in facebook-developers options
                        
            // If authorization succeeds or is canceled, .Completed will be fired.
            auth.Completed += (s, ee) => {
                var progressDialog = ProgressDialog.Show(this, Constants.wait, Constants.info, true);

                if (!ee.IsAuthenticated)
                {
                    var builder = new AlertDialog.Builder(this);
                    builder.SetMessage("Not Authenticated");
                    builder.SetPositiveButton("Ok", (o, e) => { });
                    builder.Create().Show();
                    progressDialog.Hide();
                    return;
                }

                // Now that we're logged in, make a OAuth2 request to get the user's info.
                var request = new OAuth2Request("GET", new Uri(Constants.Url), null, ee.Account);
                request.GetResponseAsync().ContinueWith(t => {
                    var builder = new AlertDialog.Builder(this);
                    progressDialog.Hide();
                    if (t.IsFaulted)
                    {
                        builder.SetTitle("Error");
                        builder.SetMessage(t.Exception.Flatten().InnerException.ToString());
                        builder.SetPositiveButton("Ok", (o, e) => { });
                        builder.Create().Show();
                    }
                    else if (t.IsCanceled)
                    {
                        builder.SetTitle("Task Canceled");
                        builder.SetPositiveButton("Ok", (o, e) => { });
                        builder.Create().Show();
                    }   
                    else
                    {
                        var obj = JsonValue.Parse(t.Result.GetResponseText());
                        
                        //Instead of passing data through activity we are just assigning to another class 
                        DataClass.userData = obj;

                        //Passing username to next Activity..
                        //activity2.PutExtra("MyData", "User Details: " +  obj);
                        StartActivity(activity2);
                    }

                }, UIScheduler);
            };

            //Getting facebook login Ui
            var intent = auth.GetUI(this);
            StartActivity(intent);
        }
Exemplo n.º 59
-1
		void LoginToVk ()
		{
			var auth = new OAuth2Authenticator (
				clientId: "5171316",  // id  нашого додатку 
				scope: "wall,photos,notes,pages", // запит прав нашого додатку 
				authorizeUrl: new System.Uri ("https://oauth.vk.com/authorize"),
				redirectUrl: new System.Uri ("https://oauth.vk.com/blank.html"));

			auth.AllowCancel = true;
			auth.Completed += (s, ee) => { //провірка чи аудентифіколваний
				if (!ee.IsAuthenticated) {
					var builder = new AlertDialog.Builder (this);
					builder.SetMessage ("Not Authenticated");
					builder.SetPositiveButton ("Ok", (o, e) => { });
					builder.Create().Show();
					return;
				}
				else
				{
					token = ee.Account.Properties ["access_token"].ToString ();
					userId = ee.Account.Properties ["user_id"].ToString ();	
					GetInfo();
				}
			};
			var intent = auth.GetUI (this);
			StartActivity (intent);
		}
        public DirectoryService DirectoryService()
        {
            var provider = InitializeProvider();
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            return new DirectoryService(new BaseClientService.Initializer { Authenticator = auth });
        }