1
|
|
|
'use strict'; |
2
|
|
|
|
3
|
|
|
let firebase = require('firebase'); |
4
|
|
|
let admin = require('firebase-admin'); |
5
|
|
|
|
6
|
|
|
/** Class representing a firebase authentication */ |
7
|
|
|
class FirebaseAuth { |
8
|
|
|
/** |
9
|
|
|
* Creates a firebaseAuth |
10
|
|
|
* @params {Object} firebaseConfig - The config for firebase |
11
|
|
|
* @params {Object} serviceKey - The service account for firebase |
12
|
|
|
*/ |
13
|
|
|
constructor(firebaseConfig, serviceKey, nameOfAdmin) { |
14
|
|
|
this.firebase = firebase; |
15
|
|
|
this.admin = admin; |
16
|
|
|
this.firebase.initializeApp(firebaseConfig); |
17
|
|
|
|
18
|
|
|
if (nameOfAdmin) |
|
|
|
|
19
|
|
|
this.admin.initializeApp({credential: this.admin.credential.cert(serviceKey)}, nameOfAdmin); |
|
|
|
|
20
|
|
|
else |
|
|
|
|
21
|
|
|
this.admin.initializeApp({credential: this.admin.credential.cert(serviceKey)}); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Signing in an user and tries to get their id token. |
26
|
|
|
* |
27
|
|
|
* @param {String} email - Email for the account |
28
|
|
|
* @param {String} password - Password for the account |
29
|
|
|
* @promise {String} Returns a string with the id token of the user. |
30
|
|
|
* @rejects {Object} Returns an object with errors if rejected |
31
|
|
|
*/ |
32
|
|
|
signIn(email, password) { |
33
|
|
|
return this.firebase.auth().signInWithEmailAndPassword(email, password) |
34
|
|
|
.then(() => { |
35
|
|
|
return this.getIdToken(); |
36
|
|
|
}) |
37
|
|
|
.catch((error) => { |
38
|
|
|
throw { code: error.code, message: error.message }; |
39
|
|
|
}); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Gets the id token from the logged in user. |
44
|
|
|
* |
45
|
|
|
* @promise {String} Returns a string with the id token of the user. |
46
|
|
|
* @rejects {Object} Returns an object with errors if rejected |
47
|
|
|
*/ |
48
|
|
|
getIdToken() { |
49
|
|
|
return this.firebase.auth().currentUser.getIdToken(true) |
50
|
|
|
.then((idToken) => { |
51
|
|
|
return idToken; |
52
|
|
|
}).catch((error) => { |
53
|
|
|
throw { code: error.code, message: error.message }; |
54
|
|
|
}); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Verify the id token of an user. |
59
|
|
|
* |
60
|
|
|
* @promise {Boolean} Returns true if successful |
61
|
|
|
* @rejects {Object} Returns an object with errors if rejected |
62
|
|
|
*/ |
63
|
|
|
authToken(idToken) { |
64
|
|
|
return this.admin.auth().verifyIdToken(idToken) |
65
|
|
|
.then(() => { |
66
|
|
|
return true; |
67
|
|
|
}).catch((error) => { |
68
|
|
|
throw { code: error.code, message: error.message }; |
69
|
|
|
}); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
module.exports = FirebaseAuth; |
74
|
|
|
|