mirror of
https://github.com/Dr-Blank/Vaani.git
synced 2025-12-26 12:59:30 +00:00
feat: add deeplinking support for oauth login
This commit is contained in:
parent
38bad9671d
commit
61aeaf429f
23 changed files with 1310 additions and 343 deletions
121
lib/features/onboarding/view/callback_page.dart
Normal file
121
lib/features/onboarding/view/callback_page.dart
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:vaani/features/onboarding/providers/oauth_provider.dart';
|
||||
import 'package:vaani/features/onboarding/view/user_login_with_password.dart';
|
||||
import 'package:vaani/models/error_response.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
|
||||
class CallbackPage extends HookConsumerWidget {
|
||||
CallbackPage({super.key, this.state, this.code});
|
||||
|
||||
final String? state;
|
||||
final String? code;
|
||||
|
||||
final serverErrorResponse = ErrorResponseHandler();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (state == null || code == null) {
|
||||
return _SomethingWentWrong(
|
||||
message:
|
||||
'OAuth callback missing state or code\nGot: State: $state, Code: $code',
|
||||
);
|
||||
}
|
||||
|
||||
final flows = ref.read(oauthFlowsProvider);
|
||||
|
||||
// check if the state is in the flows
|
||||
if (!flows.containsKey(state)) {
|
||||
return const _SomethingWentWrong(
|
||||
message: 'State not found',
|
||||
);
|
||||
}
|
||||
|
||||
// get the token
|
||||
final loginAuthToken = ref.watch(
|
||||
loginInExchangeForCodeProvider(
|
||||
oauthState: state!,
|
||||
code: code!,
|
||||
responseHandler: serverErrorResponse,
|
||||
),
|
||||
);
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('Contacting server...\nPlease wait\n\nGot:'
|
||||
'\nState: $state\nCode: $code'),
|
||||
loginAuthToken.when(
|
||||
data: (authenticationToken) {
|
||||
if (authenticationToken == null) {
|
||||
handleServerError(
|
||||
context,
|
||||
serverErrorResponse,
|
||||
);
|
||||
return const BackToLoginButton();
|
||||
}
|
||||
return Text('Token: $authenticationToken');
|
||||
},
|
||||
loading: () => const CircularProgressIndicator(),
|
||||
error: (error, _) {
|
||||
handleServerError(
|
||||
context,
|
||||
serverErrorResponse,
|
||||
e: error,
|
||||
);
|
||||
return Column(
|
||||
children: [
|
||||
Text('Error with OAuth flow: $error'),
|
||||
const BackToLoginButton(),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BackToLoginButton extends StatelessWidget {
|
||||
const BackToLoginButton({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ElevatedButton(
|
||||
onPressed: () {
|
||||
GoRouter.of(context).goNamed(Routes.onboarding.name);
|
||||
},
|
||||
child: const Text('Return to login'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SomethingWentWrong extends StatelessWidget {
|
||||
const _SomethingWentWrong({
|
||||
super.key,
|
||||
this.message = 'Error with OAuth flow',
|
||||
});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(message),
|
||||
const BackToLoginButton(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,15 +1,14 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:lottie/lottie.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/api/authenticated_user_provider.dart';
|
||||
import 'package:vaani/api/server_provider.dart';
|
||||
import 'package:vaani/features/onboarding/view/user_login_with_open_id.dart';
|
||||
import 'package:vaani/features/onboarding/view/user_login_with_password.dart';
|
||||
import 'package:vaani/features/onboarding/view/user_login_with_token.dart';
|
||||
import 'package:vaani/hacks/fix_autofill_losing_focus.dart';
|
||||
import 'package:vaani/models/error_response.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/settings/api_settings_provider.dart';
|
||||
import 'package:vaani/settings/models/models.dart' as model;
|
||||
|
||||
|
|
@ -20,7 +19,7 @@ class UserLoginWidget extends HookConsumerWidget {
|
|||
});
|
||||
|
||||
final Uri server;
|
||||
final serverStatusError = ErrorResponse();
|
||||
final serverStatusError = ErrorResponseHandler();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
|
|
@ -40,8 +39,9 @@ class UserLoginWidget extends HookConsumerWidget {
|
|||
server: server,
|
||||
localAvailable:
|
||||
value.authMethods?.contains(AuthMethod.local) ?? false,
|
||||
openidAvailable:
|
||||
openIDAvailable:
|
||||
value.authMethods?.contains(AuthMethod.openid) ?? false,
|
||||
openIDButtonText: value.authFormData?.authOpenIDButtonText,
|
||||
);
|
||||
},
|
||||
loading: () {
|
||||
|
|
@ -85,21 +85,24 @@ class UserLoginMultipleAuth extends HookConsumerWidget {
|
|||
super.key,
|
||||
required this.server,
|
||||
this.localAvailable = false,
|
||||
this.openidAvailable = false,
|
||||
this.openIDAvailable = false,
|
||||
this.onPressed,
|
||||
this.openIDButtonText,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final bool localAvailable;
|
||||
final bool openidAvailable;
|
||||
final bool openIDAvailable;
|
||||
final void Function()? onPressed;
|
||||
final String? openIDButtonText;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
// will show choice chips for the available authentication methods
|
||||
// authToken method is always available
|
||||
final methodChoice = useState<AuthMethodChoice>(
|
||||
localAvailable ? AuthMethodChoice.local : AuthMethodChoice.authToken,
|
||||
// ! TODO revert to local when openID debugging is done
|
||||
localAvailable ? AuthMethodChoice.openid : AuthMethodChoice.authToken,
|
||||
);
|
||||
|
||||
final apiSettings = ref.watch(apiSettingsProvider);
|
||||
|
|
@ -150,7 +153,7 @@ class UserLoginMultipleAuth extends HookConsumerWidget {
|
|||
}
|
||||
},
|
||||
),
|
||||
if (openidAvailable)
|
||||
if (openIDAvailable)
|
||||
ChoiceChip(
|
||||
label: const Text('OpenID'),
|
||||
selected: methodChoice.value == AuthMethodChoice.openid,
|
||||
|
|
@ -176,17 +179,18 @@ class UserLoginMultipleAuth extends HookConsumerWidget {
|
|||
dimension: 8,
|
||||
),
|
||||
switch (methodChoice.value) {
|
||||
AuthMethodChoice.authToken => UserLoginWithToken(
|
||||
server: server,
|
||||
addServer: addServer,
|
||||
),
|
||||
AuthMethodChoice.local => UserLoginWithPassword(
|
||||
server: server,
|
||||
addServer: addServer,
|
||||
),
|
||||
AuthMethodChoice.openid => _UserLoginWithOpenID(
|
||||
server: server,
|
||||
addServer: addServer,
|
||||
),
|
||||
AuthMethodChoice.authToken => UserLoginWithToken(
|
||||
AuthMethodChoice.openid => UserLoginWithOpenID(
|
||||
server: server,
|
||||
addServer: addServer,
|
||||
openIDButtonText: openIDButtonText,
|
||||
),
|
||||
},
|
||||
],
|
||||
|
|
@ -197,292 +201,3 @@ class UserLoginMultipleAuth extends HookConsumerWidget {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UserLoginWithOpenID extends HookConsumerWidget {
|
||||
const _UserLoginWithOpenID({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
// TODO: implement build
|
||||
return const Text('OpenID');
|
||||
}
|
||||
}
|
||||
|
||||
class UserLoginWithToken extends HookConsumerWidget {
|
||||
UserLoginWithToken({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
final serverErrorResponse = ErrorResponse();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final authTokensController = useTextEditingController();
|
||||
|
||||
final api = ref.watch(audiobookshelfApiProvider(server));
|
||||
Future<void> loginAndSave() async {
|
||||
api.token = authTokensController.text;
|
||||
model.AuthenticatedUser? authenticatedUser;
|
||||
LoginResponse? success;
|
||||
try {
|
||||
success = await api.misc.authorize(
|
||||
responseErrorHandler: serverErrorResponse.storeError,
|
||||
);
|
||||
if (success == null) {
|
||||
throw StateError('No response from server');
|
||||
}
|
||||
} catch (e) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Login failed. Got response: ${serverErrorResponse.response.body} (${serverErrorResponse.response.statusCode})',
|
||||
),
|
||||
action: SnackBarAction(
|
||||
label: 'See Error',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Error'),
|
||||
content: Text(e.toString()),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
authenticatedUser = model.AuthenticatedUser(
|
||||
server: addServer(),
|
||||
id: success.user.id,
|
||||
username: success.user.username,
|
||||
authToken: api.token!,
|
||||
);
|
||||
|
||||
ref
|
||||
.read(authenticatedUserProvider.notifier)
|
||||
.addUser(authenticatedUser, setActive: true);
|
||||
|
||||
context.goNamed(Routes.home.name);
|
||||
}
|
||||
|
||||
return Form(
|
||||
child: Column(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: authTokensController,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
maxLines: 10,
|
||||
minLines: 1,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'API Token',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurface.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Please enter an API token';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onFieldSubmitted: (_) async {
|
||||
await loginAndSave();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
ElevatedButton(
|
||||
onPressed: loginAndSave,
|
||||
child: const Text('Login'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// class _UserLoginWithToken extends HookConsumerWidget {
|
||||
|
||||
class UserLoginWithPassword extends HookConsumerWidget {
|
||||
UserLoginWithPassword({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
final serverErrorResponse = ErrorResponse();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final usernameController = useTextEditingController();
|
||||
final passwordController = useTextEditingController();
|
||||
final isPasswordVisibleAnimationController = useAnimationController(
|
||||
duration: const Duration(milliseconds: 500),
|
||||
);
|
||||
|
||||
var isPasswordVisible = useState(false);
|
||||
final api = ref.watch(audiobookshelfApiProvider(server));
|
||||
|
||||
// forward animation when the password visibility changes
|
||||
useEffect(
|
||||
() {
|
||||
if (isPasswordVisible.value) {
|
||||
isPasswordVisibleAnimationController.forward();
|
||||
} else {
|
||||
isPasswordVisibleAnimationController.reverse();
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[isPasswordVisible.value],
|
||||
);
|
||||
|
||||
/// Login to the server and save the user
|
||||
Future<void> loginAndSave() async {
|
||||
final username = usernameController.text;
|
||||
final password = passwordController.text;
|
||||
|
||||
LoginResponse? success;
|
||||
try {
|
||||
success = await api.login(
|
||||
username: username,
|
||||
password: password,
|
||||
responseErrorHandler: serverErrorResponse.storeError,
|
||||
);
|
||||
if (success == null) {
|
||||
throw StateError('No response from server');
|
||||
}
|
||||
} catch (e) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Login failed. Got response: ${serverErrorResponse.response.body} (${serverErrorResponse.response.statusCode})',
|
||||
),
|
||||
action: SnackBarAction(
|
||||
label: 'See Error',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Error'),
|
||||
content: Text(e.toString()),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
// save the server
|
||||
final authenticatedUser = model.AuthenticatedUser(
|
||||
server: addServer(),
|
||||
id: success.user.id,
|
||||
password: password,
|
||||
username: username,
|
||||
authToken: api.token!,
|
||||
);
|
||||
// add the user to the list of users
|
||||
ref
|
||||
.read(authenticatedUserProvider.notifier)
|
||||
.addUser(authenticatedUser, setActive: true);
|
||||
|
||||
// redirect to the library page
|
||||
GoRouter.of(context).goNamed(Routes.home.name);
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: InactiveFocusScopeObserver(
|
||||
child: AutofillGroup(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: usernameController,
|
||||
autofocus: true,
|
||||
autofillHints: const [AutofillHints.username],
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Username',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
TextFormField(
|
||||
controller: passwordController,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
textInputAction: TextInputAction.done,
|
||||
obscureText: !isPasswordVisible.value,
|
||||
onFieldSubmitted: (_) {
|
||||
loginAndSave();
|
||||
},
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Password',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: ColorFiltered(
|
||||
colorFilter: ColorFilter.mode(
|
||||
Theme.of(context).colorScheme.primary.withOpacity(0.8),
|
||||
BlendMode.srcIn,
|
||||
),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(50),
|
||||
onTap: () {
|
||||
isPasswordVisible.value = !isPasswordVisible.value;
|
||||
},
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(left: 8, right: 8),
|
||||
child: Lottie.asset(
|
||||
'assets/animations/Animation - 1714930099660.json',
|
||||
controller: isPasswordVisibleAnimationController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
suffixIconConstraints: const BoxConstraints(
|
||||
maxHeight: 45,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
ElevatedButton(
|
||||
onPressed: loginAndSave,
|
||||
child: const Text('Login'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
116
lib/features/onboarding/view/user_login_with_open_id.dart
Normal file
116
lib/features/onboarding/view/user_login_with_open_id.dart
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/features/onboarding/providers/oauth_provider.dart';
|
||||
import 'package:vaani/features/onboarding/view/user_login_with_password.dart';
|
||||
import 'package:vaani/main.dart';
|
||||
import 'package:vaani/models/error_response.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/settings/constants.dart';
|
||||
import 'package:vaani/settings/models/models.dart' as model;
|
||||
import 'package:vaani/shared/utils.dart';
|
||||
|
||||
class UserLoginWithOpenID extends HookConsumerWidget {
|
||||
UserLoginWithOpenID({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
this.openIDButtonText,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
final String? openIDButtonText;
|
||||
final responseErrorHandler = ErrorResponseHandler(name: 'OpenID');
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final serverStatus = ref.watch(serverStatusProvider(server));
|
||||
void openIDLoginFlow() async {
|
||||
appLogger.fine('Clicked Login with OpenID');
|
||||
|
||||
final api = ref.read(audiobookshelfApiProvider(server));
|
||||
final (verifier, challenge) = generateVerifierAndChallenge();
|
||||
|
||||
appLogger.fine('Generated verifier: $verifier\nchallenge: $challenge');
|
||||
final appRedirectUri =
|
||||
'${AppMetadata.appScheme}://${Routes.openIDCallback.fullPath.substring(1)}';
|
||||
final (openIDLoginEndpoint, authCookie) = await api.server.oauth2Request(
|
||||
clientId: AppMetadata.appName,
|
||||
codeChallenge: challenge,
|
||||
// redirectUri: Uri(
|
||||
// scheme: AppMetadata.appScheme,
|
||||
// host: Routes.openIDCallback.path.substring(1),
|
||||
// ).toString(),
|
||||
redirectUri: appRedirectUri,
|
||||
responseErrorHandler: responseErrorHandler.storeError,
|
||||
);
|
||||
|
||||
if (openIDLoginEndpoint == null) {
|
||||
if (responseErrorHandler.response.statusCode == 400 &&
|
||||
responseErrorHandler.response.body
|
||||
.toLowerCase()
|
||||
.contains(RegExp(r'invalid.*redirect.*uri'))) {
|
||||
// show error
|
||||
handleServerError(
|
||||
context,
|
||||
responseErrorHandler,
|
||||
title: 'Failed to get OpenID login endpoint\n',
|
||||
body:
|
||||
'Please check that the redirect URI: "$appRedirectUri" is registered with the server.',
|
||||
outLink: server.replace(path: '${Routes.settings.fullPath}/auth'),
|
||||
outLinkText: 'Server settings',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// show error
|
||||
handleServerError(
|
||||
context,
|
||||
responseErrorHandler,
|
||||
title: 'Failed to get OpenID login endpoint',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// extract the state parameter
|
||||
final oauthState = openIDLoginEndpoint.queryParameters['state'];
|
||||
|
||||
if (oauthState == null) {
|
||||
handleServerError(
|
||||
context,
|
||||
responseErrorHandler,
|
||||
title: 'Failed to get OpenID login endpoint',
|
||||
body: 'No state parameter found in the response',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
appLogger.fine('Got OpenID login endpoint: $openIDLoginEndpoint');
|
||||
|
||||
// add the flow to the provider
|
||||
ref.read(oauthFlowsProvider.notifier).addFlow(
|
||||
oauthState,
|
||||
verifier: verifier,
|
||||
serverUri: server,
|
||||
cookie: Cookie.fromSetCookieValue(authCookie!),
|
||||
);
|
||||
|
||||
await handleLaunchUrl(
|
||||
openIDLoginEndpoint,
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: openIDLoginFlow,
|
||||
child: Text(openIDButtonText ?? 'Login with OpenID'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
224
lib/features/onboarding/view/user_login_with_password.dart
Normal file
224
lib/features/onboarding/view/user_login_with_password.dart
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:lottie/lottie.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/api/authenticated_user_provider.dart';
|
||||
import 'package:vaani/hacks/fix_autofill_losing_focus.dart';
|
||||
import 'package:vaani/models/error_response.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/settings/models/models.dart' as model;
|
||||
import 'package:vaani/shared/utils.dart';
|
||||
|
||||
class UserLoginWithPassword extends HookConsumerWidget {
|
||||
UserLoginWithPassword({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
final serverErrorResponse = ErrorResponseHandler();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final usernameController = useTextEditingController();
|
||||
final passwordController = useTextEditingController();
|
||||
final isPasswordVisibleAnimationController = useAnimationController(
|
||||
duration: const Duration(milliseconds: 500),
|
||||
);
|
||||
|
||||
var isPasswordVisible = useState(false);
|
||||
final api = ref.watch(audiobookshelfApiProvider(server));
|
||||
|
||||
// forward animation when the password visibility changes
|
||||
useEffect(
|
||||
() {
|
||||
if (isPasswordVisible.value) {
|
||||
isPasswordVisibleAnimationController.forward();
|
||||
} else {
|
||||
isPasswordVisibleAnimationController.reverse();
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[isPasswordVisible.value],
|
||||
);
|
||||
|
||||
/// Login to the server and save the user
|
||||
Future<void> loginAndSave() async {
|
||||
final username = usernameController.text;
|
||||
final password = passwordController.text;
|
||||
|
||||
LoginResponse? success;
|
||||
try {
|
||||
success = await api.login(
|
||||
username: username,
|
||||
password: password,
|
||||
responseErrorHandler: serverErrorResponse.storeError,
|
||||
);
|
||||
if (success == null) {
|
||||
throw StateError('No response from server');
|
||||
}
|
||||
} catch (e) {
|
||||
handleServerError(
|
||||
context,
|
||||
serverErrorResponse,
|
||||
title: 'Login failed',
|
||||
e: e,
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
// save the server
|
||||
final authenticatedUser = model.AuthenticatedUser(
|
||||
server: addServer(),
|
||||
id: success.user.id,
|
||||
password: password,
|
||||
username: username,
|
||||
authToken: api.token!,
|
||||
);
|
||||
// add the user to the list of users
|
||||
ref
|
||||
.read(authenticatedUserProvider.notifier)
|
||||
.addUser(authenticatedUser, setActive: true);
|
||||
|
||||
// redirect to the library page
|
||||
GoRouter.of(context).goNamed(Routes.home.name);
|
||||
}
|
||||
|
||||
return Center(
|
||||
child: InactiveFocusScopeObserver(
|
||||
child: AutofillGroup(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: usernameController,
|
||||
autofocus: true,
|
||||
autofillHints: const [AutofillHints.username],
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Username',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
TextFormField(
|
||||
controller: passwordController,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
textInputAction: TextInputAction.done,
|
||||
obscureText: !isPasswordVisible.value,
|
||||
onFieldSubmitted: (_) {
|
||||
loginAndSave();
|
||||
},
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Password',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurface
|
||||
.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: ColorFiltered(
|
||||
colorFilter: ColorFilter.mode(
|
||||
Theme.of(context).colorScheme.primary.withOpacity(0.8),
|
||||
BlendMode.srcIn,
|
||||
),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(50),
|
||||
onTap: () {
|
||||
isPasswordVisible.value = !isPasswordVisible.value;
|
||||
},
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(left: 8, right: 8),
|
||||
child: Lottie.asset(
|
||||
'assets/animations/Animation - 1714930099660.json',
|
||||
controller: isPasswordVisibleAnimationController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
suffixIconConstraints: const BoxConstraints(
|
||||
maxHeight: 45,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
ElevatedButton(
|
||||
onPressed: loginAndSave,
|
||||
child: const Text('Login'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> handleServerError(
|
||||
BuildContext context,
|
||||
ErrorResponseHandler responseErrorHandler, {
|
||||
String title = 'Something went wrong',
|
||||
String? body,
|
||||
Uri? outLink,
|
||||
String? outLinkText,
|
||||
Object? e,
|
||||
}) async {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'$title\n'
|
||||
'Got response: ${responseErrorHandler.response.body} (${responseErrorHandler.response.statusCode})',
|
||||
),
|
||||
action: SnackBarAction(
|
||||
label: 'See Error',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Error'),
|
||||
content: SelectableText('$title\n'
|
||||
'Got response: ${responseErrorHandler.response.body} (${responseErrorHandler.response.statusCode})\n'
|
||||
'Stacktrace: $e\n\n'
|
||||
'$body\n\n'),
|
||||
actions: [
|
||||
if (outLink != null)
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await handleLaunchUrl(outLink);
|
||||
},
|
||||
child: Text(outLinkText ?? 'Open link'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// open an issue on the github page
|
||||
handleLaunchUrl(
|
||||
Uri.parse(
|
||||
'https://github.com/Dr-Blank/Vaani/issues',
|
||||
),
|
||||
);
|
||||
},
|
||||
child: const Text('Open issue'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
110
lib/features/onboarding/view/user_login_with_token.dart
Normal file
110
lib/features/onboarding/view/user_login_with_token.dart
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:shelfsdk/audiobookshelf_api.dart';
|
||||
import 'package:vaani/api/api_provider.dart';
|
||||
import 'package:vaani/api/authenticated_user_provider.dart';
|
||||
import 'package:vaani/models/error_response.dart';
|
||||
import 'package:vaani/router/router.dart';
|
||||
import 'package:vaani/settings/models/models.dart' as model;
|
||||
|
||||
class UserLoginWithToken extends HookConsumerWidget {
|
||||
UserLoginWithToken({
|
||||
super.key,
|
||||
required this.server,
|
||||
required this.addServer,
|
||||
});
|
||||
|
||||
final Uri server;
|
||||
final model.AudiobookShelfServer Function() addServer;
|
||||
final serverErrorResponse = ErrorResponseHandler();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final authTokensController = useTextEditingController();
|
||||
|
||||
final api = ref.watch(audiobookshelfApiProvider(server));
|
||||
Future<void> loginAndSave() async {
|
||||
api.token = authTokensController.text;
|
||||
model.AuthenticatedUser? authenticatedUser;
|
||||
LoginResponse? success;
|
||||
try {
|
||||
success = await api.misc.authorize(
|
||||
responseErrorHandler: serverErrorResponse.storeError,
|
||||
);
|
||||
if (success == null) {
|
||||
throw StateError('No response from server');
|
||||
}
|
||||
} catch (e) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Login failed. Got response: ${serverErrorResponse.response.body} (${serverErrorResponse.response.statusCode})',
|
||||
),
|
||||
action: SnackBarAction(
|
||||
label: 'See Error',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Error'),
|
||||
content: Text(e.toString()),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
authenticatedUser = model.AuthenticatedUser(
|
||||
server: addServer(),
|
||||
id: success.user.id,
|
||||
username: success.user.username,
|
||||
authToken: api.token!,
|
||||
);
|
||||
|
||||
ref
|
||||
.read(authenticatedUserProvider.notifier)
|
||||
.addUser(authenticatedUser, setActive: true);
|
||||
|
||||
context.goNamed(Routes.home.name);
|
||||
}
|
||||
|
||||
return Form(
|
||||
child: Column(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: authTokensController,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
maxLines: 10,
|
||||
minLines: 1,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'API Token',
|
||||
labelStyle: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurface.withOpacity(0.8),
|
||||
),
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Please enter an API token';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onFieldSubmitted: (_) async {
|
||||
await loginAndSave();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
ElevatedButton(
|
||||
onPressed: loginAndSave,
|
||||
child: const Text('Login'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue