authorize static method
Method that implements the OAuth 2.0 protocol and gets (and retain)
in the SharedPreferences
the access and refresh tokens from Dexcom APIs.
Implementation
static Future<bool> authorize(
{BuildContext? context,
required String clientID,
required String clientSecret,
required String redirectUri,
required String callbackUrlScheme,
required bool isSandbox}) async {
// Instantiate Dio and its Response
Dio dio = Dio();
Response response;
// Generate the Dexcom url
final dexcomAuthorizeFormUrl = DexcomAuthAPIURL.authorizeForm(
redirectUri: redirectUri, clientID: clientID, isSandbox: isSandbox);
// Perform authentication
try {
final result = await FlutterWebAuth.authenticate(
url: dexcomAuthorizeFormUrl.url,
callbackUrlScheme: callbackUrlScheme);
//Get the auth code
final code = Uri.parse(result).queryParameters['code'];
// Generate the Dexcom url
final dexcomAuthorizeUrl = DexcomAuthAPIURL.authorize(
redirectUri: redirectUri,
code: code!,
clientID: clientID,
clientSecret: clientSecret,
isSandbox: isSandbox);
response = await dio.post(
dexcomAuthorizeUrl.url,
data: dexcomAuthorizeUrl.data,
options: Options(
contentType: Headers.formUrlEncodedContentType,
),
);
// Debugging
final logger = Logger();
logger.i('$response');
// Save authorization tokens
final accessToken = response.data['access_token'] as String;
final refreshToken = response.data['refresh_token'] as String;
final expires = response.data['expires_in'] as int;
GetIt.instance<SharedPreferences>()
.setString('dexcomAccessToken', accessToken);
GetIt.instance<SharedPreferences>()
.setString('dexcomRefreshToken', refreshToken);
GetIt.instance<SharedPreferences>()
.setString('dexcomTokenExpires', Formats.fullDateFormat.format(DateTime.now().add(Duration(seconds: expires))));
GetIt.instance<SharedPreferences>()
.setString('dexcomRedirectUri', redirectUri);
} catch (e) {
print(e);
} // catch
return true;
}