Skip to content

Instantly share code, notes, and snippets.

@rico
Last active February 11, 2018 14:42
Show Gist options
  • Save rico/57b1b5a6af51ff20eee0c9ee4a6ed8e3 to your computer and use it in GitHub Desktop.
Save rico/57b1b5a6af51ff20eee0c9ee4a6ed8e3 to your computer and use it in GitHub Desktop.
vue-authenticate #110
// File: store/modules/auth.js
import authProvider from '../../providers/authenticate'
import http from '../../providers/http'
// You can use it as state property
const state = {
isAuthenticated: false,
user: null
};
const getters = {
isAuthenticated () {
return authProvider.isAuthenticated()
},
user () {
return state.user
}
};
const mutations = {
isAuthenticated (state, payload) {
state.isAuthenticated = payload.isAuthenticated
},
user (state, payload) {
state.user = payload;
}
};
const actions = {
// Perform VueAuthenticate login using Vuex actions
login (context, payload) {
return new Promise((resolve, reject) => {
authProvider.login(payload.credentials).then((response) => {
context.commit('isAuthenticated', {
isAuthenticated: authProvider.isAuthenticated()
});
http.get('/auth/user')
.then(function (response) {
context.commit('user', response.data);
resolve();
});
})
.catch((err) => {
reject(err);
});
});
}
};
export default {
state,
getters,
actions,
mutations
}
// File: providers/authenticate.js
import Vue from 'vue'
import { VueAuthenticate } from 'vue-authenticate'
import http from "./http";
export default new VueAuthenticate(Vue.prototype.$http, {
loginUrl: 'auth/user/login',
tokenName: 'access_token'
});
// File: providers/http.js
import Vue from "vue";
import axios from "axios/index";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
Vue.axios.defaults.baseURL = 'http://local.test';
export default Vue.axios;
// File: store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
import auth from './modules/auth'
export default new Vuex.Store({
modules: {
auth
},
});
// Component: Login.vue
data: () => ({
credentials: {
username: '',
password: '',
},
errors: {},
loading:false
}),
methods : {
login: function () {
this.errors = {};
this.loading = true;
this.$store.dispatch('login', {credentials: this.credentials})
.then(() => {
this.loading = false;
this.$router.push('/');
})
.catch((e) => {
if (e.response.status == 422) {
this.errors = e.response.data.errors;
} else if (e.response.status == 401) {
this.errors.message = 'Kein Benutzer mit diesen Angaben gefunden.'
}
this.loading = false;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment