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

Add security for score submission with key verification in flappybird #456

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
20 changes: 19 additions & 1 deletion lib/flappybird/class/score.dart
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
import 'package:myecl/tools/functions.dart';
import 'package:myecl/user/class/list_users.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';

class Score {
late final SimpleUser user;
late final int value;
late final int key;
late final DateTime date;
late final int position;

Score({
required this.user,
required this.value,
required this.key,
required this.date,
required this.position,
});

static int genKey(int value) {
final data = "$value";
final bytes = utf8.encode(data);
final hash = sha256.convert(bytes);
final hashBytes = hash.bytes;

return hashBytes.sublist(0, 4).fold(0, (acc, byte) => (acc << 8) + byte);
}

Score.fromJson(Map<String, dynamic> json, {int? index = 0}) {
user = SimpleUser.fromJson(json['user']);
value = json['value'];
key = json['key'];
date = processDateFromAPI(json['creation_time']);
position = json['position'] ?? index;
}
Expand All @@ -25,18 +39,21 @@ class Score {
final Map<String, dynamic> data = <String, dynamic>{};
data['user_id'] = user.id;
data['value'] = value;
data['key'] = key;
return data;
}

Score copyWith({
SimpleUser? user,
int? value,
int? key,
DateTime? date,
int? position,
}) {
return Score(
user: user ?? this.user,
value: value ?? this.value,
key: key ?? this.key,
date: date ?? this.date,
position: position ?? this.position,
);
Expand All @@ -45,11 +62,12 @@ class Score {
Score.empty() {
user = SimpleUser.empty();
value = 0;
key = genKey(0);
date = DateTime.now();
position = 0;
}

@override
String toString() =>
'Score(user: $user, value: $value, date: $date, position: $position)';
'Score(user: $user, value: $value, key: $key, date: $date, position: $position)';
}
1 change: 1 addition & 0 deletions lib/flappybird/ui/pages/game_page/game_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class GamePage extends HookConsumerWidget {
Score(
user: newBird.user,
value: newBird.score,
key: Score.genKey(newBird.score),
date: DateTime.now(),
position: 0,
),
Expand Down
Loading