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

116 lines
3 KiB
C#
Raw Normal View History

2016-05-02 09:52:09 +03:00
using System;
using System.Text;
using System.Threading.Tasks;
using Bit.App.Abstractions;
using Bit.App.Models.Api;
2016-05-03 00:50:16 +03:00
using Plugin.Settings.Abstractions;
2016-05-02 09:52:09 +03:00
namespace Bit.App.Services
{
public class AuthService : IAuthService
{
private const string TokenKey = "token";
2016-05-03 00:50:16 +03:00
private const string UserIdKey = "userId";
2016-05-02 09:52:09 +03:00
private readonly ISecureStorageService _secureStorage;
2016-05-03 00:50:16 +03:00
private readonly ISettings _settings;
2016-05-02 09:52:09 +03:00
private readonly ICryptoService _cryptoService;
private readonly IAuthApiRepository _authApiRepository;
2016-05-02 09:52:09 +03:00
2016-05-03 00:50:16 +03:00
private string _token;
private string _userId;
2016-05-02 09:52:09 +03:00
public AuthService(
2016-05-03 00:50:16 +03:00
ISecureStorageService secureStorage,
ISettings settings,
2016-05-02 09:52:09 +03:00
ICryptoService cryptoService,
IAuthApiRepository authApiRepository)
2016-05-02 09:52:09 +03:00
{
_secureStorage = secureStorage;
2016-05-03 00:50:16 +03:00
_settings = settings;
2016-05-02 09:52:09 +03:00
_cryptoService = cryptoService;
_authApiRepository = authApiRepository;
2016-05-02 09:52:09 +03:00
}
public string Token
{
get
{
2016-05-03 00:50:16 +03:00
if(_token != null)
{
return _token;
}
2016-05-02 09:52:09 +03:00
var tokenBytes = _secureStorage.Retrieve(TokenKey);
2016-05-03 00:50:16 +03:00
if(tokenBytes == null)
{
return null;
}
_token = Encoding.UTF8.GetString(tokenBytes, 0, tokenBytes.Length);
return _token;
2016-05-02 09:52:09 +03:00
}
set
{
if(value != null)
{
var tokenBytes = Encoding.UTF8.GetBytes(value);
_secureStorage.Store(TokenKey, tokenBytes);
}
else
{
_secureStorage.Delete(TokenKey);
2016-05-03 00:50:16 +03:00
_token = null;
}
}
}
public string UserId
{
get
{
if(_userId != null)
{
return _userId;
}
_userId = _settings.GetValueOrDefault<string>(UserIdKey);
return _userId;
}
set
{
if(value != null)
{
_settings.AddOrUpdateValue(UserIdKey, value);
}
else
{
_settings.Remove(UserIdKey);
_userId = null;
2016-05-02 09:52:09 +03:00
}
}
}
public bool IsAuthenticated
{
get
{
2016-05-03 00:50:16 +03:00
return _cryptoService.Key != null && Token != null && UserId != null;
2016-05-02 09:52:09 +03:00
}
}
2016-05-03 00:50:16 +03:00
public void LogOut()
{
Token = null;
UserId = null;
_cryptoService.Key = null;
}
2016-05-02 09:52:09 +03:00
public async Task<ApiResult<TokenResponse>> TokenPostAsync(TokenRequest request)
{
// TODO: move more logic in here
return await _authApiRepository.PostTokenAsync(request);
2016-05-02 09:52:09 +03:00
}
}
}