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

59 lines
1.8 KiB
C#
Raw Normal View History

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