Added client to call backend authentication logic
This commit is contained in:
34
src/plugins/clientPlugin.js
Normal file
34
src/plugins/clientPlugin.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import axios from "axios";
|
||||
import { inject } from 'vue';
|
||||
|
||||
const clientKey = Symbol('client');
|
||||
|
||||
export default {
|
||||
install: (app) => {
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: 'https://localhost:5001/',
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
axiosInstance.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('jwt');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
}, (error) => {
|
||||
return Promise.reject(error);
|
||||
});
|
||||
|
||||
app.provide(clientKey, axiosInstance);
|
||||
console.log("client provided");
|
||||
}
|
||||
};
|
||||
|
||||
export function useClient() {
|
||||
const client = inject(clientKey);
|
||||
if (!client) {
|
||||
throw new Error('Axios instance is not provided');
|
||||
}
|
||||
return client;
|
||||
}
|
||||
55
src/plugins/store/authStore.js
Normal file
55
src/plugins/store/authStore.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
const baseUrl = '/api/Users';
|
||||
|
||||
export const useAuthStore = defineStore({
|
||||
id: 'auth',
|
||||
state: () => ({
|
||||
user: null,
|
||||
refreshTokenTimeout: null
|
||||
}),
|
||||
actions: {
|
||||
async login(client, email, password) {
|
||||
const requestBody = {
|
||||
email: email,
|
||||
password: password
|
||||
};
|
||||
try {
|
||||
const response = await client.post(`${baseUrl}/login`, requestBody)
|
||||
this.user = {
|
||||
accessToken: response.data.accessToken,
|
||||
refreshToken: response.data.refreshToken,
|
||||
email: email
|
||||
}
|
||||
localStorage.setItem('jwt', this.user.accessToken);
|
||||
this.startRefreshTokenTimer();
|
||||
} catch (error) {
|
||||
throw new Error('Login failed.')
|
||||
}
|
||||
|
||||
|
||||
|
||||
},
|
||||
logout() {
|
||||
localStorage.setItem('jwt', '');
|
||||
this.stopRefreshTokenTimer();
|
||||
this.user = null;
|
||||
|
||||
},
|
||||
async refreshToken(client) {
|
||||
const response = await client.post(`${baseUrl}/refresh`, {});
|
||||
this.user.accessToken = response.accessToken;
|
||||
localStorage.setItem('jwt', this.user.accessToken);
|
||||
|
||||
|
||||
this.startRefreshTokenTimer();
|
||||
},
|
||||
startRefreshTokenTimer() {
|
||||
const timeout = 50 * 1000;
|
||||
this.refreshTokenTimeout = setTimeout(this.refreshToken, timeout);
|
||||
},
|
||||
stopRefreshTokenTimer() {
|
||||
clearTimeout(this.refreshTokenTimeout);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user