Exemplo n.º 1
0
        public bool CreateAndSaveAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            byte[] salt           = CryptoUtilities.Get256BitSalt();
            byte[] hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(password), salt);

            AccountStore store = AccountStore.Create();

            if (GetAccountFromStore(store, username) != null)
            {
                return(false);
            }

            Account account = new Account(username);

            account.Properties.Add(key_password, Convert.ToBase64String(hashedPassword));
            account.Properties.Add(key_salt, Convert.ToBase64String(salt));
            account.Properties.Add(key_keymaterial, Convert.ToBase64String(
                                       CryptoUtilities.GetAES256KeyMaterial()));

            store.Save(account, service_id);

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 判斷這個使用者是否已經通過了身分驗證
        /// </summary>
        /// <returns></returns>
        public static async Task <Account> IsAlreadyAuthenticated()
        {
            // 取得 Prism 相依性服務使用到的容器
            IUnityContainer fooContainer = (XFoAuth2.App.Current as PrismApplication).Container;
            // 取得 IAccountStore 介面實際實作的類別物件
            IAccountStore fooIAccountStore = fooContainer.Resolve <IAccountStore>();

            #region 若可以取得使用者認證的使用者資訊,表示,這個使用者已經通過認證了
            if (fooIAccountStore.GetPlatform() == "UWP")
            {
                return(await fooIAccountStore.GetAccount());
            }
            else
            {
                // Retrieve any stored account information
                var accounts = await AccountStore.Create().FindAccountsForServiceAsync(AppName);

                var account = accounts.FirstOrDefault();

                // If we already have the account info then we are set
                if (account == null)
                {
                    return(null);
                }
                return(account);
            }
            #endregion
        }
Exemplo n.º 3
0
        public bool LoginToAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            AccountStore store   = AccountStore.Create();
            Account      account = GetAccountFromStore(store, username);

            if (account == null)
            {
                return(false);
            }

            byte[] salt, hashedPassword;

            // Upgrade existing passwords to our new format
            if (!account.Properties.ContainsKey(key_salt))
            {
                salt           = CryptoUtilities.Get256BitSalt();
                hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(account.Properties[key_password]), salt);
                account.Properties[key_password] = Convert.ToBase64String(hashedPassword);
                account.Properties.Add(key_salt, Convert.ToBase64String(salt));
                store.Save(account, service_id);
            }

            salt           = Convert.FromBase64String(account.Properties[key_salt]);
            hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(password), salt);

            return(account.Properties[key_password] == Convert.ToBase64String(hashedPassword));
        }
        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.º 5
0
 public ProfileService()
 {
     account   = AccountStore.Create().FindAccountsForService("facebook").FirstOrDefault();
     fbService = new FacebookService {
         ClientId = AuthHelpers.ClientId
     };
 }
Exemplo n.º 6
0
        public OAuthNativeFlowPage()
        {
            InitializeComponent();

            store   = AccountStore.Create();
            account = store.FindAccountsForService(Constants.AppName).FirstOrDefault();
        }
Exemplo n.º 7
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // window = new UIWindow (UIScreen.MainScreen.Bounds);

            Forms.Init();

            FBSettings.DefaultAppID       = FacebookAppId;
            FBSettings.DefaultDisplayName = DisplayName;

            window = new UIWindow(UIScreen.MainScreen.Bounds);
            UIViewController initialController;

            // Try to open up the cached fb access token
            var accountStore      = AccountStore.Create();
            var savedBuddyAccount = accountStore.FindAccountsForService(PopPicConstants.BuddyAccountKey).LastOrDefault();

            if (savedBuddyAccount != null &&
                FBSession.OpenActiveSession(false) &&
                FBSession.ActiveSession.IsOpen)
            {
                var            buddyToken  = savedBuddyAccount.Properties [PopPicConstants.BuddyAccessTokenKey];
                BuddyClient    buddyClient = new BuddyClient(PopPicConstants.BuddyAppName, PopPicConstants.BuddyAppKey);
                FacebookClient fb          = new FacebookClient(FBSession.ActiveSession.AccessTokenData.AccessToken);
                fb.AppId     = PopPicConstants.AppId;
                fb.AppSecret = PopPicConstants.AppSecret;

                initialController = SplashScreenStoryboard.InstantiateViewController("SplashScreenViewController") as UIViewController;

                buddyClient.LoginAsync(buddyToken).ContinueWith(t => {
                    if (!t.IsFaulted)
                    {
                        var authenticatedUser  = t.Result;
                        var repository         = new GameRepository(authenticatedUser, buddyClient, fb);
                        AppDelegate.Repository = repository;

                        InvokeOnMainThread(() => {
                            var newController = Storyboard.InstantiateViewController("MyGamesTabBarController") as UIViewController;
                            newController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal;
                            initialController.PresentViewController(newController, true, null);
                        });
                    }
                    else
                    {
                        // TODO: error
                    }
                });
            }
            else
            {
                initialController = Storyboard.InstantiateViewController("MyGamesTabBarController") as UIViewController;
                // initialController = GameplayStoryboard.InstantiateViewController("GameplayViewController") as GameplayViewController;
            }


            window.RootViewController = initialController;
            window.MakeKeyAndVisible();

            return(true);
        }
Exemplo n.º 8
0
        public CreateAuthPage(Account OldAccount)
        {
            string first  = "";
            string second = "";

            PinViewModel = new PinViewModel
            {
                TargetPinLength = 6,
                ValidatorFunc   = (arg) =>
                {
                    second = "";
                    foreach (char c in arg)
                    {
                        second += c;
                    }

                    if (second.Equals(first))
                    {
                        Account acc = new Account(first);
                        acc.Properties.Add("FingerPrint", OldAccount.Properties["FingerPrint"]);
                        if (OldAccount.Properties.ContainsKey("PrivateKey"))
                        {
                            acc.Properties.Add("PrivateKey", OldAccount.Properties["PrivateKey"]);
                        }
                        AccountStore.Create().Delete(OldAccount, App.AppName);
                        AccountStore.Create().Save(acc, App.AppName);
                        App.Current.Properties["Pin"] = acc;
                        Navigation.PopToRootAsync();
                        return(true);
                    }
                    else
                    {
                        if (first.Equals(""))
                        {
                            first    += second;
                            PIN.Title = "Confirm your pin";
                        }
                        else
                        {
                            DisplayAlert("Error", "Passcode doesn't match.\nTry it again.", "OK");
                            first     = "";
                            second    = "";
                            PIN.Title = "Create your pin";
                        }
                        return(false);
                    }
                }
            };

            PIN = new PinView
            {
                Title             = "Create your pin",
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions   = LayoutOptions.CenterAndExpand,
                BindingContext    = PinViewModel,
            };

            Content = PIN;
        }
Exemplo n.º 9
0
        public override async void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);

            _account = AccountStore
                       .Create(Context)
                       .FindAccountsForService(GetString(Resource.String.app_name))
                       .FirstOrDefault();

            RestManager.SetAccessToken(_account.Properties["token"]);
            HttpResponseMessage httpResponse = await RestManager.GetMemberDetails(_account.Username);

            string response = await httpResponse.Content.ReadAsStringAsync();

            if (!string.IsNullOrWhiteSpace(response) && response != "null")
            {
                _memberDetails = JsonConvert.DeserializeObject <MemberDetails>(response);
            }
            var imagePath = await RestManager.GetMemberPhoto(_account.Username);

            TextView     firstName        = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_firstName);
            TextView     lastName         = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_lastName);
            TextView     height           = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_height);
            TextView     weight           = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_weight);
            TextView     dateOfBirth      = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_dateOfBirth);
            TextView     preferedPosition = View.FindViewById <TextView>(Resource.Id.tv_memberDetails_preferedPosition);
            LinearLayout playerSection    = View.FindViewById <LinearLayout>(Resource.Id.ll_memberDetails_playerSection);

            _mainPhoto = View.FindViewById <ImageView>(Resource.Id.iv_memberDetails_mainPhoto);
            var bitmap = BitmapFactory.DecodeFile(imagePath);

            _mainPhoto.SetImageBitmap(bitmap);

            firstName.Text = _memberDetails.FirstName;
            lastName.Text  = _memberDetails.LastName;
            if (string.Compare(_account.Properties["roles"], Role.Player.ToString(), true) == 0)
            {
                height.Text = _memberDetails.Height.HasValue ?
                              string.Format(Literals.HeightCmFormat, string.Empty, _memberDetails.Height.Value.ToString()) :
                              "0";
                weight.Text = _memberDetails.Weight.HasValue ?
                              string.Format(Literals.WeightKgFormat, string.Empty, _memberDetails.Weight.Value.ToString()) :
                              "0";
                dateOfBirth.Text = _memberDetails.DateOfBirth.HasValue ?
                                   _memberDetails.DateOfBirth.Value.ToShortDateString() :
                                   string.Empty;
                preferedPosition.Text    = Literals.ResourceManager.GetString(_memberDetails.PreferedPosition.Value.ToString());
                playerSection.Visibility = ViewStates.Visible;
            }

            Button logout = View.FindViewById <Button>(Resource.Id.btn_memberDetails_logout);

            logout.Click     += Logout_Click;
            logout.Visibility = ViewStates.Visible;

            Button editMemberDetails = View.FindViewById <Button>(Resource.Id.btn_memberDetails_edit);

            editMemberDetails.Click += EditMemberDetails_Click;
        }
Exemplo n.º 10
0
        public override async void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            _account = AccountStore
                       .Create(Context)
                       .FindAccountsForService(GetString(Resource.String.app_name))
                       .FirstOrDefault();
            _noClubEvents = View.FindViewById <TextView>(Resource.Id.tv_clubEvent_noClubEvents);

            if (_account.Properties["roles"].Contains(Role.Coach.ToString()))
            {
                FloatingActionButton goToCreateClubEventButton = View.FindViewById <FloatingActionButton>(Resource.Id.btn_clubEvent_goToCreateClubEvent);
                goToCreateClubEventButton.BringToFront();
                goToCreateClubEventButton.Click     += GoToCreateClubEventButton_Click;
                goToCreateClubEventButton.Visibility = ViewStates.Visible;
            }

            HttpResponseMessage clubHttpResponse = await RestManager.GetMemberClub(_account.Username);

            string clubResponse = await clubHttpResponse.Content.ReadAsStringAsync();

            if (clubResponse != "null")
            {
                _clubDetails            = JsonConvert.DeserializeObject <ClubDetails>(clubResponse);
                _clubEventFilterRequest = new ClubEventFilterRequest
                {
                    MemberId = int.Parse(_account.Properties["memberId"]),
                    ClubId   = _clubDetails.Id
                };

                HttpResponseMessage httpResponse = await RestManager.GetClubEvents(_clubEventFilterRequest);

                string response = await httpResponse.Content.ReadAsStringAsync();

                _clubEvents = JsonConvert.DeserializeObject <IEnumerable <ClubEventFilterResult> >(response);

                if (_clubEvents.Any())
                {
                    _timeSpans = View.FindViewById <Spinner>(Resource.Id.spn_clubEvent_timeSpan);
                    var timeSpans = Enum.GetNames(typeof(EventTimeSpan))
                                    .Select(r => Literals.ResourceManager.GetString(r)).ToArray();
                    _timeSpans.Adapter       = new ArrayAdapter <string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem, timeSpans);
                    _timeSpans.ItemSelected += TimeSpans_ItemSelected;

                    _eventsFilter            = View.FindViewById <LinearLayout>(Resource.Id.ll_clubEvent_clubEventsFilter);
                    _eventsFilter.Visibility = ViewStates.Visible;

                    _adapter      = new ClubEventAdapter(Activity, _clubEvents.ToArray(), _clubDetails, _account);
                    _recyclerView = View.FindViewById <RecyclerView>(Resource.Id.rv_clubEvent_clubEvents);
                    _recyclerView.SetAdapter(_adapter);
                    _layoutManager = new LinearLayoutManager(Activity, LinearLayoutManager.Vertical, false);
                    _recyclerView.SetLayoutManager(_layoutManager);
                }
                else
                {
                    _noClubEvents.Visibility = ViewStates.Visible;
                }
            }
        }
Exemplo n.º 11
0
        public (string username, string password) LoadCredentials(string appname)
        {
            var    account = AccountStore.Create().FindAccountsForService(appname).FirstOrDefault();
            string u       = (account != null) ? account.Username : null;
            string p       = (account != null) ? account.Properties["Password"] : null;

            return(username : u, password : p);
        }
 private static void RecuperarCuentaLocal()
 {
     //Recupera la cuenta local
     if (_cuenta == null)
     {
         _cuenta = AccountStore.Create().FindAccountsForService("InventarioProductorCiudadFutura").FirstOrDefault();
     }
 }
Exemplo n.º 13
0
        private AccountStore GetStore()
        {
#if __ANDROID__
            return(AccountStore.Create(Xamarin.Forms.Forms.Context));
#else
            return(AccountStore.Create());
#endif
        }
Exemplo n.º 14
0
		/// <summary>
		/// Deletes the credentials.
		/// </summary>
		public void DeleteCredentials()
		{
			var accounts = AccountStore.Create(Forms.Context).FindAccountsForService(App.AppName);
			foreach (var account in accounts)
			{
				AccountStore.Create(Forms.Context).Delete(account, App.AppName);
			}
		}
Exemplo n.º 15
0
 public IEnumerable <ISalesforceUser> LoadAccounts()
 {
     return(AccountStore
            .Create(CurrentPlatformContext as Context)
            .FindAccountsForService(PlatformStrings.CredentialStoreServiceName)
            .Cast <ISalesforceUser>()        // using System.Linq
            );
 }
Exemplo n.º 16
0
 public void EndSession()
 {
     AccountStore.Create().Delete(CurrentUserAccount, AppName);
     CurrentUserAccount = null;
     OnSessionStateChanged(new SessionState {
         IsAuthenticated = false
     });
 }
Exemplo n.º 17
0
        public AuthenticationService(IPlatformAuthenticator authenticator, IMobileServiceClient mobileService, IDataService dataService)
        {
            _authenticator = authenticator;
            _mobileService = mobileService;
            _dataService   = dataService;

            _accountStore = AccountStore.Create();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Does the credentials exist in Xamarin.Auth component.
        /// </summary>
        /// <returns><c>true</c>, if credentials exist , <c>false</c> otherwise.</returns>
        public bool DoCredentialsExist()
        {
            Debug.WriteLine("DoCredentialsExist called");
            var temp = AccountStore.Create().FindAccountsForService(AppConstants.AppName).Any();

            Debug.WriteLine("DoCredentialsExist: " + temp);
            return(temp);
        }
Exemplo n.º 19
0
 public Dictionary <string, string> Retrieve()
 {
     foreach (var account in AccountStore.Create(_context).FindAccountsForService(ProviderName))
     {
         return(account.Properties);
     }
     return(new Dictionary <string, string>());
 }
Exemplo n.º 20
0
        public AccountService(HttpClient client)
        {
            _accountRepository      = new AccountRepository(client);
            _accountTokenRepository = new AccountTokenRepository(client);

            AccountStore   = AccountStore.Create();
            XamarinAccount = AccountStore.FindAccountsForService(Constants.AppName).FirstOrDefault();
        }
Exemplo n.º 21
0
        private void SaveNewAppiontment(AppointmentStoreNew app)
        {
            Account account = new Account();

            account.Properties.Add("AppoitmentTime", app.AppoitmentTime);
            account.Properties.Add("AppoitmentDate", app.AppoitmentDate);
            AccountStore.Create(Forms.Context).Save(account, "NewAppiontment");
        }
    public void Store(string userId, string providerName, IDictionary <string, string> data)
    {
        Clear(providerName);
        var accountStore = AccountStore.Create(Android.App.Application.Context);
        var account      = new Account(userId, data);

        accountStore.Save(account, providerName);
    }
Exemplo n.º 23
0
        public OAuthNativeFlowPage()
        {
            InitializeComponent();

            store = AccountStore.Create();

            EasterEggInit();
        }
Exemplo n.º 24
0
        public static void Disconnect()
        {
            currentUser = null;
            var accounts = AccountStore.Create(app.ApplicationContext, Constants.appPwd).FindAccountsForService(Constants.appName).ToList();

            accounts.ForEach(account => AccountStore.Create(app.ApplicationContext, Constants.appPwd).Delete(account, Constants.appName));
            app = null;
        }
Exemplo n.º 25
0
 private static void RecuperarCuentaLocal()
 {
     //Recupera la cuenta local
     if (_cuenta == null)
     {
         _cuenta = AccountStore.Create().FindAccountsForService("AyudanteNewen").FirstOrDefault();
     }
 }
Exemplo n.º 26
0
 public LogInPageViewModel(INavigationService navigationService,
                           ILocalizationService localizationService,
                           IAuthorizationService authorizationService) : base(navigationService, localizationService)
 {
     _authorizationService = authorizationService;
     _isPassword           = true;
     store = AccountStore.Create();
 }
Exemplo n.º 27
0
        private static AccountStore GetStore()
        {
#if __ANDROID__
            return(AccountStore.Create(Android.App.Application.Context));
#else
            return(AccountStore.Create());
#endif
        }
Exemplo n.º 28
0
 static AuthenticationService()
 {
     TokenEndpoint = new Uri($"{App.Settings.Identity.Url}connect/token");
     AccountStore  = AccountStore.Create();
     AuthAccount   = AccountStore
                     .FindAccountsForService(App.Settings.ServiceId)
                     .FirstOrDefault();
 }
Exemplo n.º 29
0
        void LoginToFacebook(bool allowCancel)
        {
            var auth = new OAuth2Authenticator(
                clientId: "635793476502695",
                scope: "",
                authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
                redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));

            auth.AllowCancel = allowCancel;

            // If authorization succeeds or is canceled, .Completed will be fired.
            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;
                }

                // 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 =>
                {
                    var builder = new AlertDialog.Builder(this);
                    if (t.IsFaulted)
                    {
                        builder.SetTitle("Error");
                        builder.SetMessage(t.Exception.Flatten().InnerException.ToString());
                    }
                    else if (t.IsCanceled)
                    {
                        builder.SetTitle("Task Canceled");
                    }
                    else
                    {
                        var obj = JsonValue.Parse(t.Result.GetResponseText());

                        builder.SetTitle("Logged in");
                        builder.SetMessage("Name: " + obj["name"]);

                        //Store the account
                        AccountStore.Create(this).Save(ee.Account, "Facebook");

                        StartActivity(typeof(NewA));
                    }

                    builder.SetPositiveButton("Ok", (o, e) => { });
                    builder.Create().Show();
                }, UIScheduler);
            };

            var intent = auth.GetUI(this);

            StartActivity(intent);
        }
Exemplo n.º 30
0
        public void DeleteCredentials()
        {
            var account = AccountStore.Create(Android.App.Application.Context).FindAccountsForService(App.AppName).FirstOrDefault();

            if (account != null)
            {
                AccountStore.Create(Android.App.Application.Context).Delete(account, App.AppName);
            }
        }