Skip to content

Commit

Permalink
CLI authorize implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Muska-Ami committed Dec 22, 2024
1 parent 6063070 commit 4eb1a6e
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 58 deletions.
6 changes: 3 additions & 3 deletions nyalcf_cli/bin/nyalcf_cli.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import 'package:nyalcf_inject/nyalcf_inject.dart';

// Project imports:
import 'package:nyalcf/arguments.dart';
import 'package:nyalcf/commands/authorize.dart';
import 'package:nyalcf/commands/config.dart';
import 'package:nyalcf/commands/download.dart';
import 'package:nyalcf/commands/login.dart';
import 'package:nyalcf/commands/logout.dart';
import 'package:nyalcf/commands/start.dart';
import 'package:nyalcf/state.dart';
Expand Down Expand Up @@ -57,8 +57,8 @@ void main(List<String> arguments) async {
}

// 登录登出
if (results.wasParsed('login')) {
await Login().main(results.rest);
if (results.wasParsed('authorize')) {
await Authorize().main(results.rest);
}
if (results.wasParsed('logout')) {
await Logout().main(results.rest);
Expand Down
6 changes: 3 additions & 3 deletions nyalcf_cli/lib/arguments.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ class Arguments {
help: 'Print this usage information.',
)
..addFlag(
'login',
abbr: 'l',
'authorize',
abbr: 'a',
negatable: false,
help: 'Login to LoCyanFrp. usage: <username> <password>',
help: 'Authorize. usage: <username> <password>',
)
..addFlag(
'logout',
Expand Down
85 changes: 85 additions & 0 deletions nyalcf_cli/lib/commands/authorize.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Dart imports:
import 'dart:convert';
import 'dart:io';

// Package imports:
import 'package:crypto/crypto.dart';
import 'package:nyalcf_core/models/user_info_model.dart';
import 'package:nyalcf_core/network/client/api/auth/oauth/access_token.dart';
import 'package:nyalcf_core/network/client/api/user/info.dart' as user_info;
import 'package:nyalcf_core/network/client/api_client.dart';
import 'package:nyalcf_core/network/server/oauth.dart';
import 'package:nyalcf_core/storages/stores/user_info_storage.dart';
import 'package:nyalcf_core/utils/logger.dart';
import 'package:nyalcf_core_extend/storages/token_storage.dart';

// Project imports:
import 'package:nyalcf/templates/command.dart';

import 'package:nyalcf_core/network/client/api/user/frp/token.dart'
as user_frp_token;

class Authorize implements Command {
static final _tokenStorage = TokenStorage();

static bool _callback = false;
static String? _refreshToken;

@override
Future<void> main(List<String> args) async {
final ApiClient api = ApiClient();

await startHttpServer();
Logger.write('Waiting callback...');
while (!_callback) {}
if (_refreshToken == null) exit(1);
final rs = await api.post(PostAccessToken(
appId: 1,
refreshToken: _refreshToken!,
));
if (rs == null) exit(1);
final int userId = rs.data['data']['user_id'];
final String accessToken = rs.data['data']['access_token'];
_tokenStorage.setRefreshToken(_refreshToken!);
_tokenStorage.setAccessToken(accessToken);

final apix = ApiClient(accessToken: accessToken);
final rsInfo = await apix.get(user_info.GetInfo(
userId: userId,
));
final rsFrpToken = await apix.get(user_frp_token.GetToken(
userId: userId,
));
if (rsInfo == null || rsFrpToken == null) exit(1);
final userInfo = UserInfoModel(
username: rsInfo.data['data']['username'],
id: rsInfo.data['data']['id'],
email: rsInfo.data['data']['email'],
avatar: "https://cravatar.cn/avatar/"
"${md5.convert(utf8.encode(rsInfo.data['data']['email']))}",
inbound: rsInfo.data['data']['inbound'],
outbound: rsInfo.data['data']['outbound'],
traffic: rsInfo.data['data']['traffic'],
);
UserInfoStorage.save(userInfo);
final frpToken = rsFrpToken.data['data']['frp_token'];
_tokenStorage.setFrpToken(frpToken);
}

Future<void> startHttpServer() async {
OAuth.initRoute(
response: OAuthResponseBody(success: '授权成功', error: '授权失败'),
callback: callback,
);
await OAuth.start();
}

void callback({String? refreshToken, String? error}) {
if (error != null) {
Logger.error('Error: $error');
} else {
_refreshToken = refreshToken;
}
_callback = true;
}
}
15 changes: 7 additions & 8 deletions nyalcf_cli/lib/commands/download.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class Download implements Command {
_provide = true;
}
if (verbose) {
Logger.verbose('Provide info: $_provideArch, $_providePlatform');
Logger.verbose('Provide info: $_provideArch, $_providePlatform');
}
final systemArch = await CPUArch.getCPUArchitecture();
if (verbose) {
Expand Down Expand Up @@ -74,15 +74,15 @@ class Download implements Command {
onFailed: onFailed,
useMirror: false,
);
stdout.write('\r${' ' * 30}');
stdout.write('\rPlease wait, extracting frpc...\n');
Logger.write('Please wait, extracting frpc...');
await FrpcArchive.extract(
platform: platform, arch: _selectedArch, version: '0.51.3-6');
stdout.write('\r${' ' * 30}');
stdout.write('\rSuccess!\n');
Logger.info('Success!');
} else {
Logger.error(
'Unsupported system! If you believe this is wrong, please provide arch manually in command.');
'Unsupported system! If you believe this is wrong,'
' please provide arch manually in command.',
);
}
default:
Logger.error('No valid arguments provided.');
Expand All @@ -105,8 +105,7 @@ class Download implements Command {
}

void callback(downloaded, all) {
stdout.write('\r${' ' * 30}');
stdout.write('\rProgress: ${(downloaded / all * 100).toStringAsFixed(2)}%');
Logger.write('Progress: ${(downloaded / all * 100).toStringAsFixed(2)}%');
}

void onFailed(Object e) {
Expand Down
42 changes: 0 additions & 42 deletions nyalcf_cli/lib/commands/login.dart

This file was deleted.

2 changes: 1 addition & 1 deletion nyalcf_cli/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ packages:
source: hosted
version: "1.11.1"
crypto:
dependency: transitive
dependency: "direct main"
description:
name: crypto
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
Expand Down
1 change: 1 addition & 0 deletions nyalcf_cli/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies:
path: ./nyalcf_core_extend
dio: ^5.7.0
args: ^2.4.2
crypto: ^3.0.6

dev_dependencies:
lints: ^5.0.0
Expand Down
7 changes: 6 additions & 1 deletion nyalcf_core/lib/utils/logger.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class Logger {
}

/// 获取 Logger 对象
static get _logger async {
static Future<log_u.Logger> get _logger async {
List<log_u.LogOutput> multiOutput = [_consoleOutput, await _fileOutPut];
return log_u.Logger(
filter: LogFilter(),
Expand Down Expand Up @@ -91,6 +91,11 @@ class Logger {
}
}

static Future<void> write(s) async {
stdout.write('\r${' ' * 30}');
stdout.write('\r$s');
}

/// FRPC INFO
static Future<void> frpcInfo(pxid, s) async {
(await _frpcLogger).i('[$pxid] $s');
Expand Down

0 comments on commit 4eb1a6e

Please sign in to comment.