78 lines
2.3 KiB
Dart
78 lines
2.3 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import '../data/auth_repository.dart';
|
|
import 'auth_state.dart';
|
|
|
|
class AuthCubit extends Cubit<AuthState> {
|
|
final AuthRepository _repo;
|
|
|
|
AuthCubit(this._repo) : super(const AuthState());
|
|
|
|
Future<void> checkAuth() async {
|
|
final hasToken = await _repo.hasSavedToken();
|
|
if (hasToken) {
|
|
final cachedUser = await _repo.getCachedUser();
|
|
if (cachedUser != null) {
|
|
emit(state.copyWith(
|
|
status: AuthStatus.authenticated,
|
|
user: cachedUser,
|
|
));
|
|
}
|
|
}
|
|
final user = await _repo.me();
|
|
if (user != null) {
|
|
emit(state.copyWith(
|
|
status: AuthStatus.authenticated,
|
|
user: user,
|
|
));
|
|
} else {
|
|
final hasTokenAfterMe = await _repo.hasSavedToken();
|
|
if (!hasTokenAfterMe) {
|
|
emit(state.copyWith(
|
|
status: AuthStatus.unauthenticated,
|
|
user: null,
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
Future<void> sendOtp(String phone) async {
|
|
if (phone.trim().isEmpty) {
|
|
emit(state.copyWith(status: AuthStatus.error, error: 'أدخل رقم الهاتف'));
|
|
return;
|
|
}
|
|
try {
|
|
emit(state.copyWith(status: AuthStatus.authenticating, phone: phone.trim()));
|
|
await _repo.sendOtp(phone.trim());
|
|
emit(state.copyWith(status: AuthStatus.codeSent, phone: phone.trim()));
|
|
} catch (_) {
|
|
emit(state.copyWith(status: AuthStatus.error, error: 'تعذّر إرسال الرمز'));
|
|
}
|
|
}
|
|
|
|
Future<void> verify(String code) async {
|
|
try {
|
|
emit(state.copyWith(status: AuthStatus.authenticating));
|
|
final user = await _repo.verify(state.phone, code.trim());
|
|
emit(state.copyWith(status: AuthStatus.authenticated, user: user));
|
|
} catch (_) {
|
|
emit(state.copyWith(status: AuthStatus.error, error: 'رمز غير صحيح'));
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await _repo.logout();
|
|
emit(const AuthState(status: AuthStatus.unauthenticated));
|
|
}
|
|
|
|
Future<void> updateName(String name) async {
|
|
try {
|
|
emit(state.copyWith(status: AuthStatus.authenticating));
|
|
final user = await _repo.updateName(name);
|
|
emit(state.copyWith(status: AuthStatus.authenticated, user: user));
|
|
} catch (_) {
|
|
emit(state.copyWith(status: AuthStatus.error, error: 'تعذّر حفظ الاسم'));
|
|
}
|
|
}
|
|
}
|