Flutter fingerprint login

Jun 7 '21

Post Original

No te rompas mucho la cabeza con esta funcionalidad.

Usa Shared Preferences para guardas las credenciales de tus usuarios. Puedes pasarte por su documentación para ver cómo funciona. Pero para tu comodidad, te ahorro el trabajo con esta pequeña clase.

import 'package:shared_preferences/shared_preferences.dart';

class SessionParams {
  static final String _userKey = '_userKey';
  static final String _passwordKey = '_passwordKey';
  final String user;
  final String password;

  SessionParams._(this.user, this.password);

  static Future<void> deleteSession() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }

  static Future<SessionParams> getSession() async {
    var prefs = await SharedPreferences.getInstance();
    var user = prefs.getString(_userKey) ?? '';
    var password = prefs.getString(_passwordKey) ?? '';
    return user, password);
  }

  /// ❗ Throwable Function
  Future<void> saveSession(String user, String password) async {
    var prefs = await SharedPreferences.getInstance();
    var isSaveUserParam =
        await prefs.setString(_userKey, user);
    var isSavePasswordParam = await prefs.setString(_passwordKey, password);

    if (isSaveUserParam && isSavePasswordParam) return;

    deleteSession();
    throw '<SessionParams> session not saved';
  }

  @override
  String toString() {
    return 'SessionParams {user: $user, password $password}';
  }
}
Enter fullscreen mode Exit fullscreen mode

Para pedir la huella dactilar podemos hacer uso de local_auth. Aquí también te echó una mano, buapo, con estás pequeñas funciones.

Future<bool> _canCheckBiometrics() async {
  return await _auth.canCheckBiometrics;
}

Future<bool> _faceIdAvailable() async {
  List<BiometricType> availableBiometrics =
      await _auth.getAvailableBiometrics();
  if (Platform.isIOS && availableBiometrics.contains(BiometricType.face))
    return true;
  return false;
}

Future<bool> _authenticateWithBiometrics() async {
  bool authenticated = false;

  try {
    authenticated = await _auth.authenticate(
        localizedReason: 'Scan your fingerprint to authenticate',
        useErrorDialogs: true,
        stickyAuth: true,
        biometricOnly: true);
  } on PlatformException catch (e) {
    print(e);
    return authenticated;
  } catch (e) {
    print('Oooopps Algo salio mal 🤷‍♂️');
  }

  return authenticated;
}
Enter fullscreen mode Exit fullscreen mode

Ahora solo usamos todo lo anterior hecho 🚀🚀.

Future<void> loginWithBiometrics(){
  try {
    var session = await SessionParams.getSession();
    var authenticateWithBiometrics = await _authenticateWithBiometrics();

    if (authenticateWithBiometrics) {
      doLoginEvent(session.user, session.password, true);
    }
  } catch (e) {
    print('Oooopps Algo salio mal 🤷‍♂️');
  }
}

Future<bool> doLoginEvent(String user, String password, {bool remember = false}) async {
  // TODO: Este es el equivalente a tu función para hacer login.
  // Reemplázala 
  if (remember)
    await (await SessionParams.getSession())
              .saveSession(event.user, event.password);
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Mucha suerte en tus proyectos, precioso ❤️. Déjame tu opinión ¿Prefieres este tipo de ejemplos o preferirías una aplicación completa? ¿Otro tipo de tutoriales? Ayúdame a ayudarte.

PD: Si te preocupa la seguridad puedes pasar los parámetros por crypt. Se le deja este último paso al lector. Si eres muy flojo déjame un comentario y te echó un cable.

Powered by dev.to