iampass 0.0.1 copy "iampass: ^0.0.1" to clipboard
iampass: ^0.0.1 copied to clipboard

PlatformAndroidiOS
outdated

IAMPASS Flutter Plugin

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;

import 'package:flutter/services.dart';
import 'package:iampass/iampass.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:encrypted_shared_preferences/encrypted_shared_preferences.dart';
import 'package:iampass/iampass_user.dart';
import 'package:iampass/iampass_authentication_params.dart';
import 'package:iampass/iampass_authentication_session.dart';
import 'package:iampass/iampass_authentication_request.dart';
import 'package:iampass_example/splash_screen.dart';

class Init {
  static IAMPASSUser? currentUser;
  static String appUserID = "";
  static Future initialize() async {
    await _loadSettings();
    if (currentUser != null) {
      await _updateUser();
      await _saveUser();
    }
  }

  static _loadSettings() async {
    EncryptedSharedPreferences encryptedSharedPreferences =
        EncryptedSharedPreferences();

    String rawValue = await encryptedSharedPreferences.getString("user");

    if (rawValue.isNotEmpty) {
      // Convert to map
      Map<String, dynamic> m = jsonDecode(rawValue);
      currentUser = IAMPASSUser.fromJson(m);
    }

    appUserID = await encryptedSharedPreferences.getString("app-user-id");
  }

  static _updateUser() async {
    var iampassPlugin = Iampass();
    currentUser = await iampassPlugin.updateUser(
        "user", currentUser!, "notificationToken");
  }

  static _saveUser() async {
    if (currentUser != null) {
      String encoded = jsonEncode(currentUser);
      EncryptedSharedPreferences encryptedSharedPreferences =
          EncryptedSharedPreferences();

      if (!await encryptedSharedPreferences.setString("user", encoded)) {
        developer.log("Failed to save updated user.",
            name: "iampass.interface");
      }
    }
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _iampassPlugin = Iampass();
  IAMPASSUser? _currentUser;
  IAMPASSAuthenticationSession? _currentSession;

  final TextEditingController usernameController = TextEditingController();
  EncryptedSharedPreferences encryptedSharedPreferences =
      EncryptedSharedPreferences();

  final Future _initFuture = Init.initialize();

  bool _hasInitialized = false;
  String _appUserID = "";

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<IAMPASSUser?> loadIAMPassUser() async {
    String rawValue = await encryptedSharedPreferences.getString("user");

    if (rawValue.isNotEmpty) {
      // Convert to map
      Map<String, dynamic> m = jsonDecode(rawValue);
      IAMPASSUser u = IAMPASSUser.fromJson(m);
      developer.log("Added user", name: "iampass.interface");
      return u;
    }
    return null;
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  void showErrorMessage(String message) {
    showMessage(message, true);
  }

  void showSuccessMessage(String message) {
    showMessage(message, false);
  }

  void showMessage(String message, bool error) {
    MaterialColor backgroundColor = error ? Colors.red : Colors.green;
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: backgroundColor,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  void onAddUser() async {
    try {
      String userID = usernameController.text;
      await _iampassPlugin.addUser(userID, "*notificationToken").then((user) {
        if (user == null) {
          showErrorMessage("addUser Failed");
        } else {
          // The user has been added.
          String encoded = jsonEncode(user);

          encryptedSharedPreferences.setString("user", encoded);
          encryptedSharedPreferences.setString("app-user-id", userID);

          setState(() {
            _currentUser = user;
            _appUserID = userID;
          });
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "addUser Failed.");
    } catch (e) {
      showErrorMessage("addUser Failed");
    }
  }

  void onRegisterUser() async {
    try {
      String userID = usernameController.text;
      await _iampassPlugin.registerUser(userID).then((registered) {
        if (!registered) {
          showErrorMessage("registerUser Failed");
        } else {
          showSuccessMessage("registerUser Succeeded");
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "registerUser Failed");
    } catch (e) {
      showErrorMessage("registerUser Failed");
    }
  }

  void onRegisterDevice() async {
    try {
      String userID = usernameController.text;
      await _iampassPlugin
          .registerDevice(userID, "*notificationToken")
          .then((device) {
        if (device == null) {
          showErrorMessage("registerDevice Failed");
        } else {
          // Save the user
          String encoded = jsonEncode(device);

          encryptedSharedPreferences.setString("user", encoded);
          encryptedSharedPreferences.setString("app-user-id", userID);
          setState(() {
            _currentUser = device;
            _appUserID = userID;
          });
          showSuccessMessage("registerDevice Succeeded");
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "registerDevice Failed");
    } catch (e) {
      showErrorMessage("registerDevice Failed");
    }
  }

  void onHandleRegistrationLink() async {
    try {
      String userID = usernameController.text;
      await _iampassPlugin
          .getRegistrationLink(userID, userID)
          .then((registrationLink) {
        if (registrationLink == null) {
          showErrorMessage("getRegistrationLink Failed");
        } else {
          // Save the user
          handleRegistrationLink(registrationLink);
          showSuccessMessage("registerDevice Succeeded");
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "getRegistrationLink Failed");
    } catch (e) {
      showErrorMessage("getRegistrationLink Failed");
    }
  }

  void handleRegistrationLink(String registrationLink) async {
    String userID = usernameController.text;

    try {
      await _iampassPlugin
          .handleRegistrationLink(registrationLink, "*notificationToken")
          .then((device) {
        if (device == null) {
          showErrorMessage("handleRegistrationLink Failed");
        } else {
          // Save the user
          String encoded = jsonEncode(device);

          encryptedSharedPreferences.setString("user", encoded);
          encryptedSharedPreferences.setString("app-user-id", userID);
          setState(() {
            _currentUser = device;
            _appUserID = userID;
          });
          showSuccessMessage("registerDevice Succeeded");
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "getRegistrationLink Failed");
    } catch (e) {
      showErrorMessage("getRegistrationLink Failed");
    }
  }

  void onAuthenticateUser() async {
    try {
      IAMPASSStartAuthenticationParams params =
          IAMPASSStartAuthenticationParams(
              _appUserID, null, null, _currentUser!);

      await _iampassPlugin.authenticateUser(params).then((session) {
        if (session == null) {
          showErrorMessage("authenticateUser Failed");
        } else {
          showSuccessMessage("authenticateUser Succeeded");
          setState(() {
            _currentSession = session;
          });
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "Failed to authenticate user.");
    } catch (e) {
      showErrorMessage("Failed to authenticate user.");
    }
  }

  void onHandleAuthenticationRequest() async {
    try {
      IAMPASSStartAuthenticationParams params =
          IAMPASSStartAuthenticationParams(
              _appUserID, null, null, _currentUser!);

      await _iampassPlugin.debugStartAuth(params).then((result) async {
        if (result['session'] != null && result['request'] != null) {
          IAMPASSAuthenticationSession session = result['session'];
          IAMPASSAuthenticationRequest request = result['request'];

          await _iampassPlugin
              .handleAuthenticationRequest(request, _currentUser!)
              .then((session) {
            if (session) {
              showSuccessMessage("handleAuthenticationRequest Succeeded");
            } else {
              showErrorMessage("handleAuthenticationRequest Failed");
            }
          });
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "handleAuthenticationRequest Failed");
    } catch (e) {
      showErrorMessage("handleAuthenticationRequest Failed");
    }
  }

  void onEndSession() async {
    try {
      await _iampassPlugin.endSession(_currentSession!).then((ended) {
        if (ended) {
          showSuccessMessage("endSession Succeeded");
          setState(() {
            _currentSession = null;
          });
        }
      });
    } catch (updateException) {
      showErrorMessage("endSession Failed");
    }
  }

  void onUpdateUser() async {
    try {
      await _iampassPlugin
          .updateUser(_appUserID, _currentUser!, "*notificationToken")
          .then((user) {
        // The user has been updated.
        if (user != null) {
          showSuccessMessage("updateUser Succeeded");
          if (user.trainingRequired) {
            // Do training
            doTraining(user);
          } else {
            setState(() {
              _currentUser = user;
            });
          }
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "updateUser Failed");
    } catch (e) {
      showErrorMessage("updateUser Failed");
    }
  }

  void doTraining(IAMPASSUser user) async {
    try {
      await _iampassPlugin.trainUser(_currentUser!).then((user) {
        // The user has been updated.
        if (user != null) {
          setState(() {
            _currentUser = user;
          });
          showSuccessMessage("trainUser Succeeded");
        }
      });
    } on PlatformException catch (e) {
      showErrorMessage(e.message ?? "trainUser Failed");
    } catch (e) {
      showErrorMessage("trainUser Failed");
    }
  }

  void onUpdateSession() async {
    try {
      await _iampassPlugin
          .updateSession(_currentSession!)
          .then((updatedSession) {
        if (updatedSession != null) {
          setState(() {
            _currentSession = updatedSession;
          });

          showSuccessMessage("Updated Session");
        }
      });
    } catch (updateException) {
      showErrorMessage("Failed to update session.");
    }
  }

  void onDeleteCurrentUser() async {
    bool deleted = await _iampassPlugin.deleteUser(_appUserID);

    if (deleted) {
      showSuccessMessage("User removed");
    } else {
      showErrorMessage("Failed to remove user");
    }

    encryptedSharedPreferences.remove("user");
    setState(() {
      _currentUser = null;
      _appUserID = "";
    });
  }

  Widget homePage() {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Text('User: $_appUserID\n'),
            TextButton(
                onPressed: _currentUser == null ? null : onDeleteCurrentUser,
                child: const Text('Delete User')),
            TextButton(
                onPressed: _currentUser == null ? null : onUpdateUser,
                child: const Text('UpdateUser')),
            TextButton(
                onPressed: _currentUser != null && _currentSession == null
                    ? onAuthenticateUser
                    : null,
                child: const Text('authenticateUser')),
            TextButton(
                onPressed: _currentUser != null && _currentSession == null
                    ? onHandleAuthenticationRequest
                    : null,
                child: const Text('handleAuthenticationRequest')),
            TextButton(
                onPressed: _currentSession == null ? null : onEndSession,
                child: const Text('endSession')),
            TextButton(
                onPressed: _currentSession == null ? null : onUpdateSession,
                child: const Text('Update'))
          ],
        ));
  }

  Widget registerPage() {
    return Scaffold(
        appBar: AppBar(
          title: const Text('IAMPASS Example'),
        ),
        body: Column(
          children: <Widget>[
            FractionallySizedBox(
                widthFactor: 0.75,
                child: TextField(
                  obscureText: false,
                  controller: usernameController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Username',
                  ),
                )),
            TextButton(
                onPressed: _currentUser == null ? onAddUser : null,
                child: const Text('AddUser')),
            TextButton(
                onPressed: _currentUser == null ? onRegisterUser : null,
                child: const Text('RegisterUser')),
            TextButton(
                onPressed: _currentUser == null ? onRegisterDevice : null,
                child: const Text('RegisterDevice')),
            TextButton(
                onPressed:
                    _currentUser == null ? onHandleRegistrationLink : null,
                child: const Text('handleRegistrationLink'))
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: FutureBuilder(
      future: _initFuture,
      builder: (context, snapshot) {
        if (!_hasInitialized) {
          _currentUser = Init.currentUser;
          _appUserID = Init.appUserID;
        }

        if (snapshot.connectionState == ConnectionState.done) {
          if (!_hasInitialized) {
            _currentUser = Init.currentUser;
            _appUserID = Init.appUserID;
            _hasInitialized = true;
          }
          if (_currentUser != null) {
            return homePage();
          } else {
            return registerPage();
          }
        } else {
          return const SplashScreen();
        }
      },
    ));
  }
}