/* * This file is part of wger Workout Manager . * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:http/http.dart' as http; import 'package:logging/logging.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:version/version.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/shared_preferences.dart'; import 'helpers.dart'; enum LoginActions { update, proceed, } enum AuthState { updateRequired, serverUpdateRequired, loggedIn, loggedOut, } class AuthProvider with ChangeNotifier { final _logger = Logger('AuthProvider'); String? token; String? serverUrl; String? serverVersion; PackageInfo? applicationVersion; Map metadata = {}; AuthState state = AuthState.loggedOut; bool _serverConfigWarning = false; bool get serverConfigWarning => _serverConfigWarning; static const MIN_APP_VERSION_URL = 'min-app-version'; static const SERVER_VERSION_URL = 'version'; static const REGISTRATION_URL = 'register'; static const LOGIN_URL = 'login'; static const USERPROFILE_URL = 'userprofile'; late http.Client client; AuthProvider([http.Client? client]) { this.client = client ?? http.Client(); } /// Clear the server config warnings void clearServerConfigWarning() { _serverConfigWarning = false; notifyListeners(); } /// flag to indicate that the application has successfully loaded all initial data bool dataInit = false; bool get isAuth { return token != null; } /// Server application version Future setServerVersion() async { final response = await client.get(makeUri(serverUrl!, SERVER_VERSION_URL)); serverVersion = json.decode(response.body); } /// (flutter) Application version Future setApplicationVersion() async { applicationVersion = await PackageInfo.fromPlatform(); } Future initVersions(String serverUrl) async { this.serverUrl = serverUrl; await setApplicationVersion(); await setServerVersion(); } /// Checking if there is a new version of the application. Future applicationUpdateRequired([String? version]) async { final applicationCurrentVersion = version ?? applicationVersion!.version; final response = await client.get(makeUri(serverUrl!, MIN_APP_VERSION_URL)); final currentVersion = Version.parse(applicationCurrentVersion); final requiredAppVersion = Version.parse(jsonDecode(response.body)); final needUpdate = requiredAppVersion > currentVersion; if (needUpdate) { _logger.fine('Application update required: $requiredAppVersion > $currentVersion'); } return needUpdate; } /// Checks whether the connected server meets the minimum version required /// by this build of the app. /// /// [version] overrides [serverVersion] and is intended for unit testing. bool serverUpdateRequired([String? version]) { final rawVersion = version ?? serverVersion; if (rawVersion == null) { // If we couldn't read the server version, allow the login to proceed // so as not to lock out users on unexpected server configurations. _logger.warning('serverUpdateRequired: serverVersion is null, skipping check'); return false; } // Strip common non-semver suffixes emitted by Python/Django backends, // e.g. '2.5.0a2' → '2.5.0', '2.3.0 (git-abc1234)' → '2.3.0'. final sanitized = rawVersion .replaceFirst(RegExp(r'\s.*$'), '') // strip trailing space + anything after .replaceFirst(RegExp(r'[a-zA-Z].*$'), ''); // strip alpha/beta/rc suffix final Version current; try { current = Version.parse(sanitized); } on FormatException { // Completely unparseable version string — be lenient and allow login. _logger.warning( 'serverUpdateRequired: could not parse server version "$rawVersion" ' '(sanitized: "$sanitized"), skipping check', ); return false; } final required = Version.parse(MIN_SERVER_VERSION); final needUpdate = current < required; if (needUpdate) { _logger.fine('Server update required: server $current < minimum $required'); } return needUpdate; } /// Detects reverse-proxy misconfiguration on the server by checking that /// pagination URLs returned by the API point to the same host and scheme as /// the configured [serverUrl]. /// /// Returns `true` when the configuration looks fine (or the check could not /// be completed conclusively), `false` when a mismatch is detected. Future serverConfigSane() async { try { final baseUri = Uri.parse(serverUrl!); final response = await client.get( Uri.parse('$serverUrl/api/v2/exercise/?limit=1'), headers: { HttpHeaders.authorizationHeader: 'Token $token', HttpHeaders.acceptHeader: 'application/json', }, ); if (response.statusCode != 200) { return true; } final data = jsonDecode(response.body) as Map; final nextUrl = data['next'] as String?; if (nextUrl == null) { return true; } final nextUri = Uri.parse(nextUrl); return nextUri.host.toLowerCase() == baseUri.host.toLowerCase() && nextUri.scheme == baseUri.scheme; } catch (e) { _logger.info('serverConfigSane check failed: $e'); return true; } } /// Registers a new user Future register({ required String username, required String password, required String email, required String serverUrl, String locale = 'en', }) async { // Register final Map data = { 'username': username, 'password': password, }; if (email != '') { data['email'] = email; } final response = await client.post( makeUri(serverUrl, REGISTRATION_URL), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(), HttpHeaders.acceptLanguageHeader: locale, }, body: json.encode(data), ); if (response.statusCode >= 400) { throw WgerHttpException(response); } return login(username, password, serverUrl, null); } /// Authenticates a user Future login( String username, String password, String serverUrl, String? apiToken, ) async { await logout(shouldNotify: false); _serverConfigWarning = false; // Login using the API token if (apiToken != null && apiToken.isNotEmpty) { final response = await client.get( makeUri(serverUrl, USERPROFILE_URL), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(), HttpHeaders.authorizationHeader: 'Token $apiToken', }, ); if (response.statusCode >= 400) { throw WgerHttpException(response); } token = apiToken; // Login using password } else { final response = await client.post( makeUri(serverUrl, LOGIN_URL), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8', HttpHeaders.userAgentHeader: getAppNameHeader(), }, body: json.encode({'username': username, 'password': password}), ); if (response.statusCode >= 400) { throw WgerHttpException(response); } final responseData = json.decode(response.body); token = responseData['token']; } await initVersions(serverUrl); // If the server is too old for this app version, surface the dedicated // screen so the user knows what to do (ask their server admin to upgrade). if (serverUpdateRequired()) { state = AuthState.serverUpdateRequired; return LoginActions.update; } // If app update is required don't log in user if (await applicationUpdateRequired()) { state = AuthState.updateRequired; return LoginActions.update; } // Surface a warning to the user when the server's reverse proxy is // misconfigured (pagination URLs pointing to the wrong host). if (!await serverConfigSane()) { _serverConfigWarning = true; notifyListeners(); } // Log user in state = AuthState.loggedIn; notifyListeners(); // store login data in shared preferences final prefs = PreferenceHelper.asyncPref; final userData = json.encode({ 'token': token, 'serverUrl': this.serverUrl, }); final serverData = json.encode({'serverUrl': this.serverUrl}); prefs.setString(PREFS_USER, userData); prefs.setString(PREFS_LAST_SERVER, serverData); return LoginActions.proceed; } /// Loads the last server URL from which the user successfully logged in Future getServerUrlFromPrefs() async { final prefs = PreferenceHelper.asyncPref; if (!(await prefs.containsKey(PREFS_LAST_SERVER))) { return DEFAULT_SERVER_PROD; } final userData = json.decode((await prefs.getString(PREFS_LAST_SERVER))!); return userData['serverUrl'] as String; } /// Tries to auto-login the user with the stored token Future tryAutoLogin() async { final prefs = PreferenceHelper.asyncPref; if (!(await prefs.containsKey(PREFS_USER))) { _logger.info('autologin failed, no saved user data'); state = AuthState.loggedOut; return; } final userData = json.decode((await prefs.getString(PREFS_USER))!); if (!userData.containsKey('token') || !userData.containsKey('serverUrl')) { _logger.info('autologin failed, no token or serverUrl'); state = AuthState.loggedOut; return; } token = userData['token']; serverUrl = userData['serverUrl']; if (token == null || serverUrl == null) { _logger.info('autologin failed, token or serverUrl is null'); state = AuthState.loggedOut; return; } // // Try to talk to a URL using the token, if this doesn't work, log out final response = await client.head( makeUri(serverUrl!, 'routine'), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(), HttpHeaders.authorizationHeader: 'Token $token', }, ); if (response.statusCode != 200) { _logger.info('autologin failed, statusCode: ${response.statusCode}'); await logout(); return; } await initVersions(serverUrl!); // If the server is too old for this app version, surface the dedicated // screen so the user knows what to do (ask their server admin to upgrade). if (serverUpdateRequired()) { state = AuthState.serverUpdateRequired; notifyListeners(); return; } // If app update is required don't log in user if (await applicationUpdateRequired()) { state = AuthState.updateRequired; } else { state = AuthState.loggedIn; _logger.info('autologin successful'); } notifyListeners(); } Future logout({bool shouldNotify = true}) async { _logger.fine('logging out'); token = null; serverUrl = null; dataInit = false; state = AuthState.loggedOut; if (shouldNotify) { notifyListeners(); } final prefs = PreferenceHelper.asyncPref; prefs.remove(PREFS_USER); } /// Returns the application name and version /// /// This is used in the headers when talking to the API String getAppNameHeader() { String out = ''; if (applicationVersion != null) { out = '/${applicationVersion!.version} ' '(${applicationVersion!.packageName}; ' 'build: ${applicationVersion!.buildNumber}; ' 'platform: ${Platform.operatingSystem})' ' - https://github.com/wger-project'; } return 'wger App$out'; } }