0

I want to create a function for auto login like Facebook in flutter but don't know the best way to do it. My function for login and auto login, I used SharedPreferences plugin for store data.

SignIn function:

Future<void> signIn(String userName, String pass) async {
final url = Uri.parse('MyAPI_login');// sorry it for privacy
debugPrint("$userName / $pass");
try {
  var respone = await http.post(url, body: {
    'user_name': userName, 
    'password': pass, 
    'platform': 'mobile',
    'device_token': '',
  });
  final reponseData = jsonDecode(respone.body);
  _userName = userName;
  _token = reponseData['data']['accessToken'];
  _expiryDate = DateTime.now().add(Duration(
      seconds: int.parse(reponseData['data']['tokenExpireAt'].toString())));
  _refreshToken = reponseData['data']['refreshToken'].toString();
  _timerRefreshToken =
      int.parse(reponseData['data']['refreshTokenExpireAt'].toString());
  // debugPrint(
  //     '$_token \n $_expiryDate \n $_refreshToken \n $_timerRefreshToken');
  notifyListeners();
  final prefs = await SharedPreferences.getInstance();
  final userData = json.encode({
    '_userId': _userName.toString(),
    'token': _token.toString(),
    'expiryDate': _expiryDate!.toIso8601String(),
    'refreshToken': _refreshToken,
    'timerRefreshToken': _timerRefreshToken.toString(),
  });
  await prefs.setString('userData', userData);
} catch (error) {
  throw Exception(error.toString());
}}

TryAutoLogin function:

Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
  return false;
}
final extractedUserData = json
    .decode(prefs.getString('userData').toString()) as Map<String, dynamic>;
final expiryDate =
    DateTime.parse(extractedUserData['expiryDate'].toString());
if (expiryDate.isBefore(DateTime.now())) {
  _token = extractedUserData['refreshToken'].toString();
  _expiryDate = DateTime.now().add(
      Duration(seconds: int.parse(extractedUserData['timerRefreshToken'])));
  _refreshNewToken(extractedUserData['refreshToken'].toString());
}

return true;}

RefreshNewToken function:

Future<void> _refreshNewToken(String oldRefreshToken) async {
final url =
    Uri.parse('MyAPI_refreshtoken');
var respone = await http.post(url, body: {'refreshToken': oldRefreshToken});
debugPrint(respone.body);}

My API for login response is like this:

{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODI4NTk5M30.3kMByfweUhzQM-4d5S0G7tUaC0e-nZLJF3_dbdV_7fM","tokenExpireAt":1658285940964,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODM2ODc5M30.Bv7PZrnx9zDzwIuxNMppFxlwZlJEnthVjEYBKYl-aWM","refreshTokenExpireAt":1658368740964},"message":"Logged in successfully!","status":200,"errors":null}

Also, my API has a refresh token request, it returns like this:

{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODI4NTk5NH0.wcyouoprMHFnRD4_oSpP9RSasxMBrktX6nZI2x2PQec","tokenExpireAt":1658285940242,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODM2ODc5NH0.y-8MP4M_1LzCwmqo_KQZGyQXkycrxdOLWz_fdqIPRyQ","refreshTokenExpireAt":1658368740242},"message":"Request successfully!","status":200,"errors":null}

3
  • What is the issue you are facing? Jul 20, 2022 at 4:02
  • Sorry for the confusing question, I just don't have any idea about the autoLogin function, because I have two tokens sent by the server so when the token is expired, should I use the refresh token to assign the token variable or I just simply use refresh with the time then I call for a new token for server and when I have two new tokens so i assign token and refreshToken? Jul 20, 2022 at 5:21
  • Take a look at this: rfc-editor.org/rfc/rfc6749#section-1.5. Your flow might be more simple, but the idea is there how and when to use a refresh token. Jul 20, 2022 at 5:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.