Skip to content

Commit

Permalink
Proper firebase admin service account access
Browse files Browse the repository at this point in the history
  • Loading branch information
luanpotter committed Jul 3, 2023
1 parent bfab1a3 commit d8b9084
Show file tree
Hide file tree
Showing 8 changed files with 211 additions and 17 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
.secrets
9 changes: 6 additions & 3 deletions lib/firebase/score.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@ import 'package:firedart/firestore/models.dart';

class Score {
final int playerId;
final String email;
final String username;
final int score;

Score({
required this.playerId,
required this.email,
required this.username,
required this.score,
});

Score.fromDocument(Document document)
: this(
playerId: document.map['playerId'] as int,
email: document.map['email'] as String,
username: document.map['username'] as String,
score: document.map['score'] as int,
);

@override
String toString() => '[$playerId] $username: $score';
}
12 changes: 7 additions & 5 deletions lib/firebase/score_calculator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ class _PlayerScore {
int score = 0;

_PlayerScore(this.player);

@override
String toString() => '$player: $score';
}

class ScoreCalculator {
Expand All @@ -15,13 +18,14 @@ class ScoreCalculator {
final scores = points.entries
.toList()
.sortedBy<num>((entry) => entry.value)
.map((entry) => _PlayerScore(entry.key));
.map((entry) => _PlayerScore(entry.key))
.toList();

final numPlayers = points.length;
final totalScore = points.values.reduce((a, b) => a + b);

var jackpot = numPlayers;
if (jackpot == 0) {
if (jackpot == 0 || totalScore == 0) {
return {};
}

Expand All @@ -39,9 +43,7 @@ class ScoreCalculator {
}

return Map.fromEntries(
scores
.map((score) => MapEntry(score.player, score.score))
.where((element) => element.value > 0),
scores.where((e) => e.score > 0).map((e) => MapEntry(e.player, e.score)),
);
}
}
49 changes: 44 additions & 5 deletions lib/firebase/scores.dart
Original file line number Diff line number Diff line change
@@ -1,34 +1,73 @@
import 'dart:io';

import 'package:firebase_admin/firebase_admin.dart';
import 'package:firedart/firedart.dart';
import 'package:firedart/firestore/token_authenticator.dart';
import 'package:lightrunners/firebase/score.dart';
import 'package:uuid/uuid.dart';

class Scores {
static late Firestore firestore;
static const uuid = Uuid();
static Firestore? _firestore;

Scores._();

static Future<String> _createCustomToken() => FirebaseAdmin.instance
.initializeApp(
AppOptions(
credential: FirebaseAdmin.instance
.certFromPath('.secrets/lightrunners-service-account.json'),
),
)
.auth()
.createCustomToken(uuid.v4());

static Future<void> init() async {
// NOTE: This will not work. support was removed from the library
const projectId = 'lightrunners-e89a9';
Firestore.initialize(projectId);
firestore = Firestore.instance;
final apiKey = File('.secrets/api-key.conf').readAsStringSync();

final customToken = await _createCustomToken();

final tokenStore = VolatileStore();

final auth = FirebaseAuth(apiKey, tokenStore);
await auth.signInWithCustomToken(customToken);

final authenticator = TokenAuthenticator.from(auth)?.authenticate;
_firestore = Firestore(projectId, authenticator: authenticator);
}

static Future<List<Score>> topScores() async {
final firestore = _firestore;
if (firestore == null) {
print('Error: Firestore not initialized.');
return [];
}

final page = await firestore
.collection('scores')
.orderBy('score', descending: true)
.limit(10)
.get();
return page.map(Score.fromDocument).toList();
final results = page.map(Score.fromDocument).toList();
print('Fetch top scores: $results');
return results;
}

static Future<void> updateScore({
required int playerId,
required int score,
}) async {
final firestore = _firestore;
if (firestore == null) {
print('Error: Firestore not initialized.');
return;
}

final document =
firestore.collection('scores').document(playerId.toString());
if (await document.exists) {
print('Updating score for player id $playerId to $score.');
await document.update({'score': score});
} else {
print('Error: Score not found for player id $playerId.');
Expand Down
2 changes: 1 addition & 1 deletion lib/game/components/count_down.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import 'package:flutter/painting.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lightrunners/ui/ui.dart';

const _matchLength = 60.0;
const _matchLength = 20.0;
const _radius = Radius.circular(3.0);

class CountDown extends PositionComponent {
Expand Down
7 changes: 5 additions & 2 deletions lib/leaderboard/view/leaderboard_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,12 @@ class _LeaderboardPageState extends State<LeaderboardPage> {
}

String _toScoreboardLine(Score record) {
final name = record.email.substring(
final name = record.username.substring(
0,
min(record.email.length, _maxCharactersScoreBoard - _maxScoreDigits - 1),
min(
record.username.length,
_maxCharactersScoreBoard - _maxScoreDigits - 1,
),
);
final maxScore = pow(10, _maxScoreDigits) - 1;
final score = record.score
Expand Down
Loading

0 comments on commit d8b9084

Please sign in to comment.