frosty/lib/core/auth/auth_store.dart

176 lines
5.5 KiB
Dart
Raw Normal View History

2021-08-21 22:38:25 -04:00
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_web_auth/flutter_web_auth.dart';
2021-11-14 23:18:43 -05:00
import 'package:frosty/api/twitch_api.dart';
2022-01-07 21:56:45 -05:00
import 'package:frosty/constants/constants.dart';
import 'package:frosty/core/user/user_store.dart';
2021-11-14 23:18:43 -05:00
import 'package:mobx/mobx.dart';
2021-08-21 22:38:25 -04:00
2021-10-01 00:08:19 -04:00
part 'auth_store.g.dart';
class AuthStore = _AuthBase with _$AuthStore;
abstract class _AuthBase with Store {
2021-10-05 03:08:38 -04:00
/// Secure storage to store tokens.
static const _storage = FlutterSecureStorage();
/// The shared_preferences key for the default token.
static const _defaultTokenKey = 'default_token';
/// The shared_preferences key for the user token.
static const _userTokenKey = 'user_token';
final TwitchApi twitchApi;
/// Whether the token is valid or not.
var _tokenIsValid = false;
/// The store containing information relevant to the current user.
final UserStore user;
/// The current token.
@readonly
String? _token;
2021-10-05 03:08:38 -04:00
/// Whether the user is logged in or not.
@readonly
var _isLoggedIn = false;
2021-08-21 22:38:25 -04:00
2021-10-05 03:08:38 -04:00
/// Authentication headers for Twitch API requests.
@computed
Map<String, String> get headersTwitch => {'Authorization': 'Bearer $_token', 'Client-Id': clientId};
2021-08-21 22:38:25 -04:00
2022-01-15 16:51:11 -05:00
/// Error flag that will be non-null if login failed.
@readonly
String? _error;
_AuthBase({required this.twitchApi}) : user = UserStore(twitchApi: twitchApi);
2021-08-21 22:38:25 -04:00
/// Initialize by retrieving a token if it does not already exist.
@action
2021-08-24 09:58:31 -04:00
Future<void> init() async {
2022-01-15 16:51:11 -05:00
try {
// Read and set the currently stored user token, if any.
_token = await _storage.read(key: _userTokenKey);
2022-01-15 16:51:11 -05:00
// If the token does not exist, get the default token.
// Otherwise, log in.
if (_token == null) {
2022-01-15 16:51:11 -05:00
// Retrieve the currently stored default token if it exists.
_token = await _storage.read(key: _defaultTokenKey);
2022-01-15 16:51:11 -05:00
// If the token does not exist, get a new token and store it.
if (_token == null) {
_token = await twitchApi.getDefaultToken();
await _storage.write(key: _defaultTokenKey, value: _token);
2022-01-15 16:51:11 -05:00
}
} else {
// Initialize the user store.
await user.init(headers: headersTwitch);
if (user.details != null) _isLoggedIn = true;
}
2022-01-15 16:51:11 -05:00
// Validate the token.
_tokenIsValid = await twitchApi.validateToken(token: _token!);
2021-08-24 09:58:31 -04:00
2022-01-15 16:51:11 -05:00
// If the token is invalid, logout.
if (!_tokenIsValid) await logout();
2022-01-15 16:51:11 -05:00
_error = null;
} catch (e) {
debugPrint(e.toString());
_error = e.toString();
2021-08-21 22:38:25 -04:00
}
}
2021-10-05 03:08:38 -04:00
/// Initiates the OAuth sign-in process and updates fields accordingly upon successful login.
@action
2022-01-08 22:48:28 -05:00
Future<void> login({String? customToken}) async {
try {
2022-01-08 22:48:28 -05:00
if (customToken == null) {
// Create the OAuth sign-in URI.
final loginUrl = Uri(
scheme: 'https',
host: 'id.twitch.tv',
path: '/oauth2/authorize',
queryParameters: {
'client_id': clientId,
'redirect_uri': 'auth://',
'response_type': 'token',
'scope': 'chat:read chat:edit user:read:follows user:read:blocked_users user:manage:blocked_users',
'force_verify': 'true',
},
);
// Retrieve the OAuth redirect URI.
final result = await FlutterWebAuth.authenticate(
url: loginUrl.toString(),
callbackUrlScheme: 'auth',
);
// Parse the user token from the redirect URI fragment.
2022-01-19 13:18:35 -05:00
final url = Uri.parse(result.replaceFirst('#', '?'));
_token = url.queryParameters['access_token'];
2022-01-08 22:48:28 -05:00
} else {
_token = customToken;
}
_tokenIsValid = await twitchApi.validateToken(token: _token!);
2022-01-08 22:48:28 -05:00
if (!_tokenIsValid) return;
2021-08-24 09:58:31 -04:00
2021-10-05 03:08:38 -04:00
// Store the user token.
await _storage.write(key: _userTokenKey, value: customToken ?? _token);
// Initialize the user with the new token.
await user.init(headers: headersTwitch);
2021-10-05 03:08:38 -04:00
// Set the login status to logged in.
_isLoggedIn = true;
} catch (error) {
debugPrint('Login failed due to $error');
}
}
2021-10-05 03:08:38 -04:00
/// Logs out the current user and updates fields accordingly.
@action
Future<void> logout() async {
2022-01-15 16:51:11 -05:00
try {
2022-01-18 21:41:29 -05:00
// Revoke the existing user token and delete it.
await twitchApi.revokeToken(token: _token!);
await _storage.delete(key: _userTokenKey);
2022-01-15 16:51:11 -05:00
_token = null;
2022-01-15 16:51:11 -05:00
// Clear the user info.
user.dispose();
2022-01-15 16:51:11 -05:00
// If the default token already exists, set it.
_token = await _storage.read(key: _defaultTokenKey);
2022-01-15 16:51:11 -05:00
// If the default token does not already exist, get the new default token and store it.
// Else, validate the existing token.
if (_token == null) {
_token = await twitchApi.getDefaultToken();
await _storage.write(key: _defaultTokenKey, value: _token);
_tokenIsValid = await twitchApi.validateToken(token: _token!);
2022-01-15 16:51:11 -05:00
} else {
// Validate the stored token.
_tokenIsValid = await twitchApi.validateToken(token: _token!);
// If the stored token is invalid, get a new default token and store it.
if (!_tokenIsValid) {
_token = await twitchApi.getDefaultToken();
await _storage.write(key: _defaultTokenKey, value: _token);
2022-01-15 16:51:11 -05:00
_tokenIsValid = await twitchApi.validateToken(token: _token!);
}
}
2022-01-18 21:41:29 -05:00
// Set the login status to logged out.
_isLoggedIn = false;
debugPrint('Successfully logged out');
2022-01-15 16:51:11 -05:00
} catch (e) {
debugPrint(e.toString());
}
2021-08-21 22:38:25 -04:00
}
}