Implement authentication in frontend

This commit is contained in:
2025-10-04 15:54:31 +02:00
parent 884d674765
commit dd0fb6f5ba
3 changed files with 48 additions and 21 deletions

View File

@@ -23,20 +23,19 @@
return extractFromErrorFromField("Password", errors.value);
})
function onSubmit(e) {
postLogin(user)
.then((res) => {
if (res.ok) {
res.json().then((json) => login(user.value.username, json));
router.push('/');
return;
} else {
res.json().then((json) => (errors.value = json));
}
})
async function onSubmit(e) {
const res = await postLogin(user)
if (res.ok) {
let json = await res.json();
await login(user.value.username, json);
router.push('/');
return;
} else {
res.json().then((json) => (errors.value = json));
}
}
function login(username, json) {
async function login(username, json) {
useAuthStore().login({username: username, token: json["token"]})
}
</script>

View File

@@ -1,4 +1,5 @@
import { ref } from 'vue'
import { useAuthStore } from './auth.store.js'
const baseUrl = "http://localhost:8080"
@@ -6,10 +7,19 @@ function useFetch(url) {
const data = ref(null);
const error = ref(null);
fetch(url)
.then((res) => res.json())
.then((json) => (data.value = json))
.catch((err) => (error.value = err));
const { user } = useAuthStore();
if (user != null) {
fetch(url, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + user.token
}
})
.then((res) => res.json())
.then((json) => (data.value = json))
.catch((err) => (error.value = err));
}
return { data, error }
}
@@ -23,23 +33,41 @@ export function postBook(book) {
}
export function postLogin(user) {
return genericPostCall('/auth/login', user.value)
return genericPostCallNoAuth('/auth/login', user.value)
}
export function postSignUp(user) {
return genericPostCall('/auth/signup', user.value)
return genericPostCallNoAuth('/auth/signup', user.value)
}
export function genericPostCall(apiRoute, object) {
export function genericPostCallNoAuth(apiRoute, object) {
return fetch(baseUrl + apiRoute, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
},
body: JSON.stringify(object)
})
}
export function genericPostCall(apiRoute, object) {
const { user } = useAuthStore();
if (user != null) {
return fetch(baseUrl + apiRoute, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': authorizationHeader()
},
body: JSON.stringify(object)
})
}
else {
return Promise.resolve();
}
}
export function extractFromErrorFromField(fieldName, errors) {
if (errors === null || !('field' in errors)) {
return "";

View File

@@ -8,7 +8,7 @@ export const useAuthStore = defineStore('auth', {
returnUrl: null
}),
actions: {
login(user) {
async login(user) {
this.user = user;
localStorage.setItem('user', JSON.stringify(user));
},