Skip to content

A Vuex module and Vue Router middleware for authorization.

Notifications You must be signed in to change notification settings

storinka/vuex-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Storinka Vuex Auth

A Vuex module and Vue Router middleware for authorization.

Installation

yarn add @storinka/vuex-auth

Usage

// store/index.js

import { createStore } from "vuex";
import { createAuthStoreModule } from "@storinka/vuex-auth";

export default createStore({
    modules: {
        auth: createAuthStoreModule({
            login: credentials => fetch("auth/login", credentials),
            register: data => fetch("auth/register", data),
            getMe: () => fetch("auth/me"),
            logout: () => fetch("auth/logout"),

            tokenKey: "auth_token",
        }),
    }
});
// App.vue

import { initAuth, setupRouterGuard } from "@storinka/vuex-auth";

export default {
    beforeCreate() {
        initAuth(this.$router, this.$store);
        setupRouterGuard(this.$router, this.$store);
    }
}
// main.js
import store from "./store";

axios.interceptors.request.use(request => {
    request.headers["Authorization"] = `Bearer ${store.state.auth.token}`;

    return request;
});

axios.interceptors.response.use(
    response => response,
    error => {
        if (error.response && error.response.status === 401) {
            store.commit("auth/logout");
        }

        throw error;
    },
);

About

A Vuex module and Vue Router middleware for authorization.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published