import 'dart:convert'; import 'dart:io'; import 'package:dartssh2/dartssh2.dart'; import 'package:flutter/material.dart'; // for ed2219 key generation import 'package:cryptography/cryptography.dart'; import 'package:flutter/services.dart'; // secret storage import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:oauth2/oauth2.dart' as oauth2; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } Future getOAuth2Client() async { // This is a placeholder for OAuth2 client initialization. // Replace with your actual OAuth2 client setup. final authorizationEndpoint = Uri.parse( 'https://auth.leinelab.org/application/o/authorize/', ); final tokenEndpoint = Uri.parse( 'https://auth.leinelab.org/application/o/token/', ); final identifier = 'UwSMm8gTwBTUURSaxp5uPpuwX1OkGO4FRHeO9v3i'; final secret = null; // = 'my client secret'; final redirectUrl = Uri.parse('http://localhost:30165/'); final credentialsFile = File('~/.myapp/credentials.json'); //.... var exists = await credentialsFile.exists(); if (exists) { var credentials = oauth2.Credentials.fromJson( await credentialsFile.readAsString(), ); return oauth2.Client(credentials, identifier: identifier, secret: secret); } var grant = oauth2.AuthorizationCodeGrant( identifier, authorizationEndpoint, tokenEndpoint, secret: secret, ); var authorizationUrl = grant.getAuthorizationUrl( redirectUrl, scopes: ["profile", "email", "goauthentik.io/api", "openid"], ); // TODO: clicking the button twice might try to bind the server twice var server = await HttpServer.bind("127.0.0.1", 30165); await launchUrl(authorizationUrl); var queryParameters; await server.forEach((HttpRequest request) { request.response.write( 'Success! You can close this window now and go back to the app.', ); queryParameters = request.uri.queryParameters; request.response.close(); server.close(); }); return await grant.handleAuthorizationResponse(queryParameters); } void makeAlert(BuildContext context, String title, String message) { showDialog( context: context, builder: (BuildContext context) => AlertDialog( title: Text(title), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.pop(context, 'OK'), child: const Text('OK'), ), ], ), ); } Future generateKeyPair() async { final algorithm = Ed25519(); // Generate a key pair final cryptographyKeyPair = await algorithm.newKeyPair(); final privateKey = await cryptographyKeyPair.extractPrivateKeyBytes(); final publicKey = (await cryptographyKeyPair.extractPublicKey()).bytes; final dartsshKeyPair = OpenSSHEd25519KeyPair( Uint8List.fromList(publicKey), Uint8List.fromList(privateKey + publicKey), "", ); return dartsshKeyPair; } String encodePublicKey(OpenSSHEd25519KeyPair keyPair, {String comment = ''}) { final publicKeyBytes = keyPair.toPublicKey().encode(); return "ssh-ed25519 ${base64.encode(publicKeyBytes)} $comment"; } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'LeineLab e.V. Key App'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { int navIndex = 0; OpenSSHEd25519KeyPair? keyPair; String _output = ''; String key = ''; Future doOAuth() async { final client = await getOAuth2Client(); // TODO: Handle errors better try { final jsonMe = await client.read( Uri.parse('https://auth.leinelab.org/api/v3/core/users/me/'), ); final me = jsonDecode(jsonMe); final user = me['user']; final transformed = { "username": user['username'], "name": user['name'], "email": user['email'], "attributes.settings.locale": user['settings']['locale'], "attributes.sshPublicKeys": "foooooooobar :O :O!", // fix oder aus anderer Quelle "component": "ak-stage-prompt", }; print(user); print(transformed); final push = jsonEncode(transformed); final response0 = await client.get( Uri.parse( 'https://auth.leinelab.org/api/v3/flows/instances/default-user-settings-flow/execute/', ), ); var sessionCookieHeader = response0.headers['set-cookie']; if (sessionCookieHeader == null) { throw Exception('No session cookie found in response headers.'); } String? sessionCookie; int index = sessionCookieHeader.indexOf(';'); sessionCookie = (index == -1) ? sessionCookieHeader : sessionCookieHeader.substring(0, index); final responsea = await client.get( Uri.parse( 'https://auth.leinelab.org/api/v3/flows/executor/default-user-settings-flow/?query=', ), headers: {'Cookie': sessionCookie}, ); print("Response A status code: ${responsea.statusCode}"); print("Response body:"); print(responsea.body); print("Session cookie: $sessionCookie"); final response = await client.post( Uri.parse( 'https://auth.leinelab.org/api/v3/flows/executor/default-user-settings-flow/?query=', ), body: push, headers: {'Content-Type': 'application/json', 'Cookie': sessionCookie}, ); // Authentik expects a redirect after the POST request and only writes // the data to the database after fetching the redirect location. if (response.statusCode != 302) { throw Exception( "Expected a redirect (302) response, but got ${response.statusCode}", ); } final newLocation = response.headers['location']; if (newLocation == null) { throw Exception("No redirect location found in response headers."); } final responseFinal = await client.get( Uri.parse('https://auth.leinelab.org/' + newLocation), headers: {'Cookie': sessionCookie}, ); if (responseFinal.statusCode == 200) { print("User data updated successfully."); print("responseFinal body:"); print(responseFinal.body); responseFinal.headers.toString().split('\n').forEach(print); } else { print("Error updating user data: ${responseFinal.statusCode}"); print("responseFinal body:"); print(responseFinal.body); print(responseFinal.headers.toString()); } } catch (e) { print(e.toString()); } ; } Future doSSH() async { SSHSocket? socket; try { socket = await SSHSocket.connect( '192.168.2.123', 22, timeout: const Duration(seconds: 0, milliseconds: 500), ); final client = SSHClient( socket, username: 'test', identities: List.of(keyPair != null ? [keyPair!] : []), ); final uptime = await client.run('uptime'); setState(() { _output = utf8.decode(uptime); }); } catch (e) { setState(() { _output = "Error: $e"; }); return; } } Future obtainKeyPair({bool regenerate = false}) async { // Generate a key pair final storage = const FlutterSecureStorage(); final storedKey = await storage.read(key: 'ssh_key_pair'); // Restore the key if we have one stored and regeneration is not requested if (storedKey != null && !regenerate) { // If we have a stored key, use it final keyPairsFromStorage = SSHKeyPair.fromPem(storedKey); assert(keyPairsFromStorage.length == 1); assert(keyPairsFromStorage[0] is OpenSSHEd25519KeyPair); final keyPairFromStorage = keyPairsFromStorage[0] as OpenSSHEd25519KeyPair; setState(() { keyPair = keyPairFromStorage; key = encodePublicKey(keyPairFromStorage, comment: "leinelab-app-key"); }); return; } final generatedKeyPair = await generateKeyPair(); // local variable avoids downcast to ? ptr await storage.write(key: 'ssh_key_pair', value: generatedKeyPair.toPem()); setState(() { keyPair = generatedKeyPair; key = encodePublicKey(generatedKeyPair, comment: "leinelab-app-key"); }); await SystemChannels.platform.invokeMethod( 'Clipboard.setData', {'text': key}, ); } @override void initState() { super.initState(); // we do not await generateKey() here, as this is the intended way obtainKeyPair(); } @override Widget build(BuildContext context) { final String outputText = _output.isNotEmpty ? 'Output: $_output' : 'Press the button to run a command.'; final bodyComponentMain = Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextButton(onPressed: doOAuth, child: Text("Oauth2 Login")), Text('Current output:'), Text(outputText, style: Theme.of(context).textTheme.headlineMedium), ], ), ); final bodyComponentInfo = Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [Center(child: Text('Info\n\n$key'))], ), ); final actionButtonMain = FloatingActionButton( onPressed: doSSH, tooltip: 'Do SSH', child: const Icon(Icons.computer), ); final actionButtonInfo = FloatingActionButton( onPressed: () => obtainKeyPair(regenerate: true), tooltip: 'Regenerate Key', child: const Icon(Icons.refresh), ); var bodyComponent = bodyComponentMain; var actionButton = actionButtonMain; if (navIndex == 0) { // Main page bodyComponent = bodyComponentMain; actionButton = actionButtonMain; } else if (navIndex == 1) { // Info page bodyComponent = bodyComponentInfo; actionButton = actionButtonInfo; } else { throw Exception('Unknown navIndex: $navIndex'); } return Scaffold( appBar: AppBar(backgroundColor: Colors.amber, title: Text(widget.title)), body: bodyComponent, floatingActionButton: actionButton, drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: [ DrawerHeader( decoration: BoxDecoration(color: Colors.amber), child: Text( widget.title, style: TextStyle(color: Colors.black, fontSize: 24), ), ), ListTile( title: const Text('Main Page'), onTap: () { setState(() { navIndex = 0; }); Navigator.pop(context); }, ), ListTile( title: const Text('Info Page'), onTap: () { setState(() { navIndex = 1; }); Navigator.pop(context); }, ), ], ), ), ); } }