Siopas Inventory PETI for ISTW Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

146 lines
3.2 KiB

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user_model.dart';
import '../services/auth_service.dart';
class AuthProvider with ChangeNotifier {
UserModel? _user = UserModel();
AuthService _userService = AuthService();
String? _token;
String? get token => _token;
UserModel get user => _user!;
set user(UserModel user) {
_user = user;
notifyListeners();
}
Future<bool> autoLogin() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? token = prefs.getString('token');
if (token != null) {
try {
UserModel? user = await _userService.getUserInfoFromServer(token);
if (user != null) {
print('TOKEN ditemukan(Success): $token');
_user = user;
return true;
} else {
print('TOKEN tidak ditemukan(Failed): $token');
return false;
}
} catch (e) {
print(e);
return false;
}
}
return false;
}
FutureOr<bool> register({
String? name,
String? email,
String? password,
}) async {
try {
UserModel user = await AuthService().register(
name: name!,
email: email!,
password: password!,
);
_user = user;
return true;
} catch (e) {
print(e);
return false;
}
}
// FutureOr<UserModel> login({
// String? email,
// String? password,
// }) async {
// try {
// UserModel user = await AuthService().login(
// email: email!,
// password: password!,
// );
// // SharedPreferences prefs = await SharedPreferences.getInstance();
// // prefs.setString('token', user.token!);
// _user = user;
// return user;
// } catch (e) {
// print(e);
// throw Exception('Failed to login');
// }
// }
Future<bool> login({
String? email,
String? password,
// String? roles,
}) async {
try {
UserModel user = await AuthService().login(
email: email!,
password: password!,
);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('token', user.token!);
_user = user;
return true;
} catch (e) {
print(e);
return false;
}
}
FutureOr<bool> logout(String token) async {
try {
if (await AuthService().logout(token)) {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('token');
await prefs.remove('email');
await prefs.remove('password');
await prefs.clear();
notifyListeners();
return true;
} else {
return false;
}
} catch (e) {
print(e);
return false;
}
}
FutureOr<bool> updateProfile({
String? name,
String? username,
String? token,
}) async {
try {
UserModel user = await AuthService().updateProfile(
name: name!,
username: username!,
token: token!,
);
_user = user;
print('Success Update Profile Provider');
return true;
} catch (e) {
print(e);
return false;
}
}
}