import 'dart:async';
import 'package:appwrite/models.dart';
import 'package:flutter/foundation.dart';
import 'package:appwrite/appwrite.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:servicescheinapp/constants/constants.dart';
enum AuthStatus {
uninitialized,
authenticated,
unauthenticated,
}
// Helper class for the appwrite database
// connects to Database and Storage
class AppWriteAuth extends ChangeNotifier {
Client client = Client();
late final Account account;
late User _currentUser;
AuthStatus _status = AuthStatus.uninitialized;
// Getter methods
User get currentUser => _currentUser;
AuthStatus get status => _status;
String? get username => _currentUser?.name;
String? get email => _currentUser?.email;
String? get userid => _currentUser?.$id;
AppWriteAuth() {
init();
loadUser();
}
init() async {
await dotenv.load(fileName: "constants.env");
String serverURL = dotenv.env['SERVER_URL']!;
String apiEndpoint = 'v1';
client
.setEndpoint('$serverURL$apiEndpoint')
.setProject(appwriteProjectID2)
.setSelfSigned(status: true);
// For self signed certificates, only use for development
account = Account(client);
print('Initialization complete');
}
loadUser() async {
try {
final user = await account.get();
_status = AuthStatus.authenticated;
_currentUser = user;
} catch (e) {
_status = AuthStatus.unauthenticated;
} finally {
notifyListeners();
}
}
Future<User> createUser(
{required String email, required String password}) async {
try {
final user = await account.create(
userId: ID.unique(), email: email, password: password);
return user;
} finally {
notifyListeners();
}
}
Future<Session> createEmailSession(
{required String email, required String password}) async {
try {
final session = await account.createEmailPasswordSession(
email: email, password: password);
_currentUser = await account.get();
_status = AuthStatus.authenticated;
return session;
} finally {
notifyListeners();
}
}
// check Authentication state
Future<void> checkAuth() async {
try {
_currentUser = await account.get();
// Logged in
print('Logged in and authenticated');
print('User: ${_currentUser.email}');
} catch (e) {
// Not logged in
print('Not logged in');
print('Error: $e');
}
}
signOut() async {
try {
await account.deleteSession(sessionId: 'current');
_status = AuthStatus.unauthenticated;
} finally {
notifyListeners();
}
}
}