barcode_scanner/lib/services/token_provider.dart
mandreshope b5e83e5b7f feat: Implements API-based user authentication
Replaces the mocked login flow with an actual API call to an authentication endpoint.

Updates the `AuthStruct` schema to align with the new API response, including fields for `accessToken`, `dbName`, `uid`, `name`, and `username`.

Introduces a `UserConnectedProvider` service for managing the storage and retrieval of authenticated user details, centralizing this logic and replacing prior direct local storage methods.

Integrates the new authentication process and user storage service into the login, reception, and profile pages for a unified experience.

Adjusts the splash screen duration to reflect the real-time nature of the authentication check.
2025-07-25 17:06:36 +03:00

77 lines
2.3 KiB
Dart

import 'dart:convert';
import 'package:barcode_scanner/backend/schema/user/user_struct.dart';
import 'package:barcode_scanner/services/secure_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
final tokenProvider = Provider((ref) {
final storage = ref.watch(sharedPrefsProvider);
return TokenProvider(storage);
});
class TokenProvider {
TokenProvider(this._storage);
final FlutterSecureStorage _storage;
static const String tokenKey = "tokenKey";
static const String refreshTokenKey = "refreshTokenKey";
Future<void> setToken(String token) async {
return _storage.write(key: tokenKey, value: token);
}
Future<void> setRefreshToken(String token) async {
return _storage.write(key: refreshTokenKey, value: token);
}
// Method to get the token from secure storage and check if it's expired
Future<String?> getToken() async {
final token = await _storage.read(key: tokenKey);
debugPrint("Token expired: $token");
return token;
}
Future<String?> getRefreshToken() async {
final refreshToken = await _storage.read(key: refreshTokenKey);
debugPrint("Refresh token: $refreshToken");
return refreshToken;
}
// Method to delete the token from secure storage
Future<void> deleteToken() async {
await _storage.delete(key: tokenKey);
await _storage.delete(key: refreshTokenKey);
}
}
final userConnectedProvider = Provider((ref) {
final storage = ref.watch(sharedPrefsProvider);
return UserConnectedProvider(storage);
});
class UserConnectedProvider {
UserConnectedProvider(this._storage);
final FlutterSecureStorage _storage;
static const String key = "userConnectedKey";
Future<void> set(UserStruct user) async {
return _storage.write(key: key, value: jsonEncode(user.toJson()));
}
// Method to get the token from secure storage and check if it's expired
Future<UserStruct?> get() async {
final res = await _storage.read(key: key);
if (res == null) {
return null;
} else {
return UserStruct.fromJson(jsonDecode(res));
}
}
// Method to delete the token from secure storage
Future<void> delete() async {
await _storage.delete(key: key);
}
}