Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions mobile/lib/controllers/auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:dio/dio.dart';
import 'package:mobile/models/user.dart';
import '../services/auth.dart';

class AuthState extends ChangeNotifier {
Expand All @@ -12,18 +13,43 @@ class AuthState extends ChangeNotifier {
bool _isLoading = false;
String? _errorMessage;

UserModel? _currentUser;

String? get token => _token;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;

UserModel? get currentUser => _currentUser;

static VoidCallback? onGlobalUnauthorized;

AuthState() {
onGlobalUnauthorized = logoutSilently;
}

Future<void> loadUserProfile() async {
if (_token == null) return;

try {
final res = await _authService.getCurrentUser(_token!);
final data = res.data;

final userData = data['data'] ?? data['user'] ?? data;

_currentUser = UserModel.fromJson(userData);
notifyListeners();
} catch (e) {
debugPrint("Failed to load user profile: $e");
}
}

Future<String?> checkAutoLogin() async {
_token = await _storage.read(key: "access_token");

if (_token != null) {
await loadUserProfile();
}

notifyListeners();
return _token;
}
Expand Down Expand Up @@ -53,6 +79,9 @@ class AuthState extends ChangeNotifier {
tokens['access_token'],
tokens['refresh_token'],
);

await loadUserProfile();

_isLoading = false;
notifyListeners();
return true;
Expand Down Expand Up @@ -100,6 +129,9 @@ class AuthState extends ChangeNotifier {
tokens['access_token'],
tokens['refresh_token'],
);

await loadUserProfile();

_isLoading = false;
notifyListeners();
return true;
Expand All @@ -119,13 +151,15 @@ class AuthState extends ChangeNotifier {

Future<void> logout() async {
_token = null;
_currentUser = null;
await _authService.logout();
notifyListeners();
}

void logoutSilently() {
if (_token != null) {
_token = null;
_currentUser = null;
_authService.logout();
notifyListeners();
}
Expand Down
Loading
Loading