I have SPA application on Vue.js + Laravel. Authorization logic, completely delegated to Laravel app. However, i need check auth status, when routing has changed. I create small class, which responsible for it.
export default {
user: {
authenticated : false
},
check: function(context) {
context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) =>{
console.log(response)
});
}
Within the component has a method that is called when a change url.
beforeRouteEnter (to, from, next) {
next(vm =>{
Auth.check(vm);
if (!Auth.user.authenticated) {
next({path:'/login'});
}
})
}
Function next() given Vue app instance, then check user object. If user false, next() call again for redirect to login page. All it works, but only when the page is already loaded. If i'll reload /account page, there is a redirect to /login page, because request to Api not completed yet, but code will continue execute. Any idea?
Quite simple to do, you need to make your code work asynchronously and hold routing before request is completed.
export default {
user: {
authenticated : false
},
check: function(context) {
return context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) => {
console.log(response)
});
}
}
then
beforeRouteEnter (to, from, next) {
next(vm => {
Auth.check(vm).then(() => {
if (!Auth.user.authenticated) {
next({path:'/login'});
} else {
next()
}
}
})
}
Other pro tips
Display some loading indicator when loading so your application doesn't seem to freeze (you can use global router hooks for that)
If you are using vue-resource, consider using interceptors (perhaps in addition to the routing checks)
Consider using router.beforeEach so that you don't have to copy-paste beforeRouteEnter to every component
Done. Need to return promise like that
check: function(context) {
return context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) =>{
console.log(response)
});
}
and then
beforeRouteEnter (to, from, next) {
Auth.check().then(()=>{
if(!Auth.user.authenticated)
next({path:'/login'})
else
next();
})
}
Related
Can anyone advise on this issue?
I've got a Laravel app with a Vue front-end, connecting to the API using Laravel Sanctum. (within the same application) I'm trying to set up the authentication guards so routes can only be accessed after authentication with the API.
I'm connecting through the state action like so:
async getAuthenticatedUser({ commit }, params) {
await axios.get('api/auth-user', { params })
.then(response => {
commit('SET_AUTHENTICATED', true)
commit('SET_AUTHENTICATED_USER', response.data)
localStorage.setItem('is-authenticated', 'true')
return Promise.resolve(response.data)
})
.catch(error => {
commit('SET_AUTHENTICATED', false)
commit('SET_AUTHENTICATED_USER', [])
localStorage.removeItem('is-authenticated')
return Promise.reject(error.response.data)
})
},
The state authenticated property is set as follows:
const state = () => ({
authenticated: localStorage.getItem('is-authenticated') || false,
authUser: [],
})
I have the following guard checking the auth. If I'm not signed in the app correctly redirects me back to the login screen when I access a route with the requiresAuth attribute.
However when I attempt to log in, I get Redirected when going from "/login" to "/dashboard" via a navigation guard.
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/login')
}
if (to.matched.some((record) => record.meta.requiresVisitor)) {
if (! store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/dashboard')
}
next()
})
If it's safe to ignore, and you are using vue-router ^3.4.0, you can do:
import VueRouter from 'vue-router'
const { isNavigationFailure, NavigationFailureType } = VueRouter
...
this.$router.push(fullPath).catch(error => {
if (!isNavigationFailure(error, NavigationFailureType.redirected)) {
throw Error(error)
}
})
I have a async problem with my Vuejs/Laravel App.
If a user is connected i have in vuex : my state user and a state token. I set this token in the localStorage and with that i can relogin him if my user F5 (refresh page).
There is my store (namespaced:auth) :
export default {
namespaced: true,
state: {
token: null,
user: null
},
getters: {
authenticated(state){
return state.token && state.user;
},
user(state){
return state.user;
}
},
mutations: {
SET_TOKEN(state, token){
state.token = token;
},
SET_USER(state, data){
state.user = data;
},
},
actions: {
async login({ dispatch }, credentials){
let response = await axios.post(`/api/auth/connexion`, credentials);
dispatch('attempt', response.data.token);
}
,
async attempt({ commit, state }, token) {
if(token){
commit('SET_TOKEN', token);
}
if (!state.token){
return
}
try{
let response = await axios.get(`/api/auth/me`);
commit('SET_USER', response.data);
console.log('Done')
}
catch(err){
commit('SET_TOKEN', null);
commit('SET_USER', null);
}
}
}
}
My app.js, i do that for relog my current user :
store.dispatch('auth/attempt', localStorage.getItem('token'));
And for finish on route in router :
{
name: 'Login',
path: '/',
component: Login,
beforeEnter: (to, from, next) => {
console.log('Getter in router : ' + store.getters['auth/authenticated']);
if (!store.getters['auth/authenticated']){
next()
}else {
return next({
name: 'Home'
})
}
}
}
Where is the problem, if i call in a Home.vue my getter "authenticated" is work fine (true if user connect and false if not).
But in my router is take all time default value set in store (null). I know why is because if i reload my page for 0.5s the store state is null and after that the localStorage is learn and my user and token is created.
What i want (i think) is the router wait my actions attempt and after that he can do check.
I have follow a tutoriel https://www.youtube.com/watch?v=1YGWP-mj6nQ&list=PLfdtiltiRHWF1jqLcNO_2jWJXj9RuSDvY&index=6
And i really don't know what i need to do for my router work fine =(
Thanks a lot if someone can explain me that !
Update :
If i do that is work :
{
name: 'Login',
path: '/',
component: Login,
beforeEnter:async (to, from, next) => {
await store.dispatch('auth/attempt', localStorage.getItem('token'));
if (!store.getters['auth/authenticated']){
next()
}else {
return next({
name: 'Home'
})
}
}
But i want to understand what i really need to do because that is not a clear way is really trash.
Update2:
Maybe i found the best solution if someone have other way i take it.
{
name: 'Home',
path: '/accueil',
component: Home,
beforeEnter: (to, from, next) => {
store.dispatch('auth/attempt', localStorage.getItem('token')).then((response) => {
if (!store.getters['auth/authenticated']){
return next({
name: 'Login'
})
}else {
next();
}
});
}
}
I answer more clearly how easily wait the store !
Before in my app.js i have this :
store.dispatch('auth/attempt', localStorage.getItem('token'));
Is set for normaly every reload do that but if i put a console.log in, i see the router is execute and after the action 'attempt' is execute.
So delete this line in app.js and you can add a .then() after !
router.beforeEach((to, from, next) => {
store.dispatch('auth/attempt', localStorage.getItem('token')).then(() =>{
if (store.getters['auth/authenticated']){
next();
}else {
//something other
}
})
})
With that i have the same line code but i can say wait action "attempt" to my router.
I'm not sur is the best way obviously. But is work and i think is not a bad way !
all!
I need to get axios Promise reject in my vue component using vuex.
I have serviceApi.js file:
export default {
postAddService(service) {
return axios.post('api/services', service);
}
}
my action in vuex:
actions: {
addService(state, service) {
state.commit('setServiceLoadStatus', 1);
ServicesAPI.postAddService(service)
.then( ({data}) => {
state.commit('setServiceLoadStatus', 2);
})
.catch(({response}) => {
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
return Promise.reject(response); // <= can't catch this one
});
}
}
and in my vue component:
methods: {
addService() {
this.$store.dispatch('addService', this.service)
.then(() => {
this.forceLeave = true;
this.$router.push({name: 'services'});
this.$store.dispatch('snackbar/fire', {
text: 'New Service has been added',
color: 'success'
}).then()
})
.catch((err) => { // <== This never hapens
this.$store.dispatch('snackbar/fire', {
text: err.response.data.message || err.response.data.error,
color: 'error'
}).then();
});
}
When i use axios directly in my component all work well. I get both success and error messages.
But when i work using vuex i can't get error message in component, hoever in vuex action console.log prints what i need.
I'm always getting only successfull messages, even when bad things hapen on beckend.
How can i handle this situation using vuex ?
Wellcome to stackoverflow. One should not want to expect anything back from an action. After calling an action. Any response should be set/saved in the state via mutations. So rather have an error property on your state. Something like this should work
actions: {
async addService(state, service) {
try {
state.commit('setServiceLoadStatus', 1);
const result = await ServicesAPI.postAddService(service);
state.commit('setServiceLoadStatus', 2);
} catch (error) {
state.commit("error", "Could not add service");
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
}
}
}
And in your component you can just have an alert that listens on your state.error
Edit: Only time you are going expect something back from an action is if you want to call other actions synchronously using async /await. In that case the result would be a Promise.
I am trying to build an availability carousel. It will show the days of the week, and what time someone is available. I am using Laravel and vue.js. I have done the web api, and I can get the data object following the route
Route::group(['prefix' => '/{area}'], function () {
Route::get('/{tutor}/availability','Tutor\AvailabilityController#show');
});
with this in my availability controller
public function show(Request $request, Area $area, Tutor $tutor)
{
$availability = $tutor->availability()->get();
return response()->json([
'data' => $availability
], 200);
}
That all works.
But when I try and pull it into Vue, nothing shows up. I can't seem to figure out what I might be missing.
I pulled the vue component into blade using the following, and passing in the area and tutor id
<availability area-id="{{ $area->slug }}" tutor-id="{{ $tutor->slug }}">
</availability>
and in Availability.vue, I think where I am going wrong is pulling the data in with props, but I am really not sure anymore.
<script>
$(document).ready(function() {
$("#availability").owlCarousel();
});
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
console.log(response.json());
});
}
},
ready () {
this.getAvailability();
}
}
</script>
Thank you for the help.
Axios response object has data field which contains the response from the server. To get the data use
response.data
Also for Vue 2.0 components use mounted instead of ready for when the component is ready. If you are only loading data from the server (and not manipulating the DOM) you can use created instead.
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
var that = this;
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability')
.then((response) => {
console.log(response.data); // should print {data: availability_object}
// Set this component's availability to response's availability
that.availability = response.data.data;
//OR
//Add response's availability to the components' availability
that.availability.push(response.data.data);
});
}
},
mounted () {
this.getAvailability();
}
}
</script>
I am using laravel and vuejs for my app and every user has a role. Now I want to restrict users to access vue routes by their roles by redirecting them to another route if they can't access the page. I am using beforeRouteEnter for vuejs but I am getting an error
data() {
return{
role: '',
}
},
mounted() {
axios.post('/getRole')
.then((response) => this.role = response.data)
.catch((error) => this.errors = error.response.data.errors)
},
beforeRouteEnter (to, from, next) {
if (this.role === 'Admin') {
next()
}else {
next('/')
}
}
I am getting this error
app.js:72652 TypeError: Cannot read property 'role' of undefined
at beforeRouteEnter (app.js:90653)
at routeEnterGuard (app.js:72850)
at iterator (app.js:72690)
at step (app.js:72464)
at runQueue (app.js:72472)
at app.js:72726
at step (app.js:72461)
at app.js:72465
at app.js:72711
at app.js:72539
you can't use this in beforeRouteEnter function,because before the route updates, your component's vm does not exist.
in consideration of you put role information in your vm, you can use next to get your vm:
beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}
actually,you should use the Global Router Guard ,and put your role information in global area,so that your can redirect your routing before your target component created