Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Adds ability to use API Key to "sign in" #708

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@
"@invalidUsername": {
"description": "Error message when the user enters an invalid username"
},
"apitoken": "API Key",
"@apitoken": {},
"invalidApitoken": "Please enter a valid API key",
"@invalidApitoken": {
"description": "Error message when the user enters an invalid API key"
},
"apitokenValidChars": "A API key may only contain valid hex, a-f and 0-9 and should be 40 characters long",
"@apitokenValidChars": {
"description": "Error message when the user tries to input a API key with forbidden characters"
},
"customServerUrl": "URL of the wger instance",
"@customServerUrl": {
"description": "Label in the form where the users can enter their own wger instance"
Expand Down
50 changes: 36 additions & 14 deletions lib/providers/auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class AuthProvider with ChangeNotifier {
static const SERVER_VERSION_URL = 'version';
static const REGISTRATION_URL = 'register';
static const LOGIN_URL = 'login';
static const TEST_URL = 'userprofile';

late http.Client client;

Expand Down Expand Up @@ -129,29 +130,51 @@ class AuthProvider with ChangeNotifier {
throw WgerHttpException(response.body);
}

return login(username, password, serverUrl);
return login(username, password, serverUrl, null);
}

/// Authenticates a user
Future<Map<String, LoginActions>> login(
String username,
String password,
String serverUrl,
String? apiToken,
) async {
await logout(shouldNotify: false);

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}),
);
final responseData = json.decode(response.body);

if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
String token;

if (apiToken != null) {
final response = await client.get(
makeUri(serverUrl, TEST_URL),
headers: {
HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
HttpHeaders.userAgentHeader: getAppNameHeader(),
HttpHeaders.authorizationHeader: 'Token ${apiToken}',
},
);

if (response.statusCode != 200) {
throw WgerHttpException(response.body);
}

token = apiToken;
} 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}),
);
final responseData = json.decode(response.body);

if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}

token = responseData['token'];
}

await initVersions(serverUrl);
Expand All @@ -162,7 +185,6 @@ class AuthProvider with ChangeNotifier {
}

// Log user in
token = responseData['token'];
notifyListeners();

// store login data in shared preferences
Expand Down
65 changes: 65 additions & 0 deletions lib/screens/auth_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ class _AuthCardState extends State<AuthCard> {
'email': '',
'password': '',
'serverUrl': '',
'apitoken': '',
};
var _isLoading = false;
final _usernameController = TextEditingController();
Expand All @@ -129,6 +130,7 @@ class _AuthCardState extends State<AuthCard> {
final _serverUrlController = TextEditingController(
text: kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD,
);
final _apitokenController = TextEditingController();

@override
void dispose() {
Expand All @@ -137,6 +139,7 @@ class _AuthCardState extends State<AuthCard> {
_password2Controller.dispose();
_emailController.dispose();
_serverUrlController.dispose();
_apitokenController.dispose();
super.dispose();
}

Expand All @@ -162,6 +165,7 @@ class _AuthCardState extends State<AuthCard> {
void _resetTextfields() {
_usernameController.clear();
_passwordController.clear();
_apitokenController.clear();
}

void _submit(BuildContext context) async {
Expand All @@ -182,6 +186,7 @@ class _AuthCardState extends State<AuthCard> {
_authData['username']!,
_authData['password']!,
_authData['serverUrl']!,
_authData['apitoken']!,
);

// Register new user
Expand Down Expand Up @@ -271,6 +276,10 @@ class _AuthCardState extends State<AuthCard> {
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if(!_apitokenController.text.isEmpty) {
return null;
}

if (value == null || value.isEmpty) {
return AppLocalizations.of(context).invalidUsername;
}
Expand Down Expand Up @@ -329,6 +338,10 @@ class _AuthCardState extends State<AuthCard> {
controller: _passwordController,
textInputAction: TextInputAction.next,
validator: (value) {
if(!_apitokenController.text.isEmpty) {
return null;
}

if (value!.isEmpty || value.length < 8) {
return AppLocalizations.of(context).passwordTooShort;
}
Expand Down Expand Up @@ -367,6 +380,58 @@ class _AuthCardState extends State<AuthCard> {
: null,
);
}),
if (_authMode != AuthMode.Signup)
Row(children: <Widget>[
Expanded(
child: new Container(
margin: const EdgeInsets.only(left: 10.0, right: 20.0),
child: Divider(
color: Colors.black,
height: 36,
)),
),
Text("OR"),
Expanded(
child: new Container(
margin: const EdgeInsets.only(left: 20.0, right: 10.0),
child: Divider(
color: Colors.black,
height: 36,
)),
),
]),
if (_authMode != AuthMode.Signup)
TextFormField(
key: const Key('inputApitoken'),
decoration: InputDecoration(
labelText: AppLocalizations.of(context).apitoken,
errorMaxLines: 2,
prefixIcon: const Icon(Icons.password),
),
// autofillHints: const [AutofillHints.apitoken],
controller: _apitokenController,
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if(!_usernameController.text.isEmpty || !_passwordController.text.isEmpty) {
return null;
}
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).invalidApitoken;
}
if (!RegExp(r'^[a-f0-9]{40}$').hasMatch(value)) {
return AppLocalizations.of(context).apitokenValidChars;
}

return null;
},
inputFormatters: [
FilteringTextInputFormatter.deny(RegExp(r'\s\b|\b\s')),
],
onSaved: (value) {
_authData['apitoken'] = value!;
},
),
// Off-stage widgets are kept in the tree, otherwise the server URL
// would not be saved to _authData
Offstage(
Expand Down