-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
49 lines (42 loc) · 1.37 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const dspaceUrl = "https://une-dspace-backend.glaux.es/server/api";
// Función para obtener CSRF Token
export async function getCsrfToken() {
try {
const response = await fetch(`${dspaceUrl}/security/csrf`, {
method: "GET",
});
if (!response.ok) {
throw new Error(
`La petición fetch no se ha completado correctamente: ${response.statusText}`
);
}
const csrfToken = response.headers.get("DSPACE-XSRF-TOKEN");
const setCookieHeader = response.headers.get("set-cookie");
const xsrfCookie = setCookieHeader ? setCookieHeader.split(";")[0] : null;
if (!csrfToken || !xsrfCookie) {
throw new Error("No se pudo obtener el CSRF Token o la cookie");
}
return { csrfToken, xsrfCookie };
} catch (error) {
console.error("Error:", error.sa);
return null;
}
}
// Función para autenticar
export async function login(username, password) {
const { csrfToken, xsrfCookie } = await getCsrfToken();
const response = await fetch(`${dspaceUrl}/authn/login`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-XSRF-TOKEN": csrfToken,
Cookie: xsrfCookie,
},
body: new URLSearchParams({
user: username,
password: password,
}),
});
const jwtToken = response.headers.get("authorization").split(" ")[1];
return { jwtToken, csrfToken };
}