Skip to content
Back

Current user is not authorized to perform this action

  • 0
  • Databases
  • Flutter
  • General
  • Auth
Arif Qayoom
20 Dec, 2024, 05:51

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

TL;DR
Developers are encountering an issue where the current user is not authorized to perform actions after logging in without a page refresh. The problem seems to lie in the authentication setup. Upon signup, the process works fine, but login fails without a page reload. One potential solution could involve checking the authentication status after login or ensuring the authorization process is correctly handled within the authentication flow. If the issue persists, further debugging in the authentication logic may be needed.
Arif Qayoom
20 Dec, 2024, 05:52
TypeScript
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;
    }
  }```
Arif Qayoom
20 Dec, 2024, 05:53
TypeScript
    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();```
Arif Qayoom
20 Dec, 2024, 05:53
TypeScript
      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));```
Arif Qayoom
20 Dec, 2024, 05:53

This is Auth Repo

Arif Qayoom
20 Dec, 2024, 05:55
TypeScript
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();
  }```
Arif Qayoom
20 Dec, 2024, 05:55
TypeScript
  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 {```
Arif Qayoom
20 Dec, 2024, 05:55
TypeScript
      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);
});````
Arif Qayoom
20 Dec, 2024, 05:56

Auth Provider

Arif Qayoom
20 Dec, 2024, 05:56
TypeScript
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();
    }```
Arif Qayoom
20 Dec, 2024, 05:57
TypeScript
    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
    }
  }
}```
Arif Qayoom
20 Dec, 2024, 05:57

main.dart

Arif Qayoom
20 Dec, 2024, 05:57

Any One please help

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more