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
+22 -10
View File
@@ -1,32 +1,44 @@
<script lang="ts"> <script lang="ts">
import { Button } from '$lib/components/ui/button/index.js'; import { Button } from '$lib/components/ui/button/index.js';
import * as Card from '$lib/components/ui/card/index.js'; import * as Card from '../components/ui/card';
import * as Field from '$lib/components/ui/field/index.js'; import * as Field from '$lib/components/ui/field';
import { Input } from '$lib/components/ui/input/index.js'; import { Input } from '$lib/components/ui/input/index.js';
import type { ComponentProps } from 'svelte'; import type { RegisterDto } from '../../types';
import { register } from '@/hooks/register';
let {showAlert = $bindable() } = $props();
const setAlert = () => showAlert = true;
let dto: RegisterDto = $state({password: "", username: "", email:"", displayName: ""});
let { ...restProps }: ComponentProps<typeof Card.Root> = $props();
</script> </script>
<Card.Root {...restProps}> <Card.Root>
<Card.Header> <Card.Header>
<Card.Title>Registrarse</Card.Title> <Card.Title>Registrarse</Card.Title>
<hr /> <hr />
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
<form> <form onsubmit={(e)=>register(e, dto, setAlert)}>
<Field.Group> <Field.Group>
<Field.Field> <Field.Field>
<Field.Label for="name">Nombre Completo</Field.Label> <Field.Label for="name">Nombre de Usuario</Field.Label>
<Input id="name" type="text" placeholder="Juan Pepe" required /> <Input id="name" bind:value={dto.username} type="text" placeholder="JPepe" required />
</Field.Field> </Field.Field>
<Field.Field>
<Field.Label for="name">Nombre Visible</Field.Label>
<Input type="text" bind:value={dto.displayName} placeholder="Juan Pepe" required />
</Field.Field>
<Field.Field> <Field.Field>
<Field.Label for="email">Email</Field.Label> <Field.Label for="email">Email</Field.Label>
<Input id="email" type="email" placeholder="m@ejemplo.com" required /> <Input id="email" type="email" bind:value={dto.email} placeholder="m@ejemplo.com" required />
</Field.Field> </Field.Field>
<Field.Field> <Field.Field>
<Field.Label for="password">Contraseña</Field.Label> <Field.Label for="password">Contraseña</Field.Label>
<Input id="password" type="password" required /> <Input id="password" type="password" bind:value={dto.password} required />
<Field.Description>Debe de tener por lo menos 8 caracteres.</Field.Description> <Field.Description>Debe de tener por lo menos 8 caracteres.</Field.Description>
</Field.Field> </Field.Field>
<Field.Field> <Field.Field>
@@ -3,7 +3,13 @@
import * as Card from '@/components/ui/card'; import * as Card from '@/components/ui/card';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { FieldGroup, Field, FieldLabel, FieldDescription } from '@/components/ui/field'; import { FieldGroup, Field, FieldLabel, FieldDescription } from '@/components/ui/field';
const id = $props.id(); import type { LoginDto } from '../../../../types';
import { login } from '@/hooks/login';
let {id, showAlert = $bindable() } = $props();
let dto: LoginDto = $state({password: "", username: ""});
const setAlert = () => showAlert = true;
</script> </script>
<Card.Root class="mx-auto w-full max-w-sm"> <Card.Root class="mx-auto w-full max-w-sm">
@@ -12,11 +18,11 @@
<Card.Description>ingrese su usuario para logearse en la cuenta</Card.Description> <Card.Description>ingrese su usuario para logearse en la cuenta</Card.Description>
</Card.Header> </Card.Header>
<Card.Content> <Card.Content>
<form> <form onsubmit="{(e)=>login(e,dto, setAlert)}">
<FieldGroup> <FieldGroup>
<Field> <Field>
<FieldLabel for="email-{id}">Usuario</FieldLabel> <FieldLabel for="email-{id}">Usuario</FieldLabel>
<Input id="email-{id}" type="email" placeholder="m@example.com" required /> <Input bind:value={dto.username} type="text" placeholder="nombre de usuario" required />
</Field> </Field>
<Field> <Field>
<div class="flex items-center"> <div class="flex items-center">
@@ -25,7 +31,7 @@
Te Olvidaste la contraseña? Te Olvidaste la contraseña?
</a> </a>
</div> </div>
<Input id="password-{id}" type="password" required /> <Input bind:value={dto.password} type="password" required />
</Field> </Field>
<Field> <Field>
<Button type="submit" class="w-full">Login</Button> <Button type="submit" class="w-full">Login</Button>
+37
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
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")
}
}
+7 -7
View File
@@ -1,11 +1,11 @@
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import type { User } from '../../types'; import type { Sesion } from '../../types';
export const currentUser = writable<User | null>(null); export const currentSesion = writable<Sesion| null>(null);
export const userStore = { export const sesionStore = {
subscribe: currentUser.subscribe, subscribe: currentSesion.subscribe,
set: currentUser.set, set: currentSesion.set,
update: currentUser.update, update: currentSesion.update,
reset: () => currentUser.set(null) reset: () => currentSesion.set(null)
}; };
+31 -3
View File
@@ -1,9 +1,37 @@
<script> <script lang="ts">
import * as Alert from '@/components/ui/alert';
import LoginForm from '@/components/ui/login-form/login-form.svelte'; import LoginForm from '@/components/ui/login-form/login-form.svelte';
</script> import AlertCircleIcon from "@lucide/svelte/icons/alert-circle";
import { fade } from 'svelte/transition';
let showAlert: boolean = $state(false);
$effect(()=>{
resetAlert();
});
async function resetAlert (){
if (showAlert == true){
await new Promise(res => setTimeout(res, 2000));
showAlert=false;
}
}
</script>
<div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10"> <div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10">
<LoginForm /> <div class="w-full max-w-sm">
<LoginForm bind:showAlert={showAlert} id="1" />
{#if showAlert}
<div class="mt-2" transition:fade>
<Alert.Root variant="destructive">
<AlertCircleIcon />
<Alert.Title>No se pudo iniciar sesion</Alert.Title>
<Alert.Description>
Revise su usuario o contraseña
</Alert.Description>
</Alert.Root>
</div>
{/if} {/if}
</div> </div>
+16
View File
@@ -25,3 +25,19 @@ export interface User {
followingCount: number; followingCount: number;
refreshTokens: RefreshToken[]; refreshTokens: RefreshToken[];
} }
export interface Sesion {
accessToken:string?;
}
export interface LoginDto {
username: string?;
password: string?;
}
export interface RegisterDto {
username: string?;
email: string?;
password: string?;
displayName: string?;
}