-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.dart
213 lines (169 loc) · 5.78 KB
/
auth.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import 'dart:convert';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:nasa/models/game_user.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
enum SigninMethod {
google,
email,
guest,
}
Future<bool> isEmailAlreadyExist(email) async {
final url = Uri.parse(
'https://nasa-petacode-default-rtdb.firebaseio.com/leaderboard.json');
final response = await http.get(url);
if (json.decode(response.body) == null) return false;
final extractedData = Map<String, dynamic>.from(json.decode(response.body));
final listOfUsers = [
for (var user in extractedData.values) GameUser.fromMap(user)
];
for (var gameUser in listOfUsers) {
if (gameUser.email == email) return true;
}
return false;
}
// Future<void> updateUserId(email) async {
// final url = Uri.parse(
// 'https://nasa-petacode-default-rtdb.firebaseio.com/leaderboard.json');
// final response = await http.get(url);
// if (json.decode(response.body) == null) return false;
// final extractedData = Map<String, dynamic>.from(json.decode(response.body));
// final listOfUsers = [
// for (var user in extractedData.values) GameUser.fromMap(user)
// ];
// for (var gameUser in listOfUsers) {
// if (gameUser.email == email) return true;
// }
// return false;
// }
Future<void> addUserToLeaderboard(GameUser gameUser) async {
final uniqueId = gameUser.email!.split('@')[0];
final database = FirebaseDatabase.instance.ref();
final leaderBoardRef = database.child('leaderboard/$uniqueId');
await leaderBoardRef.set(gameUser.toMap());
// final url = Uri.parse(
// 'https://nasa-petacode-default-rtdb.firebaseio.com/leaderboard.json');
// final response = await http.post(url, body: gameUser.toJson());
// return json.decode(response.body)['name'];
}
Future<User?> emailSignin(String email, String password) async {
try {
final credential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
return credential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
throw Exception('No user found for that email.');
} else if (e.code == 'wrong-password') {
throw Exception('Wrong password provided for that user.');
}
}
return null;
}
final authProvider = ChangeNotifierProvider<Auth>((ref) {
return Auth();
});
final futureAuthProvider = FutureProvider<void>((ref) async {
final auth = ref.watch(authProvider);
await auth.getUser();
});
class Auth with ChangeNotifier {
GameUser user = GameUser();
bool get isAuth => user.isAuth;
Future<void> getUser() async {
final prefs = await SharedPreferences.getInstance();
final loadedData = prefs.getString('user');
print(loadedData);
if (loadedData == null) return;
final loadedUser = GameUser.fromJson(loadedData);
user = loadedUser;
}
Future<void> login(
SigninMethod signinMethod, {
String? name,
String? email,
String? password,
}) async {
switch (signinMethod) {
case SigninMethod.guest:
user.name = name!;
break;
case SigninMethod.google:
final loginInfo = await GoogleSignIn().signIn();
if (loginInfo == null) return;
user.name = loginInfo.displayName;
user.email = loginInfo.email;
user.imageUrl = loginInfo.photoUrl;
final isEmailExist = await isEmailAlreadyExist(user.email);
if (!isEmailExist) {
await addUserToLeaderboard(user);
}
break;
default:
final loginInfo = await emailSignin(email!, password!);
if (loginInfo == null) return;
user.name = loginInfo.displayName;
user.email = loginInfo.email;
user.imageUrl = loginInfo.photoURL;
}
final prefs = await SharedPreferences.getInstance();
prefs.setString('user', user.toJson());
notifyListeners();
}
void nextOfflineLevel(int stars) {
if (stars == 0) return;
user.nextLevel();
try {
final database = FirebaseDatabase.instance.ref();
final userRef = database.child('leaderboard/${user.username}');
userRef.update({'offlineLevel': user.offlineLevel + 1});
} catch (e) {
return;
}
}
Future<void> signup({
required String name,
required String email,
required String password,
}) async {
final isEmailExist = await isEmailAlreadyExist(email);
if (isEmailExist) {
throw Exception('User already exist');
}
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
final userInfo = await emailSignin(email, password);
if (userInfo == null) return;
await userInfo.updateDisplayName(name);
user.name = name;
user.email = userInfo.email;
user.imageUrl = userInfo.photoURL;
final gameUser = GameUser(name: name, email: email, password: password);
await addUserToLeaderboard(gameUser);
notifyListeners();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
Future<void> logout() async {
final prefs = await SharedPreferences.getInstance();
if (user.isGoogleSignin) await GoogleSignIn().signOut();
if (user.isEmailSignin) await FirebaseAuth.instance.signOut();
user.clearUser();
prefs.remove('user');
notifyListeners();
}
}