When user signup it works... but after login after directly when user login it ... says currentuser is not authorized to perform the action
but when after signup user refreshes the app or restart the app & then login it works......
I will share code Snippets
auth_repo.dart
auth_provider.dart
main.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/constants/app_constants.dart';
import '../services/appwrite_service.dart';
import '../models/user_model.dart';
class AuthRepository {
final Ref ref;
AuthRepository(this.ref);
Future<UserModel> signup({
required String email,
required String password,
required String username,
}) async {
try {
// Create Appwrite account
final account = AppwriteService.account;
final user = await account.create(
userId: ID.unique(),
email: email,
password: password,
name: username,
);
// Create user document in users collection
final databases = AppwriteService.databases;
final userDoc = await databases.createDocument(
databaseId: '66f81b280024be529cdd',
collectionId: AppConstants.usersCollection,
documentId: user.$id,
data: {
'email': email,
'username': username,
'profilePicture': null,
'bio': null,
'id': user.$id
},
);
return UserModel.fromMap(userDoc.data);
} catch (e) {
rethrow;
}
}```
required String email,
required String password,
}) async {
try {
// Login with Appwrite
final account = AppwriteService.account;
await account.createEmailPasswordSession(
email: email,
password: password,
);
// Get current user
final user = await account.get();
// Fetch user document
final databases = AppwriteService.databases;
final userDoc = await databases.getDocument(
databaseId: '66f81b280024be529cdd',
collectionId: AppConstants.usersCollection,
documentId: user.$id,
);
return UserModel.fromMap(userDoc.data);
} catch (e) {
rethrow;
}
}
Future<void> logout() async {
await AppwriteService.account.deleteSession(sessionId: 'current');
}
Future<UserModel?> getCurrentUser() async {
try {
final account = AppwriteService.account;
final user = await account.get();
final databases = AppwriteService.databases;
final userDoc = await databases.getDocument(
databaseId: '66f81b280024be529cdd',
collectionId: AppConstants.usersCollection,
documentId: user.$id,
);
return UserModel.fromMap(userDoc.data);
} catch (e) {
return null; // User is not logged in
}
}
Future<String?> getCurrentUserId() async {
final user = await getCurrentUser();
return user?.id;
}
// New method to update user profile
Future<UserModel> updateProfile({
required String username,
required String bio,
}) async {
try {
final account = AppwriteService.account;
final user = await account.get();```
final databases = AppwriteService.databases;
final userDoc = await databases.updateDocument(
databaseId: '66f81b280024be529cdd',
collectionId: AppConstants.usersCollection,
documentId: user.$id,
data: {
'username': username,
'bio': bio,
},
);
return UserModel.fromMap(userDoc.data);
} catch (e) {
rethrow;
}
}
}
// Provider for AuthRepository
final authRepositoryProvider = Provider((ref) => AuthRepository(ref));```
This is Auth Repo
import '../models/user_model.dart';
import '../repositories/auth_repository.dart';
class AuthState {
final UserModel? user;
final bool isLoading;
final String? error;
AuthState({this.user, this.isLoading = false, this.error});
}
class AuthNotifier extends StateNotifier<AuthState> {
final AuthRepository _authRepository;
AuthNotifier(this._authRepository) : super(AuthState(isLoading: true)) {
_loadCurrentUser();
}```
Future<void> _loadCurrentUser() async {
try {
final user = await _authRepository.getCurrentUser();
if (user != null) {
state = AuthState(user: user, isLoading: false); // User found
} else {
state = AuthState(user: null, isLoading: false); // No user, not logged in
}
} catch (e) {
state = AuthState(isLoading: false, error: e.toString()); // Error handling
}
}
// Method to check if the user is logged in
Future<void> checkAuthStatus() async {
try {
final user = await _authRepository.getCurrentUser();
if (user != null) {
state = AuthState(user: user, isLoading: false); // User found
} else {
state = AuthState(user: null, isLoading: false); // No user logged in
}
} catch (e) {
state = AuthState(isLoading: false, error: e.toString());
}
}
Future<void> signup({required String email, required String password, required String username}) async {
state = AuthState(isLoading: true);
try {
final user = await _authRepository.signup(email: email, password: password, username: username);
state = AuthState(user: user);
} catch (e) {
state = AuthState(error: e.toString(), isLoading: false);
}
}
Future<void> login({required String email, required String password}) async {
state = AuthState(isLoading: true);
try {
final user = await _authRepository.login(email: email, password: password);
state = AuthState(user: user);
} catch (e) {
state = AuthState(error: e.toString(), isLoading: false);
}
}
Future<void> logout() async {
await _authRepository.logout();
state = AuthState(); // Set state to not logged in
}
// New method to update user profile
Future<void> updateProfile({required String username, required String bio}) async {
state = AuthState(isLoading: true, user: state.user);
try {```
final updatedUser = await _authRepository.updateProfile(username: username, bio: bio);
state = AuthState(user: updatedUser, isLoading: false); // Update state with new user data
} catch (e) {
state = AuthState(error: e.toString(), isLoading: false); // Error handling
}
}
}
// Providers
final authNotifierProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
final authRepository = ref.watch(authRepositoryProvider);
return AuthNotifier(authRepository);
});````
Auth Provider
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:news/views/developer_page.dart';
import 'package:news/views/home_screen.dart';
import 'views/auth/signup_screen.dart';
import 'views/auth/login_screen.dart';
import 'views/splash_screen.dart';
import 'views/profile/profile_screen.dart';
import 'views/profile/edit_profile_screen.dart';
import '../repositories/auth_repository.dart';
import '../providers/auth_provider.dart';
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Article Reading App',
theme: ThemeData(primarySwatch: Colors.blue),
home: AuthGate(), // Entry point to check authentication state
routes: {
'/login': (context) => LoginScreen(),
'/signup': (context) => SignupScreen(),
'/profile': (context) => ProfileScreen(),
'/edit-profile': (context) => EditProfileScreen(),
'/home': (context) => HomeScreen(),
'/who-built-this-app': (context) => DeveloperPage(),
},
);
}
}
class AuthGate extends ConsumerStatefulWidget {
@override
_AuthGateState createState() => _AuthGateState();
}
class _AuthGateState extends ConsumerState<AuthGate> {
bool _isSplashVisible = true;
@override
void initState() {
super.initState();
// Show splash screen for 2 seconds and then load the auth state
Future.delayed(Duration(seconds: 2), () async {
await ref.read(authNotifierProvider.notifier).checkAuthStatus(); // Check auth status
setState(() {
_isSplashVisible = false;
});
});
}
@override
Widget build(BuildContext context) {
final authState = ref.watch(authNotifierProvider);
// Show splash screen while loading the authentication state
if (_isSplashVisible) {
return SplashScreen();
}```
if (authState.isLoading) {
return SplashScreen(); // You can show a loading splash screen if necessary
}
// Navigate based on user authentication state
if (authState.user != null) {
return HomeScreen(); // If the user is logged in, show HomeScreen
} else {
return LoginScreen(); // If no user is logged in, show LoginScreen
}
}
}```
main.dart
Any One please help
Recommended threads
- Error | general_unknown
I have built a website using Appwrite Cloud as backend, and also using sites for deployment. My website is live but sometimes it shows Appwrite's Error general_...
- Introducing new string column types made...
Adding new string types is hugely bennificial! Unfortunately it made the current column types not editable to change their types to the new longer field types.
- there is critical problem in this part
when user update the integer and double both get error not update or upload