Initial commit
This commit is contained in:
68
lib/services/authservice.dart
Normal file
68
lib/services/authservice.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:mileograph_flutter/objects/objects.dart';
|
||||
import 'package:mileograph_flutter/services/apiService.dart';
|
||||
|
||||
class AuthService extends ChangeNotifier {
|
||||
final ApiService api;
|
||||
|
||||
AuthService({required this.api});
|
||||
|
||||
AuthenticatedUserData? _user;
|
||||
|
||||
bool get isLoggedIn => _user != null;
|
||||
String? get token => _user?.access_token;
|
||||
String? get userId => _user?.user_id;
|
||||
String? get username => _user?.username;
|
||||
String? get fullName => _user?.full_name;
|
||||
|
||||
void setLoginData({
|
||||
required String userId,
|
||||
required String username,
|
||||
required String fullName,
|
||||
required String accessToken,
|
||||
required String email,
|
||||
}) {
|
||||
_user = AuthenticatedUserData(
|
||||
user_id: userId,
|
||||
username: username,
|
||||
full_name: fullName,
|
||||
access_token: accessToken,
|
||||
email: email,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> login(String username, String password) async {
|
||||
final formData = {
|
||||
'grant_type': 'password',
|
||||
'username': username,
|
||||
'password': password,
|
||||
'scope': '',
|
||||
'client_id': 'string',
|
||||
'client_secret': 'string',
|
||||
};
|
||||
|
||||
// 1. Get token
|
||||
final tokenResponse = await api.postForm('/token', formData);
|
||||
final accessToken = tokenResponse['access_token'];
|
||||
|
||||
// 2. Get user details
|
||||
final userResponse = await api.get(
|
||||
'/users/me',
|
||||
headers: {
|
||||
'Authorization': 'Bearer $accessToken',
|
||||
'accept': 'application/json',
|
||||
},
|
||||
);
|
||||
|
||||
// 3. Populate state
|
||||
setLoginData(
|
||||
userId: userResponse['user_id'],
|
||||
username: userResponse['username'],
|
||||
fullName: userResponse['full_name'],
|
||||
accessToken: accessToken,
|
||||
email: userResponse['email'],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user