finally the new login is completely working with refresh token as well

This commit is contained in:
Kima 2024-08-16 00:25:46 +02:00
parent f2c8e869b5
commit a673d3f1b3
11 changed files with 406 additions and 322 deletions

View File

@ -67,6 +67,7 @@ Future loginAPI({
address: '1117 Budapest, Gábor Dénes utca 4.', address: '1117 Budapest, Gábor Dénes utca 4.',
), ),
role: Role.parent, role: Role.parent,
refreshToken: '',
); );
if (onLogin != null) onLogin(user); if (onLogin != null) onLogin(user);
@ -130,6 +131,7 @@ Future loginAPI({
password: password, password: password,
instituteCode: instituteCode, instituteCode: instituteCode,
)); ));
if (res != null) { if (res != null) {
if (res.containsKey("error")) { if (res.containsKey("error")) {
if (res["error"] == "invalid_grant") { if (res["error"] == "invalid_grant") {
@ -151,6 +153,7 @@ Future loginAPI({
name: student.name, name: student.name,
student: student, student: student,
role: JwtUtils.getRoleFromJWT(res["access_token"])!, role: JwtUtils.getRoleFromJWT(res["access_token"])!,
refreshToken: '',
); );
if (onLogin != null) onLogin(user); if (onLogin != null) onLogin(user);
@ -209,6 +212,9 @@ Future newLoginAPI({
void Function()? onSuccess, void Function()? onSuccess,
}) async { }) async {
// actual login (token grant) logic // actual login (token grant) logic
Provider.of<KretaClient>(context, listen: false).userAgent =
Provider.of<SettingsProvider>(context, listen: false).config.userAgent;
Map<String, String> headers = { Map<String, String> headers = {
"content-type": "application/x-www-form-urlencoded; charset=UTF-8", "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"accept": "*/*", "accept": "*/*",
@ -216,12 +222,12 @@ Future newLoginAPI({
}; };
Map? res = await Provider.of<KretaClient>(context, listen: false) Map? res = await Provider.of<KretaClient>(context, listen: false)
.postAPI(KretaAPI.login, autoHeader: false, headers: headers, body: { .postAPI(KretaAPI.login, headers: headers, body: {
"code": code, "code": code,
"code_verifier": "DSpuqj_HhDX4wzQIbtn8lr8NLE5wEi1iVLMtMK0jY6c", "code_verifier": "DSpuqj_HhDX4wzQIbtn8lr8NLE5wEi1iVLMtMK0jY6c",
"redirect_uri": "redirect_uri":
"https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect", "https://mobil.e-kreta.hu/ellenorzo-student/prod/oauthredirect",
"client_id": "kreta-ellenorzo-student-mobile-ios", "client_id": KretaAPI.clientId,
"grant_type": "authorization_code", "grant_type": "authorization_code",
}); });
@ -236,13 +242,12 @@ Future newLoginAPI({
return; return;
} }
} else { } else {
// print("MUKODIK GECI");
// print("ACCESS TOKEN: ${res["access_token"]}");
if (res.containsKey("access_token")) { if (res.containsKey("access_token")) {
print(JwtUtils.decodeJwt(res["access_token"]));
try { try {
Provider.of<KretaClient>(context, listen: false).accessToken = Provider.of<KretaClient>(context, listen: false).accessToken =
res["access_token"]; res["access_token"];
Provider.of<KretaClient>(context, listen: false).refreshToken =
res["refresh_token"];
String instituteCode = String instituteCode =
JwtUtils.getInstituteFromJWT(res["access_token"])!; JwtUtils.getInstituteFromJWT(res["access_token"])!;
@ -261,6 +266,7 @@ Future newLoginAPI({
name: student.name, name: student.name,
student: student, student: student,
role: role, role: role,
refreshToken: res["refresh_token"],
); );
if (onLogin != null) onLogin(user); if (onLogin != null) onLogin(user);

View File

@ -81,7 +81,8 @@ class App extends StatelessWidget {
CorePalette? corePalette; CorePalette? corePalette;
final status = StatusProvider(); final status = StatusProvider();
final kreta = KretaClient(user: user, settings: settings, status: status); final kreta = KretaClient(
user: user, settings: settings, database: database, status: status);
final timetable = final timetable =
TimetableProvider(user: user, database: database, kreta: kreta); TimetableProvider(user: user, database: database, kreta: kreta);
final premium = PlusProvider(settings: settings); final premium = PlusProvider(settings: settings);

View File

@ -66,6 +66,7 @@ const usersDB = DatabaseStruct("users", {
"institute_code": String, "student": String, "role": int, "institute_code": String, "student": String, "role": int,
"nickname": String, "picture": String, // premium only (it's now plus btw) "nickname": String, "picture": String, // premium only (it's now plus btw)
"grade_streak": int, "grade_streak": int,
"refresh_token": String,
}); });
const userDataDB = DatabaseStruct("user_data", { const userDataDB = DatabaseStruct("user_data", {
"id": String, "grades": String, "timetable": String, "exams": String, "id": String, "grades": String, "timetable": String, "exams": String,
@ -138,7 +139,8 @@ Future<Database> initDB(DatabaseProvider database) async {
"role": 0, "role": 0,
"nickname": "", "nickname": "",
"picture": "", "picture": "",
"grade_streak": 0 "grade_streak": 0,
"refresh_token": "",
}, },
); );
await migrateDB(db, struct: userDataDB, defaultValues: { await migrateDB(db, struct: userDataDB, defaultValues: {

View File

@ -71,9 +71,11 @@ class NotificationsHelper {
// Refresh kreta login for current user // Refresh kreta login for current user
final status = StatusProvider(); final status = StatusProvider();
KretaClient kretaClientForUser = KretaClient( KretaClient kretaClientForUser = KretaClient(
user: userProviderForUser, user: userProviderForUser,
settings: settingsProvider, settings: settingsProvider,
status: status); database: database,
status: status,
);
await kretaClientForUser.refreshLogin(); await kretaClientForUser.refreshLogin();
// Process notifications for current user // Process notifications for current user

View File

@ -17,6 +17,8 @@ class User {
String nickname; String nickname;
String picture; String picture;
int gradeStreak; int gradeStreak;
// new login method
String refreshToken;
String get displayName => nickname != '' ? nickname : name; String get displayName => nickname != '' ? nickname : name;
bool get hasStreak => gradeStreak > 0; bool get hasStreak => gradeStreak > 0;
@ -32,6 +34,7 @@ class User {
this.nickname = "", this.nickname = "",
this.picture = "", this.picture = "",
this.gradeStreak = 0, this.gradeStreak = 0,
required this.refreshToken,
}) { }) {
if (id != null) { if (id != null) {
this.id = id; this.id = id;
@ -61,6 +64,7 @@ class User {
nickname: map["nickname"] ?? "", nickname: map["nickname"] ?? "",
picture: map["picture"] ?? "", picture: map["picture"] ?? "",
gradeStreak: map["grade_streak"] ?? 0, gradeStreak: map["grade_streak"] ?? 0,
refreshToken: map["refresh_token"] ?? "",
); );
} }
@ -75,6 +79,8 @@ class User {
"role": role.index, "role": role.index,
"nickname": nickname, "nickname": nickname,
"picture": picture, "picture": picture,
"grade_streak": gradeStreak,
"refresh_token": refreshToken,
}; };
} }

View File

@ -5,7 +5,7 @@ class KretaAPI {
static const login = BaseKreta.kretaIdp + KretaApiEndpoints.token; static const login = BaseKreta.kretaIdp + KretaApiEndpoints.token;
static const logout = BaseKreta.kretaIdp + KretaApiEndpoints.revoke; static const logout = BaseKreta.kretaIdp + KretaApiEndpoints.revoke;
static const nonce = BaseKreta.kretaIdp + KretaApiEndpoints.nonce; static const nonce = BaseKreta.kretaIdp + KretaApiEndpoints.nonce;
static const clientId = "kreta-ellenorzo-mobile-android"; static const clientId = "kreta-ellenorzo-student-mobile-ios";
// ELLENORZO API // ELLENORZO API
static String notes(String iss) => static String notes(String iss) =>

View File

@ -1,15 +1,16 @@
// ignore_for_file: avoid_print // ignore_for_file: avoid_print, use_build_context_synchronously
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:refilc/api/login.dart'; // import 'package:refilc/api/login.dart';
import 'package:refilc/api/nonce.dart'; // import 'package:refilc/api/nonce.dart';
import 'package:refilc/api/providers/database_provider.dart';
import 'package:refilc/api/providers/user_provider.dart'; import 'package:refilc/api/providers/user_provider.dart';
import 'package:refilc/api/providers/status_provider.dart'; import 'package:refilc/api/providers/status_provider.dart';
import 'package:refilc/models/settings.dart'; import 'package:refilc/models/settings.dart';
import 'package:refilc/models/user.dart'; import 'package:refilc/models/user.dart';
import 'package:refilc/utils/jwt.dart'; // import 'package:refilc/utils/jwt.dart';
import 'package:refilc_kreta_api/client/api.dart'; import 'package:refilc_kreta_api/client/api.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http; import 'package:http/io_client.dart' as http;
@ -24,6 +25,7 @@ class KretaClient {
late final SettingsProvider _settings; late final SettingsProvider _settings;
late final UserProvider _user; late final UserProvider _user;
late final DatabaseProvider _database;
late final StatusProvider _status; late final StatusProvider _status;
bool _loginRefreshing = false; bool _loginRefreshing = false;
@ -32,9 +34,11 @@ class KretaClient {
this.accessToken, this.accessToken,
required SettingsProvider settings, required SettingsProvider settings,
required UserProvider user, required UserProvider user,
required DatabaseProvider database,
required StatusProvider status, required StatusProvider status,
}) : _settings = settings, }) : _settings = settings,
_user = user, _user = user,
_database = database,
_status = status, _status = status,
userAgent = settings.config.userAgent { userAgent = settings.config.userAgent {
var ioclient = HttpClient(); var ioclient = HttpClient();
@ -212,7 +216,7 @@ class KretaClient {
res = await request.send(); res = await request.send();
if (res.statusCode == 401) { if (res.statusCode == 401) {
headerMap.remove("authorization"); headerMap.remove("authorization");
await refreshLogin(); await refreshLogin();
} else { } else {
break; break;
@ -232,65 +236,74 @@ class KretaClient {
} }
} }
Future<void> refreshLogin() async { Future<String?> refreshLogin() async {
if (_loginRefreshing) return; if (_loginRefreshing) return null;
_loginRefreshing = true; _loginRefreshing = true;
User? loginUser = _user.user; User? loginUser = _user.user;
if (loginUser == null) return; if (loginUser == null) return null;
Map<String, String> headers = { Map<String, String> headers = {
"content-type": "application/x-www-form-urlencoded", "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"accept": "*/*",
"user-agent": "eKretaStudent/264745 CFNetwork/1494.0.7 Darwin/23.4.0",
}; };
String nonceStr = await getAPI(KretaAPI.nonce, json: false);
Nonce nonce =
getNonce(nonceStr, loginUser.username, loginUser.instituteCode);
headers.addAll(nonce.header());
if (_settings.presentationMode) { if (_settings.presentationMode) {
print("DEBUG: refreshLogin: ${loginUser.id}"); print("DEBUG: refreshLogin: ${loginUser.id}");
} else { } else {
print("DEBUG: refreshLogin: ${loginUser.id} ${loginUser.name}"); print("DEBUG: refreshLogin: ${loginUser.id} ${loginUser.name}");
} }
Map? loginRes = await postAPI( refreshToken ??= loginUser.refreshToken;
KretaAPI.login,
headers: headers,
body: User.loginBody(
username: loginUser.username,
password: loginUser.password,
instituteCode: loginUser.instituteCode,
),
);
if (loginRes != null) { print("REFRESH TOKEN BELOW");
if (loginRes.containsKey("access_token")) { print(refreshToken);
accessToken = loginRes["access_token"];
}
if (loginRes.containsKey("refresh_token")) {
refreshToken = loginRes["refresh_token"];
}
// Update role
loginUser.role =
JwtUtils.getRoleFromJWT(accessToken ?? "") ?? Role.student;
}
if (refreshToken != null) { if (refreshToken != null) {
Map? refreshRes = await postAPI(KretaAPI.login, print("REFRESHING LOGIN");
Map? res = await postAPI(KretaAPI.login,
headers: headers, headers: headers,
body: User.refreshBody( body: User.refreshBody(
refreshToken: refreshToken!, refreshToken: loginUser.refreshToken,
instituteCode: loginUser.instituteCode)); instituteCode: loginUser.instituteCode,
if (refreshRes != null) { ));
if (refreshRes.containsKey("id_token")) { print("REFRESH RESPONSE BELOW");
idToken = refreshRes["id_token"]; print(res);
if (res != null) {
if (res.containsKey("error")) {
// remove user if refresh token expired
if (res["error"] == "invalid_grant") {
// remove user from app
_user.removeUser(loginUser.id);
await _database.store.removeUser(loginUser.id);
// return error
return "refresh_token_expired";
}
} }
if (res.containsKey("access_token")) {
accessToken = res["access_token"];
}
if (res.containsKey("refresh_token")) {
refreshToken = res["refresh_token"];
loginUser.refreshToken = res["refresh_token"];
_database.store.storeUser(loginUser);
_user.refresh();
}
if (res.containsKey("id_token")) {
idToken = res["id_token"];
}
_loginRefreshing = false;
} else {
_loginRefreshing = false;
} }
} else {
_loginRefreshing = false;
} }
_loginRefreshing = false; return null;
} }
Future<void> logout() async { Future<void> logout() async {

View File

@ -48,10 +48,6 @@ class _KretenLoginScreenState extends State<KretenLoginScreen> {
String code = requiredThings[0]; String code = requiredThings[0];
// String sessionState = requiredThings[1]; // String sessionState = requiredThings[1];
debugPrint('url: $url');
print(code);
widget.onLogin(code); widget.onLogin(code);
// Future.delayed(const Duration(milliseconds: 500), () { // Future.delayed(const Duration(milliseconds: 500), () {
// Navigator.of(context).pop(); // Navigator.of(context).pop();

View File

@ -341,59 +341,60 @@ class LoginScreenState extends State<LoginScreen> {
); );
} }
void _loginAPI({required BuildContext context}) { // void _loginAPI({required BuildContext context}) {
String username = usernameController.text; // String username = usernameController.text;
String password = passwordController.text; // String password = passwordController.text;
tempUsername = username; // tempUsername = username;
if (username == "" || // if (username == "" ||
password == "" || // password == "" ||
schoolController.selectedSchool == null) { // schoolController.selectedSchool == null) {
return setState(() => _loginState = LoginState.missingFields); // return setState(() => _loginState = LoginState.missingFields);
} // }
// ignore: no_leading_underscores_for_local_identifiers // // ignore: no_leading_underscores_for_local_identifiers
void _callAPI() { // void _callAPI() {
loginAPI( // loginAPI(
username: username, // username: username,
password: password, // password: password,
instituteCode: schoolController.selectedSchool!.instituteCode, // instituteCode: schoolController.selectedSchool!.instituteCode,
context: context, // context: context,
onLogin: (user) { // onLogin: (user) {
ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar( // ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar(
context: context, // context: context,
brightness: Brightness.light, // brightness: Brightness.light,
content: Text("welcome".i18n.fill([user.name]), // content: Text("welcome".i18n.fill([user.name]),
overflow: TextOverflow.ellipsis), // overflow: TextOverflow.ellipsis),
)); // ));
}, // },
onSuccess: () { // onSuccess: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar(); // ScaffoldMessenger.of(context).hideCurrentSnackBar();
setSystemChrome(context); // setSystemChrome(context);
Navigator.of(context).pushReplacementNamed("login_to_navigation"); // Navigator.of(context).pushReplacementNamed("login_to_navigation");
}).then( // }).then(
(res) => setState(() { // (res) => setState(() {
// if (res == LoginState.invalidGrant && // // if (res == LoginState.invalidGrant &&
// tempUsername.replaceAll(username, '').length <= 3) { // // tempUsername.replaceAll(username, '').length <= 3) {
// tempUsername = username + ' '; // // tempUsername = username + ' ';
// Timer( // // Timer(
// const Duration(milliseconds: 500), // // const Duration(milliseconds: 500),
// () => _loginAPI(context: context), // // () => _loginAPI(context: context),
// ); // // );
// // _loginAPI(context: context); // // // _loginAPI(context: context);
// } else { // // } else {
_loginState = res; // _loginState = res;
// } // // }
}), // }),
); // );
} // }
setState(() => _loginState = LoginState.inProgress); // setState(() => _loginState = LoginState.inProgress);
_callAPI(); // _callAPI();
} // }
// new login api // new login api
// ignore: non_constant_identifier_names
void _NewLoginAPI({required BuildContext context}) { void _NewLoginAPI({required BuildContext context}) {
String code = codeController.text; String code = codeController.text;

View File

@ -1,10 +1,13 @@
// import 'dart:async'; // import 'dart:async';
import 'package:refilc/api/client.dart';
import 'package:refilc/api/login.dart'; import 'package:refilc/api/login.dart';
import 'package:refilc/theme/colors/colors.dart'; import 'package:refilc/theme/colors/colors.dart';
import 'package:refilc_mobile_ui/common/custom_snack_bar.dart'; import 'package:refilc_mobile_ui/common/custom_snack_bar.dart';
import 'package:refilc_mobile_ui/common/system_chrome.dart'; import 'package:refilc_mobile_ui/common/system_chrome.dart';
import 'package:refilc_mobile_ui/screens/login/kreten_login.dart'; // import 'package:refilc_mobile_ui/screens/login/kreten_login.dart';
import 'package:refilc_mobile_ui/screens/login/login_button.dart';
import 'package:refilc_mobile_ui/screens/login/login_input.dart';
import 'package:refilc_mobile_ui/screens/login/school_input/school_input.dart'; import 'package:refilc_mobile_ui/screens/login/school_input/school_input.dart';
import 'package:refilc_mobile_ui/screens/settings/privacy_view.dart'; import 'package:refilc_mobile_ui/screens/settings/privacy_view.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -58,20 +61,20 @@ class LoginScreenState extends State<LoginScreen> {
systemNavigationBarIconBrightness: Brightness.dark, systemNavigationBarIconBrightness: Brightness.dark,
)); ));
// FilcAPI.getSchools().then((schools) { FilcAPI.getSchools().then((schools) {
// if (schools != null) { if (schools != null) {
// schoolController.update(() { schoolController.update(() {
// schoolController.schools = schools; schoolController.schools = schools;
// }); });
// } else { } else {
// ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar( ScaffoldMessenger.of(context).showSnackBar(CustomSnackBar(
// content: Text("schools_error".i18n, content: Text("schools_error".i18n,
// style: const TextStyle(color: Colors.white)), style: const TextStyle(color: Colors.white)),
// backgroundColor: AppColors.of(context).red, backgroundColor: AppColors.of(context).red,
// context: context, context: context,
// )); ));
// } }
// }); });
} }
@override @override
@ -150,217 +153,217 @@ class LoginScreenState extends State<LoginScreen> {
), ),
// kreten login button // kreten login button
GestureDetector( // GestureDetector(
onTap: () { // onTap: () {
final NavigatorState navigator = Navigator.of(context); // final NavigatorState navigator = Navigator.of(context);
navigator // navigator
.push( // .push(
MaterialPageRoute( // MaterialPageRoute(
builder: (context) => KretenLoginScreen( // builder: (context) => KretenLoginScreen(
onLogin: (String code) { // onLogin: (String code) {
codeController.text = code; // codeController.text = code;
navigator.pop(); // navigator.pop();
}, // },
),
),
)
.then((value) {
if (codeController.text != "") {
_NewLoginAPI(context: context);
}
});
},
child: Container(
width: MediaQuery.of(context).size.width * 0.75,
height: 50.0,
decoration: BoxDecoration(
// image: const DecorationImage(
// image:
// AssetImage('assets/images/btn_kreten_login.png'),
// fit: BoxFit.scaleDown,
// ),
borderRadius: BorderRadius.circular(12.0),
color: const Color(0xFF0097C1),
),
padding: const EdgeInsets.only(
top: 5.0, left: 5.0, right: 5.0, bottom: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/images/btn_kreten_login.png',
),
const SizedBox(
width: 10.0,
),
Container(
width: 1.0,
height: 30.0,
color: Colors.white,
),
const SizedBox(
width: 10.0,
),
Text(
'login_w_kreta_acc'.i18n,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
),
],
)),
),
const Spacer(
flex: 1,
),
// inputs
// Padding(
// padding: const EdgeInsets.only(
// left: 22.0,
// right: 22.0,
// top: 0.0,
// ),
// child: AutofillGroup(
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// // username
// Padding(
// padding: const EdgeInsets.only(bottom: 6.0),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Expanded(
// child: Text(
// "username".i18n,
// maxLines: 1,
// style: TextStyle(
// color: AppColors.of(context).loginPrimary,
// fontWeight: FontWeight.w500,
// fontSize: 12.0,
// ),
// ),
// ),
// Expanded(
// child: Text(
// "usernameHint".i18n,
// maxLines: 1,
// textAlign: TextAlign.right,
// style: TextStyle(
// color:
// AppColors.of(context).loginSecondary,
// fontWeight: FontWeight.w500,
// fontSize: 12.0,
// ),
// ),
// ),
// ],
// ),
// ), // ),
// Padding( // ),
// padding: const EdgeInsets.only(bottom: 12.0), // )
// child: LoginInput( // .then((value) {
// style: LoginInputStyle.username, // if (codeController.text != "") {
// controller: usernameController, // _NewLoginAPI(context: context);
// }
// });
// },
// child: Container(
// width: MediaQuery.of(context).size.width * 0.75,
// height: 50.0,
// decoration: BoxDecoration(
// // image: const DecorationImage(
// // image:
// // AssetImage('assets/images/btn_kreten_login.png'),
// // fit: BoxFit.scaleDown,
// // ),
// borderRadius: BorderRadius.circular(12.0),
// color: const Color(0xFF0097C1),
// ),
// padding: const EdgeInsets.only(
// top: 5.0, left: 5.0, right: 5.0, bottom: 5.0),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// Image.asset(
// 'assets/images/btn_kreten_login.png',
// ), // ),
// ), // const SizedBox(
// width: 10.0,
// // password
// Padding(
// padding: const EdgeInsets.only(bottom: 6.0),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Expanded(
// child: Text(
// "password".i18n,
// maxLines: 1,
// style: TextStyle(
// color: AppColors.of(context).loginPrimary,
// fontWeight: FontWeight.w500,
// fontSize: 12.0,
// ),
// ),
// ),
// Expanded(
// child: Text(
// "passwordHint".i18n,
// maxLines: 1,
// textAlign: TextAlign.right,
// style: TextStyle(
// color:
// AppColors.of(context).loginSecondary,
// fontWeight: FontWeight.w500,
// fontSize: 12.0,
// ),
// ),
// ),
// ],
// ), // ),
// ), // Container(
// Padding( // width: 1.0,
// padding: const EdgeInsets.only(bottom: 12.0), // height: 30.0,
// child: LoginInput( // color: Colors.white,
// style: LoginInputStyle.password,
// controller: passwordController,
// ), // ),
// ), // const SizedBox(
// width: 10.0,
// // school // ),
// Padding( // Text(
// padding: const EdgeInsets.only(bottom: 6.0), // 'login_w_kreta_acc'.i18n,
// child: Text( // textAlign: TextAlign.center,
// "school".i18n, // style: const TextStyle(
// maxLines: 1, // color: Colors.white,
// style: TextStyle( // fontWeight: FontWeight.bold,
// color: AppColors.of(context).loginPrimary, // fontSize: 15.0,
// fontWeight: FontWeight.w500,
// fontSize: 12.0,
// ), // ),
// ), // ),
// ), // ],
// SchoolInput( // )),
// scroll: _scrollController,
// controller: schoolController,
// ),
// ],
// ),
// ),
// ), // ),
// login button // const Spacer(
// Padding( // flex: 1,
// padding: const EdgeInsets.only(
// top: 35.0,
// left: 22.0,
// right: 22.0,
// ),
// child: Visibility(
// visible: _loginState != LoginState.inProgress,
// replacement: const Padding(
// padding: EdgeInsets.symmetric(vertical: 6.0),
// child: CircularProgressIndicator(
// valueColor:
// AlwaysStoppedAnimation<Color>(Colors.white),
// ),
// ),
// child: LoginButton(
// child: Text("login".i18n,
// maxLines: 1,
// style: const TextStyle(
// fontWeight: FontWeight.bold,
// fontSize: 20.0,
// )),
// onPressed: () => _loginAPI(context: context),
// ),
// ),
// ), // ),
// inputs
Padding(
padding: const EdgeInsets.only(
left: 22.0,
right: 22.0,
top: 0.0,
),
child: AutofillGroup(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// username
Padding(
padding: const EdgeInsets.only(bottom: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
"username".i18n,
maxLines: 1,
style: TextStyle(
color: AppColors.of(context).loginPrimary,
fontWeight: FontWeight.w500,
fontSize: 12.0,
),
),
),
Expanded(
child: Text(
"usernameHint".i18n,
maxLines: 1,
textAlign: TextAlign.right,
style: TextStyle(
color:
AppColors.of(context).loginSecondary,
fontWeight: FontWeight.w500,
fontSize: 12.0,
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 12.0),
child: LoginInput(
style: LoginInputStyle.username,
controller: usernameController,
),
),
// password
Padding(
padding: const EdgeInsets.only(bottom: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
"password".i18n,
maxLines: 1,
style: TextStyle(
color: AppColors.of(context).loginPrimary,
fontWeight: FontWeight.w500,
fontSize: 12.0,
),
),
),
Expanded(
child: Text(
"passwordHint".i18n,
maxLines: 1,
textAlign: TextAlign.right,
style: TextStyle(
color:
AppColors.of(context).loginSecondary,
fontWeight: FontWeight.w500,
fontSize: 12.0,
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(bottom: 12.0),
child: LoginInput(
style: LoginInputStyle.password,
controller: passwordController,
),
),
// school
Padding(
padding: const EdgeInsets.only(bottom: 6.0),
child: Text(
"school".i18n,
maxLines: 1,
style: TextStyle(
color: AppColors.of(context).loginPrimary,
fontWeight: FontWeight.w500,
fontSize: 12.0,
),
),
),
SchoolInput(
scroll: _scrollController,
controller: schoolController,
),
],
),
),
),
// login button
Padding(
padding: const EdgeInsets.only(
top: 35.0,
left: 22.0,
right: 22.0,
),
child: Visibility(
visible: _loginState != LoginState.inProgress,
replacement: const Padding(
padding: EdgeInsets.symmetric(vertical: 6.0),
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white),
),
),
child: LoginButton(
child: Text("login".i18n,
maxLines: 1,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
)),
onPressed: () => _loginAPI(context: context),
),
),
),
// error messages // error messages
if (_loginState == LoginState.missingFields || if (_loginState == LoginState.missingFields ||
_loginState == LoginState.invalidGrant || _loginState == LoginState.invalidGrant ||
@ -410,6 +413,7 @@ class LoginScreenState extends State<LoginScreen> {
} }
// new login api // new login api
// ignore: non_constant_identifier_names, unused_element
void _NewLoginAPI({required BuildContext context}) { void _NewLoginAPI({required BuildContext context}) {
String code = codeController.text; String code = codeController.text;

View File

@ -30,6 +30,7 @@ import 'package:refilc_mobile_ui/common/profile_image/profile_image.dart';
import 'package:refilc_mobile_ui/common/soon_alert/soon_alert.dart'; import 'package:refilc_mobile_ui/common/soon_alert/soon_alert.dart';
// import 'package:refilc_mobile_ui/common/soon_alert/soon_alert.dart'; // import 'package:refilc_mobile_ui/common/soon_alert/soon_alert.dart';
import 'package:refilc_mobile_ui/common/splitted_panel/splitted_panel.dart'; import 'package:refilc_mobile_ui/common/splitted_panel/splitted_panel.dart';
import 'package:refilc_mobile_ui/common/system_chrome.dart';
// import 'package:refilc_mobile_ui/common/system_chrome.dart'; // import 'package:refilc_mobile_ui/common/system_chrome.dart';
import 'package:refilc_mobile_ui/common/widgets/update/updates_view.dart'; import 'package:refilc_mobile_ui/common/widgets/update/updates_view.dart';
import 'package:refilc_mobile_ui/screens/news/news_screen.dart'; import 'package:refilc_mobile_ui/screens/news/news_screen.dart';
@ -105,9 +106,11 @@ class SettingsScreenState extends State<SettingsScreen>
Provider.of<NoteProvider>(context, listen: false).restore(), Provider.of<NoteProvider>(context, listen: false).restore(),
Provider.of<EventProvider>(context, listen: false).restore(), Provider.of<EventProvider>(context, listen: false).restore(),
Provider.of<AbsenceProvider>(context, listen: false).restore(), Provider.of<AbsenceProvider>(context, listen: false).restore(),
Provider.of<KretaClient>(context, listen: false).refreshLogin(),
]); ]);
Future<String?> refresh() =>
Provider.of<KretaClient>(context, listen: false).refreshLogin();
void buildAccountTiles() { void buildAccountTiles() {
accountTiles = []; accountTiles = [];
user.getUsers().forEach((account) { user.getUsers().forEach((account) {
@ -143,8 +146,58 @@ class SettingsScreenState extends State<SettingsScreen>
//? ColorUtils.stringToColor(account.name) //? ColorUtils.stringToColor(account.name)
//: Theme.of(context).colorScheme.secondary, //: Theme.of(context).colorScheme.secondary,
), ),
onTap: () { onTap: () async {
user.setUser(account.id); user.setUser(account.id);
// check if refresh token is still valid
String? err = await refresh();
if (err != null) {
showDialog(
context: context,
builder: (_) => AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0)),
title: Text('oopsie'.i18n),
content: Text('session_expired'.i18n),
actions: [
ActionButton(
label: "Ok",
onTap: () async {
String? userId = user.id;
if (userId == null) return;
// delete user
user.removeUser(userId);
await Provider.of<DatabaseProvider>(context,
listen: false)
.store
.removeUser(userId);
// if no users, show login, else login with back button
if (user.getUsers().isNotEmpty) {
user.setUser(user.getUsers().first.id);
restore().then(
(_) => user.setUser(user.getUsers().first.id));
Navigator.of(context).pop();
Navigator.of(context)
.pushNamed("login_back")
.then((value) {
setSystemChrome(context);
});
} else {
Navigator.of(context).pop();
Navigator.of(context)
.pushNamedAndRemoveUntil("login", (_) => false);
}
})
],
),
);
return;
}
// switch user
restore().then((_) => user.setUser(account.id)); restore().then((_) => user.setUser(account.id));
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },