Completed
Push — master ( bf15fc...a16eac )
by david
03:53 queued 02:02
created

index.js (1 issue)

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) {
14
		this.firebase = firebase;
15
		this.admin = admin;
16
		this.firebase.initializeApp(firebaseConfig);
17
		this.admin.initializeApp({credential: this.admin.credential.cert(serviceKey)}, 'admin-auth');
0 ignored issues
show
This line exceeds the maximum configured line length of 100.
Loading history...
18
	}
19
20
	/**
21
	 * Signing in an user and tries to get their id token.
22
	 *
23
	 * @param  {String} email - Email for the account
24
	 * @param  {String} password - Password for the account
25
	 * @promise {String} Returns a string with the id token of the user.
26
	 * @rejects {Object} Returns an object with errors if rejected
27
	 */
28
	signIn(email, password) {
29
		return this.firebase.auth().signInWithEmailAndPassword(email, password)
30
			.then(() => {
31
				return this.getIdToken();
32
			})
33
			.catch((error) => {
34
				throw { code: error.code, message: error.message };
35
			});
36
	}
37
38
	/**
39
	 * Gets the id token from the logged in user.
40
	 *
41
	 * @promise {String} Returns a string with the id token of the user.
42
	 * @rejects {Object} Returns an object with errors if rejected
43
	 */
44
	getIdToken() {
45
		return this.firebase.auth().currentUser.getIdToken(true)
46
			.then((idToken) => {
47
				return idToken;
48
			}).catch((error) => {
49
				throw { code: error.code, message: error.message };
50
			});
51
	}
52
53
	/**
54
	 * Verify the id token of an user.
55
	 *
56
	 * @promise {Boolean} Returns true if successful
57
	 * @rejects {Object} Returns an object with errors if rejected
58
	 */
59
	authToken(idToken) {
60
		return this.admin.auth().verifyIdToken(idToken)
61
			.then(() => {
62
				return true;
63
			}).catch((error) => {
64
				throw { code: error.code, message: error.message };
65
			});
66
	}
67
}
68
69
module.exports = FirebaseAuth;
70