2019-03-28 21:09:39 +03:00
|
|
|
|
using Bit.Core.Abstractions;
|
2019-04-09 03:48:18 +03:00
|
|
|
|
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;
|
|
|
|
|
|
2019-04-10 00:10:56 +03:00
|
|
|
|
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)
|
|
|
|
|
{
|
2019-04-09 03:48:18 +03:00
|
|
|
|
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;
|
|
|
|
|
}
|
2019-04-09 03:48:18 +03:00
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|