bitwarden-android/src/App/Services/SecureStorageService.cs

57 lines
1.7 KiB
C#
Raw Normal View History

2019-03-28 21:09:39 +03:00
using Bit.Core.Abstractions;
using Newtonsoft.Json;
2019-04-09 03:49:48 +03:00
using Newtonsoft.Json.Serialization;
2019-03-28 21:09:39 +03:00
using System.Threading.Tasks;
namespace Bit.App.Services
2019-03-28 21:09:39 +03:00
{
public class SecureStorageService : IStorageService
{
2019-04-09 04:23:16 +03:00
private readonly string _keyFormat = "bwSecureStorage:{0}";
2019-04-09 03:49:48 +03:00
private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
2019-03-28 21:09:39 +03:00
public async Task<T> GetAsync<T>(string key)
{
var formattedKey = string.Format(_keyFormat, key);
var val = await Xamarin.Essentials.SecureStorage.GetAsync(formattedKey);
2019-04-09 04:23:16 +03:00
if(typeof(T) == typeof(string))
2019-03-28 21:09:39 +03:00
{
return (T)(object)val;
}
else
{
2019-04-09 03:49:48 +03:00
return JsonConvert.DeserializeObject<T>(val, _jsonSettings);
2019-03-28 21:09:39 +03:00
}
}
public async Task SaveAsync<T>(string key, T obj)
{
if(obj == null)
{
await RemoveAsync(key);
return;
}
var formattedKey = string.Format(_keyFormat, key);
2019-04-09 04:23:16 +03:00
if(typeof(T) == typeof(string))
2019-03-28 21:09:39 +03:00
{
await Xamarin.Essentials.SecureStorage.SetAsync(formattedKey, obj as string);
}
else
{
2019-04-09 03:49:48 +03:00
await Xamarin.Essentials.SecureStorage.SetAsync(formattedKey,
JsonConvert.SerializeObject(obj, _jsonSettings));
2019-03-28 21:09:39 +03:00
}
}
public Task RemoveAsync(string key)
{
var formattedKey = string.Format(_keyFormat, key);
Xamarin.Essentials.SecureStorage.Remove(formattedKey);
return Task.FromResult(0);
}
}
}