forked from flutter/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase_auth.dart
More file actions
executable file
·370 lines (322 loc) · 11.5 KB
/
firebase_auth.dart
File metadata and controls
executable file
·370 lines (322 loc) · 11.5 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';
/// Represents user data returned from an identity provider.
class UserInfo {
final Map<dynamic, dynamic> _data;
UserInfo._(this._data);
/// The provider identifier.
String get providerId => _data['providerId'];
/// The provider’s user ID for the user.
String get uid => _data['uid'];
/// The name of the user.
String get displayName => _data['displayName'];
/// The URL of the user’s profile photo.
String get photoUrl => _data['photoUrl'];
/// The user’s email address.
String get email => _data['email'];
@override
String toString() {
return '$runtimeType($_data)';
}
}
/// Represents user profile data that can be updated by [updateProfile]
/// The purpose of having separate class with a map is to give possibility
/// to check if value was set to null or not provided
class UserUpdateInfo {
/// Container of data that will be send in update request
final Map<String, String> _updateData = <String, String>{};
set displayName(String displayName) =>
_updateData["displayName"] = displayName;
String get displayName => _updateData["displayName"];
set photoUrl(String photoUri) => _updateData["photoUrl"] = photoUri;
String get photoUrl => _updateData["photoUrl"];
}
/// Represents a user.
class FirebaseUser extends UserInfo {
final List<UserInfo> providerData;
FirebaseUser._(Map<dynamic, dynamic> data)
: providerData = data['providerData']
.map<UserInfo>((dynamic item) => new UserInfo._(item))
.toList(),
super._(data);
// Returns true if the user is anonymous; that is, the user account was
// created with signInAnonymously() and has not been linked to another
// account.
bool get isAnonymous => _data['isAnonymous'];
/// Returns true if the user's email is verified.
bool get isEmailVerified => _data['isEmailVerified'];
/// Obtains the id token for the current user, forcing a [refresh] if desired.
///
/// Completes with an error if the user is signed out.
Future<String> getIdToken({bool refresh: false}) async {
return await FirebaseAuth.channel.invokeMethod('getIdToken', <String, bool>{
'refresh': refresh,
});
}
Future<void> sendEmailVerification() async {
await FirebaseAuth.channel.invokeMethod('sendEmailVerification');
}
/// Manually refreshes the data of the current user (for example, attached providers, display name, and so on).
Future<void> reload() async {
await FirebaseAuth.channel.invokeMethod('reload');
}
@override
String toString() {
return '$runtimeType($_data)';
}
}
class FirebaseAuth {
@visibleForTesting
static const MethodChannel channel = const MethodChannel(
'plugins.flutter.io/firebase_auth',
);
final Map<int, StreamController<FirebaseUser>> _authStateChangedControllers =
<int, StreamController<FirebaseUser>>{};
/// Provides an instance of this class corresponding to the default app.
///
/// TODO(jackson): Support for non-default apps.
static FirebaseAuth instance = new FirebaseAuth._();
FirebaseAuth._() {
channel.setMethodCallHandler(_callHandler);
}
/// Receive [FirebaseUser] each time the user signIn or signOut
Stream<FirebaseUser> get onAuthStateChanged {
Future<int> _handle;
StreamController<FirebaseUser> controller;
controller = new StreamController<FirebaseUser>.broadcast(onListen: () {
_handle = channel
.invokeMethod('startListeningAuthState')
.then<int>((dynamic v) => v);
_handle.then((int handle) {
_authStateChangedControllers[handle] = controller;
});
}, onCancel: () {
_handle.then((int handle) async {
await channel.invokeMethod(
"stopListeningAuthState", <String, int>{"id": handle});
_authStateChangedControllers.remove(handle);
});
});
return controller.stream;
}
/// Asynchronously creates and becomes an anonymous user.
///
/// If there is already an anonymous user signed in, that user will be
/// returned instead. If there is any other existing user signed in, that
/// user will be signed out.
///
/// Will throw a PlatformException if
/// FIRAuthErrorCodeOperationNotAllowed - Indicates that anonymous accounts are not enabled. Enable them in the Auth section of the Firebase console.
/// See FIRAuthErrors for a list of error codes that are common to all API methods.
Future<FirebaseUser> signInAnonymously() async {
final Map<dynamic, dynamic> data =
await channel.invokeMethod('signInAnonymously');
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<FirebaseUser> createUserWithEmailAndPassword({
@required String email,
@required String password,
}) async {
assert(email != null);
assert(password != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'createUserWithEmailAndPassword',
<String, String>{
'email': email,
'password': password,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<List<String>> fetchProvidersForEmail({
@required String email,
}) async {
assert(email != null);
final List<dynamic> providers = await channel.invokeMethod(
'fetchProvidersForEmail',
<String, String>{
'email': email,
},
);
return providers?.cast<String>();
}
Future<void> sendPasswordResetEmail({
@required String email,
}) async {
assert(email != null);
return await channel.invokeMethod(
'sendPasswordResetEmail',
<String, String>{
'email': email,
},
);
}
Future<FirebaseUser> signInWithEmailAndPassword({
@required String email,
@required String password,
}) async {
assert(email != null);
assert(password != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'signInWithEmailAndPassword',
<String, String>{
'email': email,
'password': password,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<FirebaseUser> signInWithFacebook(
{@required String accessToken}) async {
assert(accessToken != null);
final Map<dynamic, dynamic> data =
await channel.invokeMethod('signInWithFacebook', <String, String>{
'accessToken': accessToken,
});
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
/// Signs in with a Twitter account using the specified credentials.
///
/// The returned future completes with the signed-in user or a [PlatformException], if sign in failed.
Future<FirebaseUser> signInWithTwitter({
@required String authToken,
@required String authTokenSecret,
}) async {
assert(authToken != null);
assert(authTokenSecret != null);
final Map<dynamic, dynamic> data =
await channel.invokeMethod('signInWithTwitter', <String, String>{
'authToken': authToken,
'authTokenSecret': authTokenSecret,
});
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<FirebaseUser> signInWithGoogle({
@required String idToken,
@required String accessToken,
}) async {
assert(idToken != null);
assert(accessToken != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'signInWithGoogle',
<String, String>{
'idToken': idToken,
'accessToken': accessToken,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<FirebaseUser> signInWithCustomToken({@required String token}) async {
assert(token != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'signInWithCustomToken',
<String, String>{
'token': token,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<void> signOut() async {
return await channel.invokeMethod("signOut");
}
/// Asynchronously gets current user, or `null` if there is none.
Future<FirebaseUser> currentUser() async {
final Map<dynamic, dynamic> data =
await channel.invokeMethod("currentUser");
final FirebaseUser currentUser =
data == null ? null : new FirebaseUser._(data);
return currentUser;
}
/// Links email account with current user and returns [Future<FirebaseUser>]
/// basically current user with additional email information
///
/// throws [PlatformException] when
/// 1. email address is already used
/// 2. wrong email and password provided
Future<FirebaseUser> linkWithEmailAndPassword({
@required String email,
@required String password,
}) async {
assert(email != null);
assert(password != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'linkWithEmailAndPassword',
<String, String>{
'email': email,
'password': password,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<void> updateProfile(UserUpdateInfo userUpdateInfo) async {
assert(userUpdateInfo != null);
return await channel.invokeMethod(
'updateProfile',
userUpdateInfo._updateData,
);
}
/// Links google account with current user and returns [Future<FirebaseUser>]
///
/// throws [PlatformException] when
/// 1. No current user provided (user has not logged in)
/// 2. No google credentials were found for given [idToken] and [accessToken]
/// 3. Google account already linked with another [FirebaseUser]
/// Detailed documentation on possible error causes can be found in [Android docs](https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseUser#exceptions_4) and [iOS docs](https://firebase.google.com/docs/reference/ios/firebaseauth/api/reference/Classes/FIRUser#/c:objc(cs)FIRUser(im)linkWithCredential:completion:)
/// TODO: Throw custom exceptions with error codes indicating cause of exception
Future<FirebaseUser> linkWithGoogleCredential({
@required String idToken,
@required String accessToken,
}) async {
assert(idToken != null);
assert(accessToken != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'linkWithGoogleCredential',
<String, String>{
'idToken': idToken,
'accessToken': accessToken,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<FirebaseUser> linkWithFacebookCredential({
@required String accessToken,
}) async {
assert(accessToken != null);
final Map<dynamic, dynamic> data = await channel.invokeMethod(
'linkWithFacebookCredential',
<String, String>{
'accessToken': accessToken,
},
);
final FirebaseUser currentUser = new FirebaseUser._(data);
return currentUser;
}
Future<Null> _callHandler(MethodCall call) async {
switch (call.method) {
case "onAuthStateChanged":
_onAuthStageChangedHandler(call);
break;
}
return null;
}
void _onAuthStageChangedHandler(MethodCall call) {
final Map<dynamic, dynamic> data = call.arguments["user"];
final int id = call.arguments["id"];
final FirebaseUser currentUser =
data != null ? new FirebaseUser._(data) : null;
_authStateChangedControllers[id].add(currentUser);
}
}