import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:e2ee_chat/common/global.dart'; import 'package:e2ee_chat/common/api.dart'; import '../model/user.dart'; import 'profile.dart'; class LoginModel extends ProfileChangeNotifier { // TODO: online keep status; A logout, B logout? bool get isLogin => profile.isLogin; User? get user => profile.user; Future login({String? username, String? password}) async { debug('UserModel login begin'); if (username != null) { profile.user = User(username); } bool _result = false; String? token = await profile.token; if (profile.username != null && (password != null || token != null)) { String? _token; try { _token = await Api().login(username: profile.username!, password: password, token: token); _result = _token != null; } on DioError catch(e) { print(e); } profile.setToken(_token); debug('UserModel login get token: ${await profile.token}'); if (await profile.token != null) { debug('UserModel login success!'); profile.isLogin = true; profile.isLogout = false; notifyListeners(); } } debug('UserModel login end'); return _result; } Future logout() async { if (profile.isLogin && await Api().logout()) { profile.isLogin = false; profile.isLogout = true; notifyListeners(); } } Future loginOrRegister(String username, String password) async { if (await login(username: username, password: password)) { return true; } else if (await Api().register(username, password)) { return await login(username: username, password: password); } return false; } }