import { lastValueFrom } from 'rxjs'; import { ContraTempComponent } from './../../components/iam/contra-temp/contra-temp.component'; import { MatDialog } from '@angular/material/dialog'; import { Injectable, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Router } from '@angular/router'; import { ResponseLogin } from 'src/app/interfaces/iam/response-login'; import { IAMInterface } from 'src/app/interfaces/iam/iam-interface'; import { ENCService } from '../enc/enc.service'; import { WebSocketService } from '../socket/web-socket.service'; import { ResponseData } from 'src/app/interfaces/response-data'; import { LocalstorageService } from '../localstorage.service'; import { AuthGuard } from 'src/app/auth/auth.guard'; import { AdminGuard } from 'src/app/auth/admin.guard'; import { UserGuard } from 'src/app/auth/user.guard'; @Injectable({ providedIn: 'root', }) export class IAMService implements OnInit { private _url = 'https://sirh.ittec.mx/v1/public/api'; header: HttpHeaders = new HttpHeaders(); current_user: string = ''; jwt: string = ''; constructor( private http: HttpClient, private _snackBar: MatSnackBar, private router: Router, private _encService: ENCService, private webSocketService: WebSocketService, public setUserStorage: LocalstorageService, private adminGuard: AdminGuard, private userGuard: UserGuard, public dialog: MatDialog ) {} ngOnInit(): void {} public usuario_rfc: string = ''; public redirectUrl: string | null = null; private ipAddress: string = ''; async login(data: IAMInterface, solicitud_datos: string) { let objeto = { email: data.email.trim(), password: data.password.trim(), }; let respuesta = this.http .post(`${this._url}/login`, objeto) .toPromise(); await respuesta.then( async (data) => { if (!data?.error) { if(data?.response.PV == 'Si'){ let dialogContra = this.dialog.open(ContraTempComponent); dialogContra.afterClosed().subscribe(async (res) => { if(res){ let idUser = await this._encService.desencriptar2(data.response.IDUSUARIO); res['numero_empleado'] = idUser; res['prev_password'] = objeto.password; try{ let resCont: any = await lastValueFrom(this.http.post(`${this._url}/MESMCC/cambiar`, res, { headers: new HttpHeaders({ Authorization: 'Bearer ' + data.response.TOKEN }) })); if(resCont.error){ this.snackAlert(resCont.msg); }else{ this.procesarLogin(data, solicitud_datos); } }catch(error: any){ if(error.error == undefined || error.error.msg == undefined){ this.snackAlert('Ocurrió un error al tratar de actualizar su contraseña'); }else{ this.snackAlert(error.error.msg); } } } }); }else{ this.procesarLogin(data!, solicitud_datos); } } else { this.snackAlert(data.msg); } }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } async procesarLogin(data: ResponseLogin, solicitud_datos: string){ let status = this._encService.desencriptar(data!.response.ESTATUS); let perfil = this._encService.desencriptar(data!.response.PERFIL); let rfc_empresa_user = this._encService.desencriptar( data!.response.RFCEMPRESA ); let rfc_local = localStorage.getItem('RFCEMPRESA')!; if (rfc_local.length > 13) { await this._encService.desencriptar2(rfc_local).then( (data: string) => (rfc_local = data), (error: any) => console.log(error) ); } if (rfc_empresa_user == rfc_local) { switch (status) { case 'Activo': this.current_user = JSON.stringify(data!.response); this.jwt = data!.response.TOKEN; localStorage.setItem('jwt', data!.response.TOKEN); localStorage.setItem( 'TIMUSERENC', JSON.stringify(data?.response) ); let rfC_empresa_user = data?.response.RFCEMPRESA.replace( '"', '' ).replace('"', ''); localStorage.setItem('RFCEMPRESA', rfC_empresa_user!); this.userType(perfil, solicitud_datos); break; case 'Eliminado': this.snackAlert('El usuario no existe'); break; case 'Inactivo': this.snackAlert('El usuario esta bloqueado'); break; default: this.snackAlert('Usuario inexistente'); break; } } else { this.snackAlert( 'El R.F.C. del usuario no coincide con el R.F.C. del sistema al que desea entrar' ); } } private snackAlert(mensaje: string) { this._snackBar.open(mensaje, 'Cerrar', { duration: 4000, }); } public logout(): void { clearInterval(this.adminGuard.aux_test); clearInterval(this.userGuard.aux_test); let rfc_empresa_local = localStorage.getItem('RFCEMPRESA')!; if ( rfc_empresa_local === null || rfc_empresa_local === undefined || rfc_empresa_local === '' ) { localStorage.setItem('RFCEMPRESA', 'ITTEC'); } localStorage.removeItem('jwt'); localStorage.removeItem('TIMUSERENC'); this.router.navigate(['/iam']); this.snackAlert('¡Hasta pronto!'); } private userType(perfil: string, solicitud_datos: string) { if (perfil == '1') { if (solicitud_datos == '') { this.router.navigate(['/admin/mesmpr']); } else { this.router.navigate([ '/admin/mesmav', { solicitud_datos: solicitud_datos }, ]); } } else { if (solicitud_datos == '') { this.router.navigate(['/mesmpr']); } else { this.router.navigate([ '/mesmav', { solicitud_datos: solicitud_datos, }, ]); } } } getJWT() { return this.jwt; } getCurrentUser() { return this.current_user; } getRFCEmpresa() { return this._encService.desencriptar( JSON.parse(this.current_user).RFCEMPRESA ); } }