codigo de login front

This commit is contained in:
2025-11-14 18:25:57 -03:00
parent 4545252bd2
commit ccebc7934c
7 changed files with 163 additions and 25 deletions

37
src/lib/hooks/login.ts Normal file
View File

@@ -0,0 +1,37 @@
import { apiBase } from "@/stores/url";
import type { LoginDto } from "../../types";
import { sesionStore } from "@/stores/usuario";
import { goto } from "$app/navigation";
export async function login(e:FormDataEvent,dto: LoginDto, callbackfn:()=>void){
e.preventDefault();
if (dto.password == "" || dto.username == "") return;
try {
const { subscribe } = apiBase;
let baseUrl: string = '';
subscribe((value) => {
baseUrl = value;
})();
const req = await fetch(baseUrl + "/api/auth/login", {
method: "POST",
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify(dto)
});
if (req.ok) {
const token = await req.json();
sesionStore.set({ accessToken: token })
goto("/")
} else {
callbackfn();
}
} catch {
callbackfn();
console.error("fallo al intentar alcanzar el servidor")
}
}

39
src/lib/hooks/register.ts Normal file
View File

@@ -0,0 +1,39 @@
import { apiBase } from "@/stores/url";
import { sesionStore } from "@/stores/usuario";
import { goto } from "$app/navigation";
import type { RegisterDto } from "../../types";
export async function register(e:FormDataEvent,dto: RegisterDto, callbackfn:()=>void){
e.preventDefault();
if (dto.password == "" || dto.username == "" ||
!dto.email?.includes("@") || dto.displayName=="") return;
try {
const { subscribe } = apiBase;
let baseUrl: string = '';
subscribe((value) => {
baseUrl = value;
})();
const req = await fetch(baseUrl + "/api/auth/register", {
method: "POST",
headers:{
"Content-Type": "application/json"
},
body: JSON.stringify(dto)
});
if (req.ok) {
const data= await req.json();
goto("/login", { state: {
message: data.message,
}});
} else {
callbackfn();
}
} catch {
callbackfn();
console.error("fallo al intentar alcanzar el servidor")
}
}