Implement authentication in frontend
This commit is contained in:
@@ -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 "";
|
||||
|
||||
Reference in New Issue
Block a user