HackHeaders / FrontEnd

0 stars 0 forks source link

FEAT: Create auth method in Vue #43

Closed AnthonyLoche closed 2 months ago

AnthonyLoche commented 2 months ago

📃 Description 📃:

Checklist ✅:

⚠️ Notes (IMPORTANT) ⚠️:

🗂️ Archives 🗂️:

export default class AuthService { async postUserToken(token) { const response = await axios.get('/users/me/', { headers: { Authorization: Bearer ${token}, }, }); return response.data; } }

- Store Example: 
```js
import { ref } from 'vue';
import { defineStore } from 'pinia';

import AuthService from '@/services/auth';
const authService = new AuthService();

export const useAuthStore = defineStore('auth', () => {
  const user = ref({});

  async function setToken(token) {
    user.value = await authService.postUserToken(token);
  }

  function unsetToken() {
    user.value = {};
  }

  return { user, setToken, unsetToken };
});

HomeView Example:

<script setup>
import ProductList from '@/components/ProductList.vue';

import { onMounted } from 'vue';
import { PassageUser } from '@passageidentity/passage-elements/passage-user';
import { useAuthStore } from '@/stores/auth';

const authStore = useAuthStore();

const getUserInfo = async () => {
  try {
    const authToken = localStorage.getItem('psg_auth_token');
    const passageUser = new PassageUser(authToken);
    const user = await passageUser.userInfo(authToken);
    if (user) {
      await authStore.setToken(authToken);
    } else {
      authStore.unsetToken();
    }
  } catch (error) {
    authStore.unsetToken();
  }
};

onMounted(() => {
  getUserInfo();
});
</script>

<template>
  <product-list />
</template>

plugin/axios.js:


import axios from 'axios';

const api = axios.create({
  baseURL: 'http://127.0.0.1:8000/'
})

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('psg_auth_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);