Skip to content
Snippets Groups Projects
Commit 5bd2ad6d authored by paborte's avatar paborte
Browse files

Autenticacion, creacion de usuarios y creacion de consultas completada

parent 0a7588cb
No related branches found
No related tags found
No related merge requests found
Showing
with 370 additions and 161 deletions
...@@ -19,6 +19,7 @@ import { CompletarRegistroComponent } from './mi-cuenta/completar-registro/compl ...@@ -19,6 +19,7 @@ import { CompletarRegistroComponent } from './mi-cuenta/completar-registro/compl
import { GridProductosComponent } from './tienda/modulo-productos/grid-productos/grid-productos.component'; import { GridProductosComponent } from './tienda/modulo-productos/grid-productos/grid-productos.component';
import { CategoriasComponent } from './tienda/modulo-productos/categorias/categorias.component'; import { CategoriasComponent } from './tienda/modulo-productos/categorias/categorias.component';
import { TiendaTiendaComponent } from './tienda/tienda-tienda/tienda-tienda.component'; import { TiendaTiendaComponent } from './tienda/tienda-tienda/tienda-tienda.component';
import { RegistroCompletoComponent } from './mi-cuenta/registro-completo/registro-completo.component';
const appRoutes: Routes = [ const appRoutes: Routes = [
{ path: '', redirectTo: '/homepage', pathMatch: 'full' }, { path: '', redirectTo: '/homepage', pathMatch: 'full' },
...@@ -51,7 +52,7 @@ const appRoutes: Routes = [ ...@@ -51,7 +52,7 @@ const appRoutes: Routes = [
component: InicioSesionRegistroComponent, component: InicioSesionRegistroComponent,
}, },
{ path: 'registro', component: CompletarRegistroComponent }, { path: 'registro', component: CompletarRegistroComponent },
{ path: 'registroCompleto', component: RegistroCompletoComponent },
{ path: 'cesta', component: CestaCompraComponent }, { path: 'cesta', component: CestaCompraComponent },
{ path: 'realizarPedido', component: CompletarPedidoComponent }, { path: 'realizarPedido', component: CompletarPedidoComponent },
{ path: 'realizarPedidoPago', component: CompletarPedidoPagoComponent }, { path: 'realizarPedidoPago', component: CompletarPedidoPagoComponent },
......
...@@ -2,17 +2,15 @@ ...@@ -2,17 +2,15 @@
<h3 class="verde-tienda">Contacto</h3> <h3 class="verde-tienda">Contacto</h3>
</div> </div>
<div class="container border"> <div class="container border">
<form <form #contactoForm="ngForm" class="mt-3 mb-3">
action="
"
class="mt-3 mb-3"
>
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input
type="text" type="text"
class="form-control" class="form-control"
id="floatingPassword" placeholder="Nombre"
placeholder="12345" name="nombre"
ngModel
required
/> />
<label for="floatingPassword">Nombre </label> <label for="floatingPassword">Nombre </label>
</div> </div>
...@@ -20,8 +18,10 @@ ...@@ -20,8 +18,10 @@
<input <input
type="text" type="text"
class="form-control" class="form-control"
id="floatingPassword" placeholder="Apellido1 Apellido2"
placeholder="12345" name="apellidos"
ngModel
required
/> />
<label for="floatingPassword">Apellidos</label> <label for="floatingPassword">Apellidos</label>
</div> </div>
...@@ -29,8 +29,11 @@ ...@@ -29,8 +29,11 @@
<input <input
type="email" type="email"
class="form-control" class="form-control"
id="floatingPassword" placeholder="example@example.es"
placeholder="12345" name="email"
email
required
ngModel
/> />
<label for="floatingPassword">Correo Electrónico</label> <label for="floatingPassword">Correo Electrónico</label>
</div> </div>
...@@ -38,18 +41,17 @@ ...@@ -38,18 +41,17 @@
<input <input
type="text" type="text"
class="form-control" class="form-control"
id="floatingPassword" placeholder="telefono"
placeholder="12345" name="telefono"
minlength="9"
maxlength="9"
required
ngModel
/> />
<label for="floatingPassword">Correo Electrónico</label> <label for="floatingPassword">Telefono</label>
</div> </div>
<div class="form-floating mb-3"> <div class="form-floating mb-3">
<input <input type="text" class="form-control" placeholder="pid" ngModel />
type="text"
class="form-control"
id="floatingPassword"
placeholder="12345"
/>
<label for="floatingPassword" <label for="floatingPassword"
>Numero de pedido (dejar en blanco si no se posee)</label >Numero de pedido (dejar en blanco si no se posee)</label
> >
...@@ -65,11 +67,18 @@ ...@@ -65,11 +67,18 @@
id="exampleFormControlTextarea1" id="exampleFormControlTextarea1"
rows="3" rows="3"
maxlength="2000" maxlength="2000"
name="motivoConsulta"
ngModel
required
></textarea> ></textarea>
</div> </div>
<div class="row mt-2"> <div class="row mt-2">
<div class="col d-flex justify-content-end"> <div class="col d-flex justify-content-end">
<button class="btn btn-primary border-white bg-fucsia"> <button
class="btn btn-primary border-white bg-fucsia"
type="submit"
(click)="contacto(contactoForm)"
>
Enviar consulta Enviar consulta
</button> </button>
</div> </div>
......
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AuthService } from '../services-interfaces/services/auth.service';
import { DatabaseService } from '../services-interfaces/services/database.service';
@Component({ @Component({
selector: 'app-contacto', selector: 'app-contacto',
templateUrl: './contacto.component.html', templateUrl: './contacto.component.html',
styleUrls: ['./contacto.component.css'] styleUrls: ['./contacto.component.css'],
}) })
export class ContactoComponent implements OnInit { export class ContactoComponent implements OnInit {
envioCorrecto = false;
constructor(private databaseService: DatabaseService) {}
constructor() { } ngOnInit(): void {}
ngOnInit(): void { contacto(form: NgForm) {
this.databaseService
.createConsultaInDatabase(
form.value.nombre,
form.value.apellidos,
form.value.email,
form.value.telefono,
form.value.numeroPedido,
form.value.motivoConsulta
)
.then(
(res) => {
this.envioCorrecto = true;
},
(error) => {
console.log(error);
}
);
} }
} }
...@@ -61,12 +61,13 @@ ...@@ -61,12 +61,13 @@
>Contacto</a >Contacto</a
> >
</li> </li>
<li class="nav-item pe-5"> <li class="nav-item pe-5" *ngIf="user">
<a <a class="nav-link" routerLink="/perfil" routerLinkActive="active"
class="nav-link" >Mi cuenta</a
[routerLink]="miCuenta" >
(mouseover)="checkLogin()" </li>
routerLinkActive="active" <li class="nav-item pe-5" *ngIf="!user">
<a class="nav-link" routerLink="/auth" routerLinkActive="active"
>Mi cuenta</a >Mi cuenta</a
> >
</li> </li>
......
import { Component, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Usuario } from '../services-interfaces/interfaces/usuario';
import { AuthService } from '../services-interfaces/services/auth.service'; import { AuthService } from '../services-interfaces/services/auth.service';
import { DatabaseService } from '../services-interfaces/services/database.service';
@Component({ @Component({
selector: 'app-header', selector: 'app-header',
templateUrl: './header.component.html', templateUrl: './header.component.html',
styleUrls: ['./header.component.css'], styleUrls: ['./header.component.css'],
}) })
export class HeaderComponent implements OnInit { export class HeaderComponent implements OnInit, OnDestroy {
miCuenta = '/auth'; miCuenta = '/auth';
isUserAuthenticated = false;
authenticatedUserBS: Subscription;
user!: Usuario;
constructor(private authService: AuthService) {} constructor(private databaseService: DatabaseService) {}
ngOnInit(): void {} ngOnInit(): void {
checkLogin() { this.authenticatedUserBS =
if (this.authService.isLoggedIn()) { this.databaseService.authenticatedUserBS.subscribe(
this.miCuenta = '/perfil'; (user) => {
} else { this.user = user;
this.miCuenta = '/auth'; },
() => {
this.isUserAuthenticated = false;
} }
);
}
ngOnDestroy(): void {
this.authenticatedUserBS.unsubscribe();
} }
} }
...@@ -41,7 +41,6 @@ ...@@ -41,7 +41,6 @@
[(ngModel)]="user.telefono" [(ngModel)]="user.telefono"
required required
minlength="9" minlength="9"
ng-pattern="/^[0-9]{1,7}$/"
maxlength="9" maxlength="9"
/> />
<label for="floatingPassword">Teléfono contacto</label> <label for="floatingPassword">Teléfono contacto</label>
......
...@@ -29,12 +29,17 @@ export class CompletarRegistroComponent implements OnInit { ...@@ -29,12 +29,17 @@ export class CompletarRegistroComponent implements OnInit {
ngOnInit(): void { ngOnInit(): void {
this.user = this.authService.getUser(); this.user = this.authService.getUser();
if (this.user === undefined) {
this.user = new Usuario();
}
console.log(this.user);
} }
finalizarRegistro(form: NgForm) { finalizarRegistro(form: NgForm) {
this.loading = true; this.loading = true;
this.user.direccionEnvio.pais = 'España'; this.user.direccionEnvio.pais = 'España';
this.user.nombre = form.value.nombre; this.user.nombre = form.value.nombre;
this.user.telefono = form.value.telefono;
if ( if (
form.value.distintasDirecciones === 'false' || form.value.distintasDirecciones === 'false' ||
form.value.distintasDirecciones === '' form.value.distintasDirecciones === ''
...@@ -46,16 +51,21 @@ export class CompletarRegistroComponent implements OnInit { ...@@ -46,16 +51,21 @@ export class CompletarRegistroComponent implements OnInit {
.createUserWithEmail(this.user.email, form.value.password1) .createUserWithEmail(this.user.email, form.value.password1)
.subscribe( .subscribe(
(res) => { (res) => {
this.databaseService.createNewUserInDatabase(this.user); this.databaseService.createNewUserInDatabase(this.user, res.user.uid);
this.authService.changeLogState();
this.router.navigate(['../perfil'], { relativeTo: this.route }); this.loading = false;
this.router.navigate(['../registroCompleto'], {
relativeTo: this.route,
});
}, },
(error) => { (error) => {
console.log(error.message); console.log(error.message);
if (error.message.indexOf('auth/email-already-in-use')) { if (error.message.indexOf('auth/email-already-in-use')) {
this.loading = false;
this.errorMessage = this.errorMessage =
'!El correo electrónico introducido ya ha sido registrado por otro usuario! Por favor introduzca un nuevo.'; '!El correo electrónico introducido ya ha sido registrado por otro usuario! Por favor introduzca un nuevo.';
} else { } else {
this.loading = false;
this.errorMessage = this.errorMessage =
'!Ha ocurrido un error insesperado, por favor, intentelo de nuevo.'; '!Ha ocurrido un error insesperado, por favor, intentelo de nuevo.';
} }
......
...@@ -13,6 +13,7 @@ import { DireccionesComponent } from './perfil-cuenta/direcciones/direcciones.co ...@@ -13,6 +13,7 @@ import { DireccionesComponent } from './perfil-cuenta/direcciones/direcciones.co
import { DatosPagoComponent } from './perfil-cuenta/datos-pago/datos-pago.component'; import { DatosPagoComponent } from './perfil-cuenta/datos-pago/datos-pago.component';
import { ResumenPedidoComponent } from './perfil-cuenta/pedidos/resumen-pedido/resumen-pedido.component'; import { ResumenPedidoComponent } from './perfil-cuenta/pedidos/resumen-pedido/resumen-pedido.component';
import { AppRoutingModule } from '../app-routing.module'; import { AppRoutingModule } from '../app-routing.module';
import { RegistroCompletoComponent } from './registro-completo/registro-completo.component';
@NgModule({ @NgModule({
imports: [CommonModule, ProgressSpinnerModule, FormsModule, AppRoutingModule], imports: [CommonModule, ProgressSpinnerModule, FormsModule, AppRoutingModule],
...@@ -25,6 +26,7 @@ import { AppRoutingModule } from '../app-routing.module'; ...@@ -25,6 +26,7 @@ import { AppRoutingModule } from '../app-routing.module';
DireccionesComponent, DireccionesComponent,
DatosPagoComponent, DatosPagoComponent,
ResumenPedidoComponent, ResumenPedidoComponent,
RegistroCompletoComponent,
], ],
exports: [], exports: [],
}) })
......
...@@ -15,7 +15,7 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s ...@@ -15,7 +15,7 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s
}) })
export class InicioSesionRegistroComponent implements OnInit { export class InicioSesionRegistroComponent implements OnInit {
public loading = false; public loading = false;
public user!: Usuario; public user = new Usuario();
public credencialesInvalidas = false; public credencialesInvalidas = false;
public userLogged = false; public userLogged = false;
...@@ -37,17 +37,7 @@ export class InicioSesionRegistroComponent implements OnInit { ...@@ -37,17 +37,7 @@ export class InicioSesionRegistroComponent implements OnInit {
.subscribe({ .subscribe({
next: (user: UserCredential) => { next: (user: UserCredential) => {
this.loading = false; this.loading = false;
this.authService.changeLogState(); this.router.navigate(['/perfil']);
this.databaseService.getUserFromDatabase(user.user.uid).subscribe(
(userRes: any) => {
console.log(userRes);
this.router.navigate(['../perfil'], { relativeTo: this.route });
},
(error) => {
console.log(error);
}
);
/* to-do guardar user en el local storage */ /* to-do guardar user en el local storage */
}, },
error: (e) => { error: (e) => {
...@@ -59,11 +49,8 @@ export class InicioSesionRegistroComponent implements OnInit { ...@@ -59,11 +49,8 @@ export class InicioSesionRegistroComponent implements OnInit {
} }
onRegister(form: NgForm): void { onRegister(form: NgForm): void {
if (form.value.passwordRegistro1 === form.value.passwordRegistro2) {
this.user = this.authService.getUser();
this.user.email = form.value.emailRegistro; this.user.email = form.value.emailRegistro;
this.authService.updateUserRegistro(this.user); this.authService.updateUserRegistro(this.user);
this.router.navigate(['../registro'], { relativeTo: this.route }); this.router.navigate(['../registro'], { relativeTo: this.route });
} }
} }
}
...@@ -3,42 +3,69 @@ ...@@ -3,42 +3,69 @@
<h4 class="verde-tienda pw-bold">{{ user.nombre }} {{ user.apellidos }}</h4> <h4 class="verde-tienda pw-bold">{{ user.nombre }} {{ user.apellidos }}</h4>
</div> </div>
<div class="row border rounded-3"> <div class="row border rounded-3">
<h4 class="mt-2">Correo electrónico</h4> <h4 class="mt-2">Correo electrónico para notificaciones</h4>
<h6 class="mt-2 text-secondary">
Este correo será utilizado para enviarte notificaciones, no es el correo
de inicio de sesión, ya que este no se puede modificar.
</h6>
<div class="row"> <div class="row">
<div <div
class="col-12 d-flex justify-content-between align-items-center pb-2" class="col-12 d-flex justify-content-between align-items-center pb-2"
> >
<h6 class="">{{ user.email }}</h6> <input
<button class="btn btn-primary bg-fucsia border-white"> type="text"
Cambiar correo class="form-control me-5"
[value]="user.email"
[disabled]="!cambioEmail"
[(ngModel)]="user.email"
/>
<!-- <h6 class="">{{ user.email }}</h6> -->
<button
class="btn btn-primary bg-fucsia border-white"
(click)="cambioEmailActivate()"
>
{{ cambioEmailText }}
</button> </button>
</div> </div>
</div> </div>
<div class="row" *ngIf="emailSuccess" (focus)="emailSuccess = false">
<div class="col-12">
<div class="alert alert-success">!Correo modificado correctamente!</div>
</div>
</div>
</div> </div>
<div class="row border rounded-3 mt-2"> <div class="row border rounded-3 mt-2">
<h4 class="mt-2">Contraseña</h4> <h4 class="mt-2">Teléfono</h4>
<h6 class="mt-2 text-secondary">
Este teléfono será utilizado para contactar contigo en caso de ser
necesario.
</h6>
<div class="row"> <div class="row">
<div <div
class="col-12 d-flex justify-content-between align-items-center pb-2" class="col-12 d-flex justify-content-between align-items-center pb-2"
> >
<h6 class="">******</h6> <input
<button class="btn btn-primary bg-fucsia border-white"> type="text"
Cambiar contraseña class="form-control me-5"
[disabled]="!cambioTelefono"
[(ngModel)]="user.telefono"
minlength="9"
maxlength="9"
/>
<button
class="btn btn-primary bg-fucsia border-white"
(click)="cambioTelefonoActivate()"
>
{{ cambioTelefonoText }}
</button> </button>
</div> </div>
</div> </div>
<div class="row" *ngIf="telefonoSuccess" (focus)="telefonoSuccess = false">
<div class="col-12">
<div class="alert alert-success">
!Telefono modificado correctamente!
</div> </div>
<div class="row border rounded-3 mt-2">
<h4 class="mt-2">Teléfono</h4>
<div class="row">
<div
class="col-12 d-flex justify-content-between align-items-center pb-2"
>
<h6 class="">+34 {{ user.telefono }}</h6>
<button class="btn btn-primary bg-fucsia border-white">
Modificar teléfono
</button>
</div> </div>
</div> </div>
</div> </div>
......
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Usuario } from 'src/app/services-interfaces/interfaces/usuario'; import { Usuario } from 'src/app/services-interfaces/interfaces/usuario';
import { AuthService } from 'src/app/services-interfaces/services/auth.service'; import { AuthService } from 'src/app/services-interfaces/services/auth.service';
import { DatabaseService } from 'src/app/services-interfaces/services/database.service'; import { DatabaseService } from 'src/app/services-interfaces/services/database.service';
...@@ -10,19 +11,59 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s ...@@ -10,19 +11,59 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s
}) })
export class DatosPersonalesComponent implements OnInit { export class DatosPersonalesComponent implements OnInit {
user: Usuario; user: Usuario;
password = '******';
userSubscription: Subscription;
cambioPassword = false;
cambioPasswordText = 'Cambiar contraseña';
passwordSuccess = false;
cambioEmail = false;
cambioEmailText = 'Cambiar correo';
emailSuccess = false;
cambioTelefono = false;
cambioTelefonoText = 'Cambiar telefono';
telefonoSuccess = false;
constructor( constructor(
private authService: AuthService, private authService: AuthService,
private databaseService: DatabaseService private databaseService: DatabaseService
) {} ) {}
ngOnInit(): void { ngOnInit(): void {
this.databaseService this.userSubscription = this.databaseService.authenticatedUserBS.subscribe(
.getUserFromDatabase(this.authService.getAuthUser().uid) (user) => {
.subscribe( this.user = user;
(userRes: any) => { }
this.user = userRes;
},
(error) => {}
); );
} }
ngOnDestroy(): void {
this.userSubscription.unsubscribe();
}
cambioEmailActivate() {
if (!this.cambioEmail) {
this.cambioEmail = true;
this.cambioEmailText = 'Confirmar cambio';
} else {
this.cambioEmail = false;
this.databaseService
.updateUserInDatabase(this.user, this.authService.credential.user.uid)
.subscribe((ok) => {
this.emailSuccess = true;
this.cambioEmailText = 'Cambiar correo';
});
}
}
cambioTelefonoActivate() {
if (!this.cambioTelefono) {
this.cambioTelefono = true;
this.cambioTelefonoText = 'Confirmar cambio';
} else {
this.cambioTelefono = false;
this.databaseService
.updateUserInDatabase(this.user, this.authService.credential.user.uid)
.subscribe((ok) => {
this.telefonoSuccess = true;
this.cambioTelefonoText = 'Cambiar telefono';
});
}
}
} }
import { Component, OnInit } from '@angular/core'; import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Usuario } from 'src/app/services-interfaces/interfaces/usuario'; import { Usuario } from 'src/app/services-interfaces/interfaces/usuario';
import { AuthService } from 'src/app/services-interfaces/services/auth.service';
import { DatabaseService } from 'src/app/services-interfaces/services/database.service'; import { DatabaseService } from 'src/app/services-interfaces/services/database.service';
@Component({ @Component({
...@@ -8,20 +8,19 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s ...@@ -8,20 +8,19 @@ import { DatabaseService } from 'src/app/services-interfaces/services/database.s
templateUrl: './direcciones.component.html', templateUrl: './direcciones.component.html',
styleUrls: ['./direcciones.component.css'], styleUrls: ['./direcciones.component.css'],
}) })
export class DireccionesComponent implements OnInit { export class DireccionesComponent implements OnInit, OnDestroy {
user: Usuario; user: Usuario;
constructor(
private authService: AuthService, private userSubscription: Subscription;
private databaseService: DatabaseService constructor(private databaseService: DatabaseService) {}
) {}
ngOnInit(): void { ngOnInit(): void {
this.databaseService this.userSubscription = this.databaseService.authenticatedUserBS.subscribe(
.getUserFromDatabase(this.authService.getAuthUser().uid) (user) => {
.subscribe( this.user = user;
(userRes: any) => { }
this.user = userRes;
},
(error) => {}
); );
} }
ngOnDestroy(): void {
this.userSubscription.unsubscribe();
}
} }
<div class="container">
<h5 class="mt-5">
¡Registro completo! Será redirigido a la pagina de inicio de sesion en
breves momentos.
</h5>
</div>
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-registro-completo',
templateUrl: './registro-completo.component.html',
styleUrls: ['./registro-completo.component.css'],
})
export class RegistroCompletoComponent implements OnInit, OnDestroy {
interval;
constructor(private router: Router) {}
ngOnInit(): void {
this.interval = setInterval(() => {
this.router.navigate(['/auth']);
}, 3000);
}
ngOnDestroy(): void {
clearInterval(this.interval);
}
}
...@@ -2,11 +2,11 @@ import { Cesta } from './cesta.model'; ...@@ -2,11 +2,11 @@ import { Cesta } from './cesta.model';
import { MetodoPago } from './metodoPago.model'; import { MetodoPago } from './metodoPago.model';
export class Usuario { export class Usuario {
nombre!: string; nombre: string;
apellidos!: string; apellidos: string;
email!: string; email: string;
telefono!: string; telefono: string;
direccionEnvio!: { direccionEnvio: {
nombre: string; nombre: string;
apellidos: string; apellidos: string;
direccion: string; direccion: string;
...@@ -15,7 +15,7 @@ export class Usuario { ...@@ -15,7 +15,7 @@ export class Usuario {
codigoPostal: string; codigoPostal: string;
pais: string; pais: string;
}; };
direccionFacturacion!: { direccionFacturacion: {
nombre: string; nombre: string;
apellidos: string; apellidos: string;
direccion: string; direccion: string;
...@@ -24,7 +24,31 @@ export class Usuario { ...@@ -24,7 +24,31 @@ export class Usuario {
codigoPostal: string; codigoPostal: string;
pais: string; pais: string;
}; };
metodosPago!: MetodoPago[]; metodosPago: MetodoPago[];
cesta!: Cesta; cesta: Cesta;
constructor() {
this.nombre = '';
this.apellidos = '';
this.email = '';
this.telefono = '';
this.direccionEnvio = {
nombre: '',
apellidos: '',
direccion: '',
poblacion: '',
provincia: '',
codigoPostal: '',
pais: '',
};
this.direccionFacturacion = {
nombre: '',
apellidos: '',
direccion: '',
poblacion: '',
provincia: '',
codigoPostal: '',
pais: '',
};
}
} }
...@@ -8,40 +8,16 @@ import { ...@@ -8,40 +8,16 @@ import {
import { Usuario } from '../interfaces/usuario'; import { Usuario } from '../interfaces/usuario';
import { from, Observable } from 'rxjs'; import { from, Observable } from 'rxjs';
import { DatabaseService } from './database.service';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
isUserLogged = false; isUserLogged = false;
public user: Usuario = { credential!: UserCredential;
nombre: '',
apellidos: '', public user!: Usuario;
email: '',
telefono: '',
direccionEnvio: {
nombre: '',
apellidos: '',
direccion: '',
poblacion: '',
provincia: '',
codigoPostal: '',
pais: '',
},
direccionFacturacion: {
nombre: '',
apellidos: '',
direccion: '',
poblacion: '',
provincia: '',
codigoPostal: '',
pais: '',
},
metodosPago: [],
cesta: {
productos: [],
},
};
private password = ''; private password = '';
constructor(private auth: Auth) {} constructor(private auth: Auth, private databaseService: DatabaseService) {}
public isLoggedIn(): boolean { public isLoggedIn(): boolean {
return this.isUserLogged; return this.isUserLogged;
...@@ -52,6 +28,14 @@ export class AuthService { ...@@ -52,6 +28,14 @@ export class AuthService {
password: string password: string
): Observable<UserCredential> { ): Observable<UserCredential> {
const loginPromise = signInWithEmailAndPassword(this.auth, email, password); const loginPromise = signInWithEmailAndPassword(this.auth, email, password);
const loginObs = from(loginPromise);
loginObs.subscribe((user) => {
this.credential = user;
this.databaseService
.getUserFromDatabaseOnLogin(user.user.uid)
.subscribe();
});
return from(loginPromise); return from(loginPromise);
} }
...@@ -83,4 +67,7 @@ export class AuthService { ...@@ -83,4 +67,7 @@ export class AuthService {
public getAuthUser() { public getAuthUser() {
return this.auth.currentUser; return this.auth.currentUser;
} }
public logOut(): Observable<any> {
return from(this.auth.signOut());
}
} }
...@@ -5,6 +5,8 @@ import { ...@@ -5,6 +5,8 @@ import {
AngularFireObject, AngularFireObject,
} from '@angular/fire/compat/database'; } from '@angular/fire/compat/database';
import { AngularFirestore, Query } from '@angular/fire/compat/firestore'; import { AngularFirestore, Query } from '@angular/fire/compat/firestore';
import { BehaviorSubject, from, Observable, tap } from 'rxjs';
import { Pedido } from '../interfaces/pedido.model'; import { Pedido } from '../interfaces/pedido.model';
import { Producto } from '../interfaces/producto.model'; import { Producto } from '../interfaces/producto.model';
import { Usuario } from '../interfaces/usuario'; import { Usuario } from '../interfaces/usuario';
...@@ -14,6 +16,8 @@ import { AuthService } from './auth.service'; ...@@ -14,6 +16,8 @@ import { AuthService } from './auth.service';
providedIn: 'root', providedIn: 'root',
}) })
export class DatabaseService { export class DatabaseService {
public authenticatedUserBS = new BehaviorSubject<Usuario>(null);
private authenticatedUser!: Usuario;
private usersPath = '/users'; private usersPath = '/users';
private pedidosPath = '/pedidos'; private pedidosPath = '/pedidos';
private productosPath = '/productos'; private productosPath = '/productos';
...@@ -23,20 +27,19 @@ export class DatabaseService { ...@@ -23,20 +27,19 @@ export class DatabaseService {
private productosRef!: AngularFireList<Producto>; private productosRef!: AngularFireList<Producto>;
constructor( constructor(
private db: AngularFireDatabase, private db: AngularFireDatabase,
private angularFirestore: AngularFirestore, private angularFirestore: AngularFirestore
private authService: AuthService
) {} ) {}
createNewUserInDatabase(user: Usuario): Promise<any> { createNewUserInDatabase(user: Usuario, uid: string): Promise<any> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
this.angularFirestore this.angularFirestore
.collection('users') .collection('users')
.doc(this.authService.getAuthUser().uid) .doc(uid)
.set({ .set({
nombre: user.nombre, nombre: user.nombre,
apellidos: user.apellidos, apellidos: user.apellidos,
email: user.email, email: user.email,
telefono: '', telefono: user.telefono,
direccionEnvio: user.direccionEnvio, direccionEnvio: user.direccionEnvio,
direccionFacturacion: user.direccionFacturacion, direccionFacturacion: user.direccionFacturacion,
metodosPago: [], metodosPago: [],
...@@ -54,11 +57,70 @@ export class DatabaseService { ...@@ -54,11 +57,70 @@ export class DatabaseService {
); );
}); });
} }
updateUserInDatabase(user: Usuario, uid: string) {
const updatePromise = this.angularFirestore
.collection('users')
.doc(uid)
.update({
nombre: user.nombre,
apellidos: user.apellidos,
email: user.email,
telefono: user.telefono,
direccionEnvio: user.direccionEnvio,
direccionFacturacion: user.direccionFacturacion,
metodosPago: [],
cesta: {
productos: [],
},
});
return from(updatePromise);
}
getUserFromDatabaseOnLogin(uid: string): Observable<any> {
return this.angularFirestore
.collection('users')
.doc(uid)
.valueChanges()
.pipe(
tap((userRecieved: any) => {
console.log(userRecieved);
getUserFromDatabase(uid: string) { this.authenticatedUserBS.next(userRecieved);
return this.angularFirestore.collection('users').doc(uid).valueChanges(); console.log(this.authenticatedUserBS);
})
);
} }
getAllUsersFromDatabase() { getAllUsersFromDatabase() {
return this.angularFirestore.collection('users').snapshotChanges(); return this.angularFirestore.collection('users').snapshotChanges();
} }
createConsultaInDatabase(
nombre: string,
apellidos: string,
email: string,
telefono: string,
numeroPedido: string,
motivoConsulta: string
) {
return new Promise<any>((resolve, reject) => {
this.angularFirestore
.collection('users')
.add({
nombre: nombre,
apellidos: apellidos,
email: email,
telefono: telefono,
numeroPedido: numeroPedido,
motivoConsulta: motivoConsulta,
})
.then(
(response) => {
console.log(response);
},
(error) => {
reject(error);
}
);
});
}
} }
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<title>TiendaChocolatesVeganos</title> <title>TiendaChocolatesVeganos</title>
<base href="/"> <base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="icon" type="image/x-icon" href="" />
</head> </head>
<body> <body>
<app-root></app-root> <app-root></app-root>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment