|
| 1 | +<script setup> |
| 2 | +import { ref } from 'vue'; |
| 3 | +import axios from 'axios'; |
| 4 | +import { useRouter } from 'vue-router'; |
| 5 | +import { useAuthStore } from '@/stores/auth'; |
| 6 | +
|
| 7 | +const username = ref('michael'); |
| 8 | +const errorMessage = ref(null); |
| 9 | +const isLoading = ref(false); |
| 10 | +
|
| 11 | +const authStore = useAuthStore(); |
| 12 | +const router = useRouter(); |
| 13 | +
|
| 14 | +const handleLogin = async () => { |
| 15 | + isLoading.value = true; |
| 16 | + errorMessage.value = null; |
| 17 | +
|
| 18 | + try { |
| 19 | + console.log("Trying to login") |
| 20 | + const response = await axios.post('http://localhost:8000/auth/login', { |
| 21 | + username: username.value, |
| 22 | + }); |
| 23 | + console.log(response) |
| 24 | +
|
| 25 | + const { access_token, refresh_token, user } = response.data; |
| 26 | +
|
| 27 | + authStore.setAuth({ |
| 28 | + accessToken: access_token, |
| 29 | + refreshToken: refresh_token, |
| 30 | + user, |
| 31 | + }); |
| 32 | +
|
| 33 | + console.log(authStore.accessToken); |
| 34 | +
|
| 35 | + await router.push({ name: 'home' }); |
| 36 | +
|
| 37 | + } catch (error) { |
| 38 | + if (error.response?.data?.detail) { |
| 39 | + errorMessage.value = error.response.data.detail; |
| 40 | + } else { |
| 41 | + errorMessage.value = 'An unexpected error occurred.'; |
| 42 | + } |
| 43 | + console.error('Login failed:', error); |
| 44 | + } finally { |
| 45 | + isLoading.value = false; |
| 46 | + } |
| 47 | +}; |
| 48 | +</script> |
| 49 | +
|
| 50 | +<template> |
| 51 | + <div> |
| 52 | + <v-btn @click="handleLogin" :disabled="isLoading || authStore.isAuthenticated"> |
| 53 | + {{ isLoading ? 'Logging in...' : 'Login' }} |
| 54 | + </v-btn> |
| 55 | + </div> |
| 56 | +</template> |
0 commit comments