Skip to content
Merged
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
13 changes: 8 additions & 5 deletions lib/application.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@ class Application extends Container {

late BaseHttpServer _server;

Future<void> initialize(
{required Map<String, dynamic> config,
List<String> args = const []}) async {
Future<void> initialize({
required Map<String, dynamic> config,
List<String> args = const [],
}) async {
IoCContainer().register<RequestHandler>(() => RequestHandler());
IoCContainer()
.register<SessionManager>(() => SessionManager(), singleton: true);
IoCContainer().register<SessionManager>(
() => SessionManager(),
singleton: true,
);
if (env('APP_KEY') == '' || env('APP_KEY') == null) {
throw Exception('Key not found');
}
Expand Down
6 changes: 1 addition & 5 deletions lib/src/authentication/authenticate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ class Authenticate extends Middleware {
final String? guard;
final bool basic;
final String loginPath;
Authenticate({
this.guard,
this.basic = false,
this.loginPath = '/login',
});
Authenticate({this.guard, this.basic = false, this.loginPath = '/login'});

@mustCallSuper
@override
Expand Down
48 changes: 27 additions & 21 deletions lib/src/authentication/authentication.dart
Original file line number Diff line number Diff line change
Expand Up @@ -158,17 +158,22 @@ class Auth {

if (!customToken) {
Map<String, dynamic> payload = HasApiTokens().verify(
token.replaceFirst('Bearer ', ''), _userGuard, 'refresh_token');
token.replaceFirst('Bearer ', ''),
_userGuard,
'refresh_token',
);

Model? authenticatable =
Config().get('auth')['guards'][_userGuard]['provider'];
Model? authenticatable = Config().get(
'auth',
)['guards'][_userGuard]['provider'];

if (authenticatable == null) {
throw InvalidArgumentException('Authenticatable class not found');
}

Map? user =
await authenticatable.query.where('id', '=', payload['id']).first();
Map? user = await authenticatable.query
.where('id', '=', payload['id'])
.first();

if (user == null) {
throw Unauthenticated(message: 'Invalid token');
Expand All @@ -193,10 +198,9 @@ class Auth {
///
/// Returns true if the operation was successful.
Future<bool> deleteTokens(dynamic userId) async {
await PersonalAccessToken()
.query
.where('tokenable_id', '=', userId)
.update({'deleted_at': DateTime.now()});
await PersonalAccessToken().query.where('tokenable_id', '=', userId).update(
{'deleted_at': DateTime.now()},
);

return true;
}
Expand All @@ -210,8 +214,7 @@ class Auth {
/// Returns a Future that resolves to true if the operation was successful.
///
Future<bool> deleteCurrentToken(String token) async {
await PersonalAccessToken()
.query
await PersonalAccessToken().query
.where('token', '=', md5.convert(utf8.encode(token)))
.update({'deleted_at': DateTime.now()});
return true;
Expand Down Expand Up @@ -239,16 +242,18 @@ class Auth {
Map<String, dynamic>? user,
bool isCustomToken = false,
}) async {
Map<String, dynamic> payload = HasApiTokens()
.verify(token.replaceFirst('Bearer ', ''), _userGuard, 'access_token');
Map<String, dynamic> payload = HasApiTokens().verify(
token.replaceFirst('Bearer ', ''),
_userGuard,
'access_token',
);

if (isCustomToken) {
_user[_userGuard] = payload;
_loggedIn = true;
return true;
} else {
Map<String, dynamic>? exists = await PersonalAccessToken()
.query
Map<String, dynamic>? exists = await PersonalAccessToken().query
.where('token', '=', md5.convert(utf8.encode(token)))
.whereNull('deleted_at')
.first(['id']);
Expand All @@ -257,20 +262,21 @@ class Auth {
throw Unauthenticated(message: 'Invalid token');
}

await PersonalAccessToken()
.query
await PersonalAccessToken().query
.where('token', '=', md5.convert(utf8.encode(token)))
.update({'last_used_at': DateTime.now()});

if (user == null) {
Model? authenticatable =
Config().get('auth')['guards'][_userGuard]['provider'];
Model? authenticatable = Config().get(
'auth',
)['guards'][_userGuard]['provider'];

if (authenticatable == null) {
throw InvalidArgumentException('Authenticatable class not found');
}
user =
await authenticatable.query.where('id', '=', payload['id']).first();
user = await authenticatable.query
.where('id', '=', payload['id'])
.first();
}

if (user != null) {
Expand Down
28 changes: 13 additions & 15 deletions lib/src/authentication/has_api_tokens.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,7 @@ class HasApiTokens {
}

final jwt = JWT(
{
'user': jsonEncode(_userPayload),
'type': 'access_token',
...userId,
},
{'user': jsonEncode(_userPayload), 'type': 'access_token', ...userId},
audience: env('JWT_AUDIENCE') == null
? null
: Audience.one(env<String>('JWT_AUDIENCE')),
Expand All @@ -60,23 +56,25 @@ class HasApiTokens {
Map<String, dynamic> payload = {};
Duration expirationTime = expiresIn ?? const Duration(hours: 1);

String accessToken =
jwt.sign(SecretKey('$secretKey$guard'), expiresIn: expirationTime);
String accessToken = jwt.sign(
SecretKey('$secretKey$guard'),
expiresIn: expirationTime,
);

payload['access_token'] = accessToken;

if (withRefreshToken) {
final jwtRefresh = JWT({
...userId,
'type': 'refresh_token',
});
String refreshToken = jwtRefresh.sign(SecretKey('$secretKey$guard'),
expiresIn: const Duration(days: 120));
final jwtRefresh = JWT({...userId, 'type': 'refresh_token'});
String refreshToken = jwtRefresh.sign(
SecretKey('$secretKey$guard'),
expiresIn: const Duration(days: 120),
);
payload['refresh_token'] = refreshToken;
}

payload['expires_in'] =
DateTime.now().add(expirationTime).toIso8601String();
payload['expires_in'] = DateTime.now()
.add(expirationTime)
.toIso8601String();

return payload;
}
Expand Down
5 changes: 1 addition & 4 deletions lib/src/authentication/redirect_if_authenticated.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ class RedirectIfAuthenticated extends Middleware {
Future handle(Request req) async {
bool loggedIn = await getSession<bool?>('logged_in') ?? false;
if (loggedIn) {
throw RedirectException(
message: path,
responseType: ResponseType.html,
);
throw RedirectException(message: path, responseType: ResponseType.html);
}
}
}
19 changes: 12 additions & 7 deletions lib/src/aws/s3_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ class S3Client {
}

Uint8List _getSignatureKey(
String key, String date, String regionName, String serviceName) {
String key,
String date,
String regionName,
String serviceName,
) {
var kDate = _hmacSha256(Uint8List.fromList(utf8.encode('AWS4$key')), date);
var kRegion = _hmacSha256(kDate, regionName);
var kService = _hmacSha256(kRegion, serviceName);
Expand Down Expand Up @@ -55,25 +59,26 @@ class S3Client {
'x-amz-date:$dateTime',
'',
signedHeaders,
hash
hash,
].join('\n');

final stringToSign = [
algorithm,
dateTime,
scope,
sha256.convert(utf8.encode(canonicalRequest)).toString()
sha256.convert(utf8.encode(canonicalRequest)).toString(),
].join('\n');

final signingKey = _getSignatureKey(_secretKey, date, _region, service);
final signature = _hmacSha256(signingKey, stringToSign)
.map((e) => e.toRadixString(16).padLeft(2, '0'))
.join();
final signature = _hmacSha256(
signingKey,
stringToSign,
).map((e) => e.toRadixString(16).padLeft(2, '0')).join();

final authorizationHeader = [
'$algorithm Credential=$_accessKey/$scope',
'SignedHeaders=$signedHeaders',
'Signature=$signature'
'Signature=$signature',
].join(', ');

return {
Expand Down
12 changes: 6 additions & 6 deletions lib/src/cache/file_cache_driver.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ class FileCacheDriver implements CacheDriver {
}

@override
Future<void> put(String key, dynamic value,
{Duration duration = const Duration(hours: 1)}) async {
Future<void> put(
String key,
dynamic value, {
Duration duration = const Duration(hours: 1),
}) async {
final file = _getCacheFile(key);
await _ensureCacheDirectory();

Expand All @@ -57,10 +60,7 @@ class FileCacheDriver implements CacheDriver {
final file = _getCacheFile(key);
await _ensureCacheDirectory();

final cache = {
'value': value,
'expiration': null,
};
final cache = {'value': value, 'expiration': null};

await file.writeAsString(jsonEncode(cache));
}
Expand Down
3 changes: 2 additions & 1 deletion lib/src/config/defined_regexp.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ final alphaRegExp = RegExp(r'^[a-zA-Z]+$');
final emailRegExp = RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');

final uuidRegExp = RegExp(
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$');
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
);
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ abstract interface class DatabaseConnection {
String query, [
Map<String, dynamic> bindings = const {},
]);
Future insert(
String query, [
Map<String, dynamic> bindings = const {},
]);
Future insert(String query, [Map<String, dynamic> bindings = const {}]);
Future<bool> execute(
String query, [
Map<String, dynamic> bindings = const {},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
part of 'query_builder.dart';

enum ConflictAction {
update,

ignore,

replace,

delete,
}
enum ConflictAction { update, ignore, replace, delete }

abstract class BulkOperationsBuilder {
Future<bool> merge(
Expand Down Expand Up @@ -53,16 +45,19 @@ abstract class BulkOperationsBuilder {
Future<void> batchProcess({
required int batchSize,
required Future<void> Function(
List<Map<String, dynamic>> batch, int batchNumber)
processor,
List<Map<String, dynamic>> batch,
int batchNumber,
)
processor,
List<String> columns = const ['*'],
});

Future<void> chunkedProcess({
required int chunkSize,
required Future<List<Map<String, dynamic>>> Function(
List<Map<String, dynamic>> chunk)
processor,
List<Map<String, dynamic>> chunk,
)
processor,
String? destination,
List<String> columns = const ['*'],
});
Expand All @@ -75,7 +70,5 @@ abstract class BulkOperationsBuilder {
List<String>? conflictColumns,
});

Future<bool> transactionalBulkOperation(
Future<bool> Function() operations,
);
Future<bool> transactionalBulkOperation(Future<bool> Function() operations);
}
27 changes: 19 additions & 8 deletions lib/src/contract/database/query_builder/_cte_builder.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
part of 'query_builder.dart';

abstract class CteBuilder {
QueryBuilder withCte(String name, QueryBuilder subQuery,
{List<String>? columns});
QueryBuilder withCte(
String name,
QueryBuilder subQuery, {
List<String>? columns,
});

QueryBuilder withMultiple(Map<String, QueryBuilder> ctes,
{Map<String, List<String>>? columnsMap});
QueryBuilder withMultiple(
Map<String, QueryBuilder> ctes, {
Map<String, List<String>>? columnsMap,
});

QueryBuilder withRecursive(
String name,
Expand All @@ -14,9 +19,15 @@ abstract class CteBuilder {
List<String>? columns,
});

QueryBuilder withMaterialized(String name, QueryBuilder subQuery,
{List<String>? columns});
QueryBuilder withMaterialized(
String name,
QueryBuilder subQuery, {
List<String>? columns,
});

QueryBuilder withNotMaterialized(String name, QueryBuilder subQuery,
{List<String>? columns});
QueryBuilder withNotMaterialized(
String name,
QueryBuilder subQuery, {
List<String>? columns,
});
}
Loading