login.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import 'package:dio/dio.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:provider/provider.dart';
  4. import 'package:e2ee_chat/common/global.dart';
  5. import 'package:e2ee_chat/common/api.dart';
  6. import '../model/user.dart';
  7. import 'profile.dart';
  8. class LoginModel extends ProfileChangeNotifier {
  9. // TODO: online keep status; A logout, B logout?
  10. bool get isLogin => profile.isLogin;
  11. User? get user => profile.user;
  12. Future<bool> login({String? username, String? password}) async {
  13. debug('UserModel login begin');
  14. if (username != null) {
  15. profile.user = User(username);
  16. }
  17. bool _result = false;
  18. String? token = await profile.token;
  19. if (profile.username != null && (password != null || token != null)) {
  20. String? _token;
  21. try {
  22. _token = await Api().login(username: profile.username!, password: password, token: token);
  23. _result = _token != null;
  24. } on DioError catch(e) {
  25. print(e);
  26. }
  27. profile.setToken(_token);
  28. debug('UserModel login get token: ${await profile.token}');
  29. if (await profile.token != null) {
  30. debug('UserModel login success!');
  31. profile.isLogin = true;
  32. profile.isLogout = false;
  33. notifyListeners();
  34. }
  35. }
  36. debug('UserModel login end');
  37. return _result;
  38. }
  39. Future<void> logout() async {
  40. if (profile.isLogin && await Api().logout()) {
  41. profile.isLogin = false;
  42. profile.isLogout = true;
  43. notifyListeners();
  44. }
  45. }
  46. Future<bool> loginOrRegister(String username, String password) async {
  47. if (await login(username: username, password: password)) {
  48. return true;
  49. } else if (await Api().register(username, password)) {
  50. return await login(username: username, password: password);
  51. }
  52. return false;
  53. }
  54. }