Skip to content

Instantly share code, notes, and snippets.

@lgs
Forked from kaungmyatlwin/Auth.js
Created May 18, 2019 09:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lgs/7c2cb4c910ab0f071bf63c4509ff6322 to your computer and use it in GitHub Desktop.
Firebase Vuex Auth Module
import firebase from 'firebase';
const state = {
userId: '',
};
const actions = {
login({ commit, state }, { email, password }) {
return new Promise((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
resolve(user);
})
.catch((err) => {
reject(err);
});
});
},
logout({ commit, state }) {
return new Promise((resolve, reject) => {
firebase.auth().signOut()
.then(() => {
commit('LOGOUT');
resolve();
})
.catch((err) => {
reject(err);
});
});
},
checkUserStatus({ commit, state }) {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
commit('SET_USER_ID', user.uid);
resolve(user.uid);
} else {
reject('User is not logged in.');
}
});
});
},
};
const mutations = {
LOGOUT(state, userId) {
state.userId = '';
},
SET_USER_ID(state, userId) {
state.userId = userId;
},
};
export default {
state,
actions,
mutations,
};
<template>
<div>
<span>{{ userId }}</span>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: 'index',
computed: {
...mapState({
userId: state => state.userId,
}),
}
};
</script>
<template>
<form @submit="handleLogin">
<input type="text" placeholder="Email" v-model="email"/>
<input type="password" placeholder="Password" v-model="password"/>
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
name: 'login',
data() {
return {
email: '',
password: '',
};
},
methods: {
handleLogin() {
const email = this.email;
const password = this.password;
this.$store.dispatch('login', { email, password })
.then((user) => {
// do something with user object
})
.catch((err) => {
console.log(err);
})
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment