hurricane/security_camera/resources/cloud_server/public/src/boot/firebase/Authentication.js

import firebase from 'firebase/app'
import 'firebase/auth'
import { b64DecodeUnicode } from 'helpers/Base64'
import axios from 'axios/index'
import { store } from 'store'
import { FUNCTIONS_URL } from 'firebaseConfig/firebase-config'
export default class Authentication {
/*********************************************************************************************************/
constructor (app) {
const self = this
this.app = app
this.auth = app.auth()
this.auth.onAuthStateChanged((user) => self._onAuthStateChanged(self, user))
}
/*********************************************************************************************************/
register (code) {
this.unregister()
let data = {
code
}
logger.debug(`Registration info: ${JSON.stringify(data)}`)
return axios.post(FUNCTIONS_URL + '/registerDevice', data)
.then((res) => {
if (res.status === 200) {
return firebase.auth().signInWithCustomToken(res.data.token).then(() => {
return true
})
}
throw new Error(`Registration failed, err: ${res.data}`)
}).catch((error) => {
if (error['response']) {
const resp = error.response
return firebase.Promise.reject(new Error(`(${resp.status}) ${resp.data}`))
} else {
return firebase.Promise.reject(error)
}
})
}
/*********************************************************************************************************/
unregister () {
store.dispatch('firebase/logout')
this.app.backend.db.stopWatching()
this.auth.signOut()
}
/********************************
* Private Methods
********************************/
/*********************************************************************************************************/
_onAuthStateChanged (self, user) {
if (user && self.auth.currentUser) {
logger.debug('Logged in')
self.auth.currentUser.getIdToken().then((token) => {
const payload = JSON.parse(b64DecodeUnicode(token.split('.')[1]))
if (payload.did) {
logger.debug(`did: ${payload.did}`)
logger.debug(`uuid: ${payload.uuid}`)
store.commit('firebase/deviceId', payload.did)
} else {
logger.warn('Token does not contain a deviceId')
store.commit('firebase/deviceId', false)
}
}).catch((err) => {
logger.warn(`Failed to retrieve login token, err:${err.description || err.message || err.toString()}`)
store.commit('firebase/deviceId', false)
})
} else {
logger.debug('Not logged in')
store.commit('firebase/deviceId', false)
}
}
}