Added client to call backend authentication logic

This commit is contained in:
Dominic Villemure
2024-03-11 12:16:13 -04:00
parent a4765405c3
commit e7a14fe380
11 changed files with 233 additions and 274 deletions

View 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;
}

View 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);
}
}
});