Skip to content

Instantly share code, notes, and snippets.

@Ebycow
Created July 7, 2019 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ebycow/8dcb1da6cab7e63087c1b2724e65515d to your computer and use it in GitHub Desktop.
Save Ebycow/8dcb1da6cab7e63087c1b2724e65515d to your computer and use it in GitHub Desktop.
npm i firebase firebase-admin
import * as admin from 'firebase-admin';
const serviceAccount = require('firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://< project-name >.firebaseio.com"
});
async function authorize(req: Request, res: Response, next: NextFunction) {
try {
const token = req.headers.authorization;
if(token !== undefined){
const decodedToken = await admin.auth().verifyIdToken(token.split(' ')[1]);
const userId = decodedToken.uid;
console.log(userId);
next();
} else {
throw new Error();
}
} catch (error) {
res.status(204).send('need authorization');
}
}
<template>
<div class="container">
<div v-if="user">{{ user }}</div>
<div v-else>offline</div>
mail: <input type="text" v-model="mail">
pass: <input type="text" v-model="password">
<button v-on:click="login">login</button>
<button v-on:click="logout">logout</button>
<hr>
name: <input type="text" v-model="name">
<button v-on:click="register">register</button>
</div>
</template>
<script>
import firebase from '../plugins/firebase';
import axios from '@nuxtjs/axios';
export default {
data () {
return {
user : null,
mail : "",
password : "",
name : ""
}
},
methods : {
async login() {
const user = await firebase.auth().signInWithEmailAndPassword(this.mail, this.password);
this.getUser();
},
async logout() {
try {
await firebase.auth().signOut();
this.user = null;
} catch (error) {
console.error(error);
}
},
async getUser() {
const token = await firebase.auth().currentUser.getIdToken();
console.log(token)
const user = await this.$axios({
method : 'GET',
url : './api/user',
headers : { 'Authorization' : `Bearer ${token}` }
});
this.user = user.data;
}
}
}
</script>
<style>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment