Skip to content
Snippets Groups Projects
Commit 471c0d62 authored by hugcubi's avatar hugcubi
Browse files

Funciona register

parent 48d68d10
Branches
Tags
2 merge requests!26Revert "Funciona register",!25Dev/angular microservicios
...@@ -6,6 +6,7 @@ import { MainPageComponent } from './core/features/user/main-page/main-page.comp ...@@ -6,6 +6,7 @@ import { MainPageComponent } from './core/features/user/main-page/main-page.comp
import { BookingListComponent } from './core/features/bookings/booking-list/booking-list.component'; import { BookingListComponent } from './core/features/bookings/booking-list/booking-list.component';
import { UserBookingListComponent } from './core/features/user/user-booking-list/user-booking-list.component'; import { UserBookingListComponent } from './core/features/user/user-booking-list/user-booking-list.component';
import { LoginComponent } from './core/features/auth/login/login.component'; import { LoginComponent } from './core/features/auth/login/login.component';
import { RegisterComponent } from './core/features/auth/register/register.component';
export const routes: Routes = [ export const routes: Routes = [
{ {
...@@ -40,6 +41,10 @@ export const routes: Routes = [ ...@@ -40,6 +41,10 @@ export const routes: Routes = [
path: 'auth/login', path: 'auth/login',
component: LoginComponent, component: LoginComponent,
}, },
{
path: 'auth/register',
component: RegisterComponent,
},
{ {
path: '**', path: '**',
redirectTo: '', redirectTo: '',
......
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
@Component({ @Component({
standalone: true, standalone: true,
selector: 'app-login', selector: 'app-login',
templateUrl: './login.component.html', templateUrl: './login.component.html',
styleUrls: ['./login.component.css'], styleUrls: ['./login.component.css'],
imports: [ReactiveFormsModule] imports: [CommonModule, ReactiveFormsModule]
}) })
export class LoginComponent { export class LoginComponent {
loginForm: FormGroup; loginForm: FormGroup;
constructor(private fb: FormBuilder) { constructor(
private fb: FormBuilder,
private http: HttpClient,
private router: Router
) {
this.loginForm = this.fb.group({ this.loginForm = this.fb.group({
email: ['', [Validators.required, Validators.email]], email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required] password: ['', [Validators.required]],
}); });
} }
onSubmit() { onSubmit() {
if (this.loginForm.valid) { if (this.loginForm.valid) {
const { email, password } = this.loginForm.value; const { email, password } = this.loginForm.value;
console.log('Login data:', { email, password });
// Aquí iría el llamado al servicio de login con JWT // Realizar la solicitud al backend
this.http.post('http://localhost:8101', { email, password }).subscribe({
next: (response: any) => {
// Guardar el token en localStorage
localStorage.setItem('authToken', response.token);
// Redirigir al dashboard
this.router.navigate(['/']);
},
error: (err) => {
console.error('Error en el login:', err);
},
});
}
} }
isAuthenticated(): boolean {
return !!localStorage.getItem('authToken');
} }
} }
<div class="register-container"> <div class="register-container">
<h2>Register</h2> <h2>Regístrate</h2>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()"> <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div> <div class="form-group">
<label for="email">Email:</label> <label for="name">Nombre</label>
<input id="email" type="email" formControlName="email" /> <input
<div *ngIf="registerForm.get('email')?.invalid && registerForm.get('email')?.touched"> id="name"
<small>Email is required and must be valid.</small> type="text"
formControlName="name"
placeholder="Introduce tu nombre"
required
/>
<div *ngIf="registerForm.get('name')?.invalid && registerForm.get('name')?.touched">
<small>El nombre es obligatorio y debe tener al menos 3 caracteres.</small>
</div> </div>
</div> </div>
<div> <div class="form-group">
<label for="password">Password:</label> <label for="email">Correo Electrónico</label>
<input id="password" type="password" formControlName="password" /> <input
<div *ngIf="registerForm.get('password')?.invalid && registerForm.get('password')?.touched"> id="email"
<small>Password is required.</small> type="email"
formControlName="email"
placeholder="Introduce tu correo"
required
/>
<div *ngIf="registerForm.get('email')?.invalid && registerForm.get('email')?.touched">
<small>El correo electrónico no es válido.</small>
</div> </div>
</div> </div>
<div> <div class="form-group">
<label for="confirmPassword">Confirm Password:</label> <label for="password">Contraseña</label>
<input id="confirmPassword" type="password" formControlName="confirmPassword" /> <input
<div *ngIf="registerForm.get('confirmPassword')?.invalid && registerForm.get('confirmPassword')?.touched"> id="password"
<small>Passwords must match.</small> type="password"
formControlName="password"
placeholder="Introduce tu contraseña"
required
/>
<div *ngIf="registerForm.get('password')?.invalid && registerForm.get('password')?.touched">
<small>La contraseña debe tener al menos 6 caracteres.</small>
</div> </div>
</div> </div>
<button type="submit" [disabled]="registerForm.invalid">Register</button> <button type="submit" [disabled]="registerForm.invalid">Registrarse</button>
<div *ngIf="errorMessage" class="error-message">
{{ errorMessage }}
</div>
</form> </form>
</div> </div>
\ No newline at end of file
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({ @Component({
standalone: true,
selector: 'app-register', selector: 'app-register',
templateUrl: './register.component.html', templateUrl: './register.component.html',
styleUrls: ['./register.component.css'] styleUrls: ['./register.component.css'],
imports: [ReactiveFormsModule, CommonModule]
}) })
export class RegisterComponent { export class RegisterComponent {
registerForm: FormGroup; registerForm: FormGroup;
errorMessage: string | null = null;
constructor(private fb: FormBuilder) { constructor(
private fb: FormBuilder,
private http: HttpClient,
private router: Router
) {
this.registerForm = this.fb.group({ this.registerForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required, Validators.email]], email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required], password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', Validators.required]
}); });
} }
onSubmit() { onSubmit() {
if (this.registerForm.valid) { if (this.registerForm.valid) {
const { email, password, confirmPassword } = this.registerForm.value; const { name, email, password } = this.registerForm.value;
if (password === confirmPassword) {
console.log('Register data:', { email, password }); // Enviar solicitud al backend
// Aquí iría el llamado al servicio de register con JWT this.http.post('http://localhost:8080/users', { name, email, password }).subscribe({
next: () => {
alert('Usuario registrado con éxito.');
this.router.navigate(['/auth/login']); // Redirigir al login
},
error: (err) => {
if (err.error instanceof ErrorEvent) {
this.errorMessage = `Error: ${err.error.message}`;
} else { } else {
console.error('Passwords do not match.'); // Si el backend devuelve un objeto de error
this.errorMessage = err.error.message || 'Ocurrió un error al registrar el usuario.';
}
} }
});
} }
} }
} }
...@@ -34,6 +34,9 @@ public class User { ...@@ -34,6 +34,9 @@ public class User {
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private UserStatus status = UserStatus.NO_BOOKINGS; private UserStatus status = UserStatus.NO_BOOKINGS;
@Basic(optional = false)
private String password;
@JsonIgnore @JsonIgnore
@OneToMany(mappedBy = "userId", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @OneToMany(mappedBy = "userId", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Booking> bookings; private List<Booking> bookings;
...@@ -41,11 +44,12 @@ public class User { ...@@ -41,11 +44,12 @@ public class User {
public User() { public User() {
} }
public User(int id, String name, String email, UserStatus status, List<Booking> bookings) { public User(int id, String name, String email, UserStatus status, List<Booking> bookings, String password) {
setId(id); setId(id);
setEmail(email); setEmail(email);
setStatus(status); setStatus(status);
setBookings(bookings); setBookings(bookings);
setPassword(password);
} }
public int getId() { public int getId() {
...@@ -87,4 +91,12 @@ public class User { ...@@ -87,4 +91,12 @@ public class User {
public void setBookings(List<Booking> bookings) { public void setBookings(List<Booking> bookings) {
this.bookings = bookings; this.bookings = bookings;
} }
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment