public AccountAuthorizationResponse AuthorizeAccount(ApplicationCredentials credentials) { CurrentToken = GetCachedAuthorization(); if (CurrentToken != null && CurrentToken.AccountID == credentials.AccountId) { return CurrentToken; } string authString = "{0}:{1}".Fmt(credentials.AccountId, credentials.ApplicationKey); byte[] authBytes = Encoding.UTF8.GetBytes(authString); client.AddHeader("Authorization", "Basic {0}".Fmt(System.Convert.ToBase64String(authBytes))); var response = client.Get<AccountAuthorizationResponse>("b2_authorize_account"); CurrentToken = response; SaveAuthorizationToken(response); return CurrentToken; }
private void SaveAuthorizationToken(AccountAuthorizationResponse authResponse, string filename = "auth.json") { File.WriteAllText(filename, authResponse.ToJson()); }
private AccountAuthorizationResponse GetCachedAuthorization(string filename = "auth.json") { if (!File.Exists("auth.json")) { return null; } //todo: make the timeout configurable if (DateTime.Now - File.GetLastWriteTime("auth.json") > TimeSpan.FromHours(6)) { return null; } CurrentToken = JsonSerializer.DeserializeFromStream<AccountAuthorizationResponse>(new FileStream("auth.json", FileMode.Open)); return CurrentToken; }