public PincodeOptions(PincodeScreen screen, Account user, string passcode)
 {
     Screen = screen;
     User = user;
     Passcode = passcode;
     Policy = User.Policy;
 }
        public static DBOpenHelper GetOpenHelper(string dbNamePrefix, Account account, string communityId)
        {
            var dbName = new StringBuilder(dbNamePrefix);

		    // If we have account information, we will use it to create a database suffix for the user.
		    if (account != null)
            {

			    // Default user path for a user is 'internal', if community ID is null.
		        if (String.IsNullOrWhiteSpace(communityId))
		        {
                    dbName.Append(communityId);
		        }
		    }
		    dbName.Append(DBNameSuffix);
		    DBOpenHelper helper = null;
            if (_openHelpers == null)
            {
                _openHelpers = new Dictionary<string, DBOpenHelper>();
                helper = new DBOpenHelper(dbName.ToString());
                _openHelpers.Add(dbName.ToString(), helper);
            }
            else
            {
                if (!_openHelpers.TryGetValue(dbName.ToString(), out helper))
                {
                    helper = new DBOpenHelper(dbName.ToString());
                }
            }
            return helper;
        }
 /// <summary>
 ///     Returns the instance of this class associated with this user and community.
 /// </summary>
 /// <param name="account"></param>
 /// <param name="communityId"></param>
 /// <returns></returns>
 public static MetadataManager GetInstance(Account account, string communityId = null)
 {
     if (account == null)
     {
         account = AccountManager.GetAccount();
     }
     if (account == null)
     {
         return null;
     }
     string uniqueId = Constants.GenerateAccountCommunityId(account, communityId);
     lock (Synclock)
     {
         MetadataManager instance = null;
         if (_instances != null)
         {
             if (_instances.TryGetValue(uniqueId, out instance))
             {
                 return instance;
             }
             instance = new MetadataManager(account, communityId);
             _instances.Add(uniqueId, instance);
         }
         else
         {
             _instances = new Dictionary<string, MetadataManager>();
             instance = new MetadataManager(account, communityId);
             _instances.Add(uniqueId, instance);
         }
         return instance;
     }
 }
 /// <summary>
 /// Persist account
 /// </summary>
 /// <param name="account"></param>
 public void PersistCredentials(Account account)
 {
     // TODO use PasswordVault
     ApplicationDataContainer settings = ApplicationData.Current.RoamingSettings;
     string accountJson = Account.ToJson(account);
     settings.Values[ACCOUNT_SETTING] = accountJson;
 }
 public static DBOpenHelper GetOpenHelper(Account account)
 {
     lock (Dbopenlock)
     {
         return GetOpenHelper(account, null);
     }
 }
 public static async Task<bool> SwitchToAccount(Account account)
 {
     if (account != null && account.UserId != null)
     {
         AuthStorageHelper.SavePinTimer();
         AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
         RestClient client = SDKManager.GlobalClientManager.PeekRestClient();
         if (client != null)
         {
             OAuth2.ClearCookies(account.GetLoginOptions());
             IdentityResponse identity = await OAuth2.CallIdentityService(account.IdentityUrl, client);
             if (identity != null)
             {
                 account.UserId = identity.UserId;
                 account.UserName = identity.UserName;
                 account.Policy = identity.MobilePolicy;
                 AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
             }
             OAuth2.RefreshCookies();
             PlatformAdapter.SendToCustomLogger("AccountManager.SwitchToAccount - done, result = true", LoggingLevel.Verbose);
             return true;
         }
     }
     PlatformAdapter.SendToCustomLogger("AccountManager.SwitchToAccount - done, result = false", LoggingLevel.Verbose);
     return false;
 }
 public static bool SwitchToAccount(Account account)
 {
     if (account != null && account.UserId != null)
     {
         AuthStorage.PersistCredentials(account);
     }
     return false;
 }
 public void TestPersistRetrieveDeleteCredentials()
 {
     Account account = new Account("loginUrl", "clientId", "callbackUrl", new string[] { "scopeA", "scopeB" }, "instanceUrl", "accessToken", "refreshToken");
     IAuthStorageHelper authStorageHelper = PlatformAdapter.Resolve<IAuthStorageHelper>();
     CheckAccount(null);
     authStorageHelper.PersistCredentials(account);
     CheckAccount(account);
     authStorageHelper.DeletePersistedCredentials();
     CheckAccount(null);
 }
 /// <summary>
 /// Persist account
 /// </summary>
 /// <param name="account"></param>
 public void PersistCredentials(Account account)
 {
     // TODO store encrypted credentials
     IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
     string accountJson = Account.ToJson(account);
     if (settings.Contains(ACCOUNT_SETTING))
     {
         settings[ACCOUNT_SETTING] = accountJson;
     }
     else
     {
         settings.Add(ACCOUNT_SETTING, accountJson);
     }
     settings.Save();
 }
 public void TestPersistRetrieveDeleteCredentials()
 {
     Account account = new Account("loginUrl", "clientId", "callbackUrl", new string[] { "scopeA", "scopeB" }, "instanceUrl", "identityUrl", "accessToken", "refreshToken");
     account.UserId = "userId";
     account.UserName = "******";
     AuthStorageHelper authStorageHelper = new AuthStorageHelper();
     CheckAccount(account, false);
     TypeInfo auth = authStorageHelper.GetType().GetTypeInfo();
     MethodInfo persist = auth.GetDeclaredMethod("PersistCredentials");
     MethodInfo delete = auth.GetDeclaredMethods("DeletePersistedCredentials").First(method => method.GetParameters().Count() == 1);
     persist.Invoke(authStorageHelper, new object[] { account });
     CheckAccount(account, true);
     delete.Invoke(authStorageHelper, new object[] { account.UserId });
     CheckAccount(account, false);
 }
 /// <summary>
 ///     Resets the Sync manager associated with this user and community.
 /// </summary>
 /// <param name="account"></param>
 /// <param name="communityId"></param>
 public static void Reset(Account account, string communityId = null)
 {
     if (account == null)
     {
         account = AccountManager.GetAccount();
     }
     if (account != null)
     {
         lock (Synclock)
         {
             MetadataManager instance = GetInstance(account, communityId);
             if (instance == null) return;
             _instances.Remove(Constants.GenerateAccountCommunityId(account, communityId));
         }
     }
 }
 /// <summary>
 /// Persist account, and sets account as the current account.
 /// </summary>
 /// <param name="account"></param>
 internal void PersistCredentials(Account account)
 {
     // TODO use PasswordVault
     ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
     Dictionary<string, Account> accounts = RetrievePersistedCredentials();
     if (accounts.ContainsKey(account.UserId))
     {
         accounts[account.UserId] = account;
     } else
     {
         accounts.Add(account.UserId, account);
     }
     String accountJson = JsonConvert.SerializeObject(accounts);
     settings.Values[ACCOUNT_SETTING] = Encryptor.Encrypt(accountJson);
     settings.Values[CURRENT_ACCOUNT] = Encryptor.Encrypt(account.UserId);
     LoginOptions options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl, account.Scopes);
     SalesforceConfig.LoginOptions = options;
 }
 private void CheckAccount(Account expectedAccount)
 {
     IAuthStorageHelper authStorageHelper = PlatformAdapter.Resolve<IAuthStorageHelper>();
     Account account = authStorageHelper.RetrievePersistedCredentials();
     if (expectedAccount == null)
     {
         Assert.IsNull(account, "No account should have been found");
     }
     else
     {
         Assert.AreEqual(expectedAccount.LoginUrl, account.LoginUrl);
         Assert.AreEqual(expectedAccount.ClientId, account.ClientId);
         Assert.AreEqual(expectedAccount.CallbackUrl, account.CallbackUrl);
         Assert.AreEqual(expectedAccount.Scopes.Length, account.Scopes.Length);
         Assert.AreEqual(expectedAccount.InstanceUrl, account.InstanceUrl);
         Assert.AreEqual(expectedAccount.AccessToken, expectedAccount.AccessToken);
         Assert.AreEqual(expectedAccount.RefreshToken, expectedAccount.RefreshToken);
     }
 }
        public static DBOpenHelper GetOpenHelper(Account account, string communityId)
        {
            string dbName = String.Format(DBName, "");

            if (account == null) return _defaultHelper ?? (_defaultHelper = new DBOpenHelper(dbName));
            var uniqueId = account.UserId;
            DBOpenHelper helper = null;
            if (_openHelpers == null)
            {
                _openHelpers = new Dictionary<string, DBOpenHelper>();
                helper = new DBOpenHelper(String.Format(DBName, uniqueId));
                _openHelpers.Add(uniqueId, helper);
            }
            else
            {
                if (!_openHelpers.TryGetValue(uniqueId, out helper))
                {
                    helper = new DBOpenHelper(dbName);
                }
            }
            return helper;
        }
 private void CheckAccount(Account expectedAccount, bool exists)
 {
     AuthStorageHelper authStorageHelper = new AuthStorageHelper();
     TypeInfo auth = authStorageHelper.GetType().GetTypeInfo();
     MethodInfo retrieve = auth.GetDeclaredMethod("RetrievePersistedCredentials");
     var accounts = (Dictionary<string, Account>) retrieve.Invoke(authStorageHelper, null);
     if (!exists)
     {
         Assert.IsFalse(accounts.ContainsKey(expectedAccount.UserId), "Account " + expectedAccount.UserId + " should not have been found");
     }
     else
     {
         Assert.IsTrue(accounts.ContainsKey(expectedAccount.UserId),  "Account " + expectedAccount.UserId + " should exist");
         Account account = accounts[expectedAccount.UserId];
         Assert.AreEqual(expectedAccount.LoginUrl, account.LoginUrl);
         Assert.AreEqual(expectedAccount.ClientId, account.ClientId);
         Assert.AreEqual(expectedAccount.CallbackUrl, account.CallbackUrl);
         Assert.AreEqual(expectedAccount.Scopes.Length, account.Scopes.Length);
         Assert.AreEqual(expectedAccount.InstanceUrl, account.InstanceUrl);
         Assert.AreEqual(expectedAccount.AccessToken, expectedAccount.AccessToken);
         Assert.AreEqual(expectedAccount.RefreshToken, expectedAccount.RefreshToken);
     }
 }
 private MetadataManager(Account account, string communityId)
 {
     _apiVersion = ApiVersionStrings.VersionNumber;
     _communityId = communityId;
     _cacheManager = CacheManager.GetInstance(account, communityId);
 }
 public Task PersistCurrentAccountAsync(Account account)
 {
     AuthStorageHelper.GetAuthStorageHelper().PersistCurrentCredentials(account);
     return Task.FromResult(0);
 }
 public static async Task<bool> HasSmartStore(Account account)
 {
     var path = DBOpenHelper.GetOpenHelper(account).DatabaseFile;
     return await AppInfoService.DoesFileExistAsync(path);
 }
 public static string GenerateDatabasePath(Account account)
 {
     DBOpenHelper open = DBOpenHelper.GetOpenHelper(account);
     var localPath = AppInfoService.GetApplicationLocalFolderPath();
     return Path.Combine(localPath, open.DatabaseFile);
 }
 private SmartStore(Account account)
 {
     _databasePath = GenerateDatabasePath(account);
     CreateMetaTables();
 }
        /// <summary>
        /// Persist account, and sets account as the current account.
        /// </summary>
        /// <param name="account"></param>
        internal void PersistCurrentCredentials(Account account)
        {
            var userCredentials = SafeRetrieveUser(PasswordVaultAccounts, account.UserName);

            if (userCredentials != null)
            {
                LoggingService.Log("removing existing credential", LoggingLevel.Verbose);
                _vault.Remove(userCredentials);

                // clear the current account from the password vault
                try
                {
                    var current = _vault.FindAllByResource(PasswordVaultCurrentAccount);
                    if (current != null)
                    {
                        foreach (var user in current)
                        {
                            _vault.Remove(user);
                        }
                    }
                }
                catch (Exception)
                {
                    LoggingService.Log("did not find existing logged in user while persisting", LoggingLevel.Verbose);
                }
            }

            var serialized = EncryptionService.Encrypt(JsonConvert.SerializeObject(account));
            if (account.UserName != null)
            {
                _vault.Add(new PasswordCredential(PasswordVaultAccounts, account.UserName, serialized));
                _vault.Add(new PasswordCredential(PasswordVaultCurrentAccount, account.UserName, serialized));
            }
            var options = new LoginOptions(account.LoginUrl, account.ClientId, account.CallbackUrl,
                LoginOptions.DefaultDisplayType, account.Scopes);
            SalesforceConfig.LoginOptions = options;
            LoggingService.Log("done adding info to vault", LoggingLevel.Verbose);
        }
 /// <summary>
 /// Serialize Account object as a JSON string
 /// </summary>
 /// <param name="account"></param>
 /// <returns></returns>
 public static string ToJson(Account account)
 {
     return JsonConvert.SerializeObject(account);
 }
        /// <summary>
        ///     Create and persist Account for newly authenticated user
        /// </summary>
        /// <param name="loginOptions"></param>
        /// <param name="authResponse"></param>
        public static async Task<Account> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse)
        {
            LoggingService.Log("Create account object", LoggingLevel.Verbose);

            var account = new Account(
                loginOptions.LoginUrl, 
                loginOptions.ClientId, 
                loginOptions.CallbackUrl,
                loginOptions.Scopes,
                authResponse.InstanceUrl, 
                authResponse.IdentityUrl, 
                authResponse.AccessToken, 
                authResponse.RefreshToken)
            {
                CommunityId = authResponse.CommunityId,
                CommunityUrl = authResponse.CommunityUrl
            };

            var cm = new ClientManager();
            cm.PeekRestClient();
            IdentityResponse identity = null;
            try
            {
                identity = await OAuth2.CallIdentityServiceAsync(authResponse.IdentityUrl, authResponse.AccessToken);
            }
            catch (JsonException ex)
            {
                LoggingService.Log("Exception occurred when retrieving account identity:",
                    LoggingLevel.Critical);
                LoggingService.Log(ex, LoggingLevel.Critical);
                Debug.WriteLine("Error retrieving account identity");
            }

            if (identity != null)
            {
                account.UserId = identity.UserId;
                account.UserName = identity.UserName;
                account.Policy = identity.MobilePolicy;
                account.OrganizationId = identity.OrganizationId;

                await AuthStorageHelper.PersistCurrentAccountAsync(account);

                LoggedInAccount = account;
            }
            LoggingService.Log("Finished creating account", LoggingLevel.Verbose);
            return account;
        }
 /// <summary>
 ///     Create and persist Account for newly authenticated user
 /// </summary>
 /// <param name="loginOptions"></param>
 /// <param name="authResponse"></param>
 public static async Task<Account> CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse)
 {
     PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - create account object", LoggingLevel.Verbose);
     var account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl,
         loginOptions.Scopes,
         authResponse.InstanceUrl, authResponse.IdentityUrl, authResponse.AccessToken, authResponse.RefreshToken);
     account.CommunityId = authResponse.CommunityId;
     account.CommunityUrl = authResponse.CommunityUrl;
     var cm = new ClientManager();
     cm.PeekRestClient();
     IdentityResponse identity = null;
     try
     {
         identity = await OAuth2.CallIdentityService(authResponse.IdentityUrl, authResponse.AccessToken);
     }
     catch (JsonException ex)
     {
         PlatformAdapter.SendToCustomLogger(
             "AccountManager.CreateNewAccount - Exception occurred when retrieving account identity:",
             LoggingLevel.Critical);
         PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);
         Debug.WriteLine("Error retrieving account identity");
     }
     if (identity != null)
     {
         account.UserId = identity.UserId;
         account.UserName = identity.UserName;
         account.Policy = identity.MobilePolicy;
         AuthStorageHelper.GetAuthStorageHelper().PersistCredentials(account);
     }
     PlatformAdapter.SendToCustomLogger("AccountManager.CreateNewAccount - done", LoggingLevel.Verbose);
     return account;
 }
 /// <summary>
 /// Raises the account changed event. This method exists because AuthStorageHelper truly knows when
 /// an account changes but the event belongs in the AccountManager class, so this method is necessary
 /// to enable AuthStorageHelper to raise that event.
 /// </summary>
 private static void RaiseAuthenticatedAccountChangedEvent(Account oldAccount, Account newAccount)
 {
     AuthenticatedAccountChanged?.Invoke(new AuthenticatedAccountChangedEventArgs(oldAccount, newAccount));
 }
 public static SmartStore GetSmartStore(Account account)
 {
     var store = new SmartStore(account);
     return store;
 }
 /// <summary>
 /// Create and persist Account for newly authenticated user
 /// </summary>
 /// <param name="loginOptions"></param>
 /// <param name="authResponse"></param>
 public static void CreateNewAccount(LoginOptions loginOptions, AuthResponse authResponse)
 {
     Account account = new Account(loginOptions.LoginUrl, loginOptions.ClientId, loginOptions.CallbackUrl, loginOptions.Scopes,
         authResponse.InstanceUrl, authResponse.AccessToken, authResponse.RefreshToken);
     PlatformAdapter.Resolve<IAuthStorageHelper>().PersistCredentials(account);
 }
        /// <summary>
        /// Delete Account (log out) for currently authenticated user
        /// </summary>
        public static void DeleteAccount()
        {
            var account = GetAccount();

            if (account == null)
            {
                return;
            }

            AuthStorageHelper.DeletePersistedAccount(account.UserName, account.UserId);

            LoggedInAccount = null;
        }
        /// <summary>
        ///     Async method for refreshing the token, persisting the data in the encrypted settings and returning the updated
        ///     account
        ///     with the new access token.
        /// </summary>
        /// <param name="account"></param>
        /// <returns>Boolean based on if the refresh auth token succeeded or not</returns>
        public static async Task<Account> RefreshAuthTokenAsync(Account account)
        {
            LoggingService.Log("Atempting to refresh auth token", LoggingLevel.Verbose);

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

            try
            {
                var loginOptions = account.GetLoginOptions();

                // args
                var argsStr = string.Format(OauthRefreshQueryString, loginOptions.ClientId, account.RefreshToken);

                // Refresh url
                var refreshUrl = loginOptions.LoginUrl + OauthRefreshPath;

                // Post
                var call = HttpCall.CreatePost(refreshUrl, argsStr);

                var response = await call.ExecuteAndDeserializeAsync<AuthResponse>();

                account.AccessToken = response.AccessToken;
                account.IdentityUrl = response.IdentityUrl;

                await SDKServiceLocator.Get<IAuthHelper>().PersistCurrentAccountAsync(account);
            }
            catch (DeviceOfflineException ex)
            {
                LoggingService.Log("Failed to refresh the token because we were offline", LoggingLevel.Warning);
                LoggingService.Log(ex, LoggingLevel.Warning);
                throw;
            }
            catch (WebException ex)
            {
                LoggingService.Log("Exception occurred when refreshing token:", LoggingLevel.Critical);
                LoggingService.Log(ex, LoggingLevel.Critical);
                Debug.WriteLine("Error refreshing token");
                throw new OAuthException(ex.Message, ex);
            }
            catch (Exception ex)
            {
                LoggingService.Log("Exception occurred when refreshing token:", LoggingLevel.Critical);
                LoggingService.Log(ex, LoggingLevel.Critical);
                Debug.WriteLine("Error refreshing token");
                throw new OAuthException(ex.Message, ex);
            }

            return account;
        }
 public JSONCredentials(Account account, RestClient client)
 {
     AccessToken = client.AccessToken;
     LoginUrl = account.LoginUrl;
     InstanceUrl = account.InstanceUrl;
     ClientId = account.ClientId;
     RefreshToken = account.RefreshToken;
     UserAgent = "SalesforceMobileSDK/2.0 windows phone"; // FIXME
     // TODO wire through the other fields
 }