Home > database >  how to create redirect to login if not authorized in flutter
how to create redirect to login if not authorized in flutter

Time:12-19

how to make if the user's token is expired or not authorized it will be redirected to the login page. I have a problem when I login, if the user token is expired, it should be redirected to the login page, but in this case it doesn't return to the login page, instead it gives an 'exception' error message, is there a code I missed. Thank you.

Future<User?> login(String nim, String password) async {
    String url = Constant.baseURL;
    try {
      var body = {
        'username': nim,
        'password': password,
      };
      var response = await http.post(
        Uri.parse(
          '$url/login_mhs',
        ),
        body: body,
      );
      if (response.statusCode == 200) {
        final token = jsonDecode(response.body)['data']['access_token'];
        await UtilSharedPreferences.setToken(token);
        print(token);
        print(await UtilSharedPreferences.getToken());
        return User.fromJson(jsonDecode(response.body));
      } else {
        return null;
      }
    } catch (e) {
      print(e);
      throw Exception();
    }
  }

and this when doing get data

Future<UserBiodata> getDataMahasiswa() async {
    String url = Constant.baseURL;
    String token = await UtilSharedPreferences.getToken();
    final response = await http.get(
      Uri.parse(
        '$url/auth/mhs_siakad/biodata',
      ),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    if (response.statusCode == 200) {
      return UserBiodata.fromJson(jsonDecode(response.body));
    } else {
      throw Exception();
    }
  }

this when calling it in the widget

TextButton(
                                  onPressed: () async {
                                    final prefs =
                                        await SharedPreferences.getInstance();
                                    prefs.setString(Constant.token, '');
                                    if (nimController.text.isEmpty ||
                                        passwordController.text.isEmpty) {
                                      showError('NIM tidak sesuai');
                                    } else {
                                      setState(() {
                                        isLoading = true;
                                      });
                                      User? user = await Provider.of<Services>(
                                              context,
                                              listen: false)
                                          .login(nimController.text,
                                              passwordController.text);
                                      setState(() {
                                        isLoading = false;
                                      });
                                      if (user == null) {
                                        showError('NIM/Password tidak sesuai');
                                      } else {
                                        userProvider.user = user;
                                        Navigator.pushNamedAndRemoveUntil(
                                          context,
                                          '/main',
                                          (route) => false,
                                        );
                                      }
                                    }
                                  },
                                  style: TextButton.styleFrom(
                                    backgroundColor: primaryColor,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(66),
                                    ),
                                  ),
                                  child: Text(
                                    "Login",
                                    style: boldButton,
                                  ),
                                ),

this is the result when I have a user whose token is expired or not authorized the result is like this enter image description here

CodePudding user response:

Use another if else condition (nested into your else of the event) like below:

   if (user == null) {
    showError('NIM/Password tidak sesuai');
    } else {
       if (token_is_not_found_equals_true){
          Navigator.pushNamedAndRemoveUntil(
           context,
            '/login',
         (route) => false,
          );
           }

   else {
    userProvider.user = user;
     Navigator.pushNamedAndRemoveUntil(
       context,
        '/main',
     (route) => false,
    );
    }
    }

CodePudding user response:

The way I handle is using the package flutter_modular, there you have a feature call Route Guard. You check details in it's documentation. It's very easy to understand and implement.

I think it's the cleanest way to handle users unauthorized users.

  • Related