Skip to content

Commit

Permalink
chore(ml-opensource#80): Introduce AuthTokenStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
nivisi committed Jan 5, 2023
1 parent 6792e4c commit 046c236
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/data/api/new/auth_token_storage/auth_token_storage.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'package:flutter_template/data/model/auth/auth_tokens.dart';

/// A storage for authentication tokens.
abstract class AuthTokenStorage {
// Future<String?> get accessToken;
// Future<String?> get refreshToken;
// Future<double?> get tokenExpiryTime;

// Future<bool> hasValidAccessToken();

// Future setAccessToken(String token);
// Future setRefreshToken(String token);
// Future setRefreshTokenExpiry(double expiresIn);

Future<AuthTokens?> get();
Future<void> set(AuthTokens tokens);

Future<void> clear();
}
44 changes: 44 additions & 0 deletions lib/data/api/new/auth_token_storage/secure_auth_token_storage.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_template/data/api/new/auth_token_storage/auth_token_storage.dart';
import 'package:flutter_template/data/model/auth/auth_tokens.dart';
import 'package:injectable/injectable.dart';

/// A storage for auth tokens that uses [FlutterSecureStorage].
@LazySingleton(as: AuthTokenStorage)
class SecureAuthTokenStorage extends AuthTokenStorage {
static const String _prefix = 'auth';

@visibleForTesting
static const String tokenKey = '${_prefix}_token';

SecureAuthTokenStorage(this._storage);

final FlutterSecureStorage _storage;

@override
Future<AuthTokens?> get() async {
final json = await _storage.read(key: tokenKey);

if (json == null) {
return null;
}

final map = jsonDecode(json) as Map<String, dynamic>;

return AuthTokens.fromJson(map);
}

@override
Future<void> set(AuthTokens tokens) {
final json = jsonEncode(tokens.toJson());
return _storage.write(key: tokenKey, value: json);
}

@override
Future<void> clear() {
return _storage.delete(key: tokenKey);
}
}

0 comments on commit 046c236

Please sign in to comment.