1
0
mirror of https://github.com/bitwarden/mobile.git synced 2024-10-01 04:27:39 +02:00
bitwarden-mobile/src/App/Services/SecureStorageService.cs

57 lines
1.7 KiB
C#
Raw Normal View History

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