iam.service.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import { lastValueFrom } from 'rxjs';
  2. import { ContraTempComponent } from './../../components/iam/contra-temp/contra-temp.component';
  3. import { MatDialog } from '@angular/material/dialog';
  4. import { Injectable, OnInit } from '@angular/core';
  5. import { HttpClient, HttpHeaders } from '@angular/common/http';
  6. import { MatSnackBar } from '@angular/material/snack-bar';
  7. import { Router } from '@angular/router';
  8. import { ResponseLogin } from 'src/app/interfaces/iam/response-login';
  9. import { IAMInterface } from 'src/app/interfaces/iam/iam-interface';
  10. import { ENCService } from '../enc/enc.service';
  11. import { WebSocketService } from '../socket/web-socket.service';
  12. import { ResponseData } from 'src/app/interfaces/response-data';
  13. import { LocalstorageService } from '../localstorage.service';
  14. import { AuthGuard } from 'src/app/auth/auth.guard';
  15. import { AdminGuard } from 'src/app/auth/admin.guard';
  16. import { UserGuard } from 'src/app/auth/user.guard';
  17. @Injectable({
  18. providedIn: 'root',
  19. })
  20. export class IAMService implements OnInit {
  21. private _url = 'https://sirh.ittec.mx/v1/public/api';
  22. header: HttpHeaders = new HttpHeaders();
  23. current_user: string = '';
  24. jwt: string = '';
  25. constructor(
  26. private http: HttpClient,
  27. private _snackBar: MatSnackBar,
  28. private router: Router,
  29. private _encService: ENCService,
  30. private webSocketService: WebSocketService,
  31. public setUserStorage: LocalstorageService,
  32. private adminGuard: AdminGuard,
  33. private userGuard: UserGuard,
  34. public dialog: MatDialog
  35. ) {}
  36. ngOnInit(): void {}
  37. public usuario_rfc: string = '';
  38. public redirectUrl: string | null = null;
  39. private ipAddress: string = '';
  40. async login(data: IAMInterface, solicitud_datos: string) {
  41. let objeto = {
  42. email: data.email.trim(),
  43. password: data.password.trim(),
  44. };
  45. let respuesta = this.http
  46. .post<ResponseLogin>(`${this._url}/login`, objeto)
  47. .toPromise();
  48. await respuesta.then(
  49. async (data) => {
  50. if (!data?.error) {
  51. if(data?.response.PV == 'Si'){
  52. let dialogContra = this.dialog.open(ContraTempComponent);
  53. dialogContra.afterClosed().subscribe(async (res) => {
  54. if(res){
  55. let idUser = await this._encService.desencriptar2(data.response.IDUSUARIO);
  56. res['numero_empleado'] = idUser;
  57. res['prev_password'] = objeto.password;
  58. try{
  59. let resCont: any = await lastValueFrom(this.http.post(`${this._url}/MESMCC/cambiar`, res, {
  60. headers: new HttpHeaders({ Authorization: 'Bearer ' + data.response.TOKEN })
  61. }));
  62. if(resCont.error){
  63. this.snackAlert(resCont.msg);
  64. }else{
  65. this.procesarLogin(data, solicitud_datos);
  66. }
  67. }catch(error: any){
  68. if(error.error == undefined || error.error.msg == undefined){
  69. this.snackAlert('Ocurrió un error al tratar de actualizar su contraseña');
  70. }else{
  71. this.snackAlert(error.error.msg);
  72. }
  73. }
  74. }
  75. });
  76. }else{
  77. this.procesarLogin(data!, solicitud_datos);
  78. }
  79. } else {
  80. this.snackAlert(data.msg);
  81. }
  82. },
  83. (error) => {
  84. if (!error.ok) {
  85. this.snackAlert('Ocurrió un error inesperado');
  86. }
  87. if (error.error.msg != undefined) {
  88. this.snackAlert(error.error.msg);
  89. }
  90. if (error.status == 408) {
  91. this.snackAlert('Conexion lenta');
  92. }
  93. }
  94. );
  95. }
  96. async procesarLogin(data: ResponseLogin, solicitud_datos: string){
  97. let status = this._encService.desencriptar(data!.response.ESTATUS);
  98. let perfil = this._encService.desencriptar(data!.response.PERFIL);
  99. let rfc_empresa_user = this._encService.desencriptar(
  100. data!.response.RFCEMPRESA
  101. );
  102. let rfc_local = localStorage.getItem('RFCEMPRESA')!;
  103. if (rfc_local.length > 13) {
  104. await this._encService.desencriptar2(rfc_local).then(
  105. (data: string) => (rfc_local = data),
  106. (error: any) => console.log(error)
  107. );
  108. }
  109. if (rfc_empresa_user == rfc_local) {
  110. switch (status) {
  111. case 'Activo':
  112. this.current_user = JSON.stringify(data!.response);
  113. this.jwt = data!.response.TOKEN;
  114. localStorage.setItem('jwt', data!.response.TOKEN);
  115. localStorage.setItem(
  116. 'TIMUSERENC',
  117. JSON.stringify(data?.response)
  118. );
  119. let rfC_empresa_user = data?.response.RFCEMPRESA.replace(
  120. '"',
  121. ''
  122. ).replace('"', '');
  123. localStorage.setItem('RFCEMPRESA', rfC_empresa_user!);
  124. this.userType(perfil, solicitud_datos);
  125. break;
  126. case 'Eliminado':
  127. this.snackAlert('El usuario no existe');
  128. break;
  129. case 'Inactivo':
  130. this.snackAlert('El usuario esta bloqueado');
  131. break;
  132. default:
  133. this.snackAlert('Usuario inexistente');
  134. break;
  135. }
  136. } else {
  137. this.snackAlert(
  138. 'El R.F.C. del usuario no coincide con el R.F.C. del sistema al que desea entrar'
  139. );
  140. }
  141. }
  142. private snackAlert(mensaje: string) {
  143. this._snackBar.open(mensaje, 'Cerrar', {
  144. duration: 4000,
  145. });
  146. }
  147. public logout(): void {
  148. clearInterval(this.adminGuard.aux_test);
  149. clearInterval(this.userGuard.aux_test);
  150. let rfc_empresa_local = localStorage.getItem('RFCEMPRESA')!;
  151. if (
  152. rfc_empresa_local === null ||
  153. rfc_empresa_local === undefined ||
  154. rfc_empresa_local === ''
  155. ) {
  156. localStorage.setItem('RFCEMPRESA', 'ITTEC');
  157. }
  158. localStorage.removeItem('jwt');
  159. localStorage.removeItem('TIMUSERENC');
  160. this.router.navigate(['/iam']);
  161. this.snackAlert('¡Hasta pronto!');
  162. }
  163. private userType(perfil: string, solicitud_datos: string) {
  164. if (perfil == '1') {
  165. if (solicitud_datos == '') {
  166. this.router.navigate(['/admin/mesmpr']);
  167. } else {
  168. this.router.navigate([
  169. '/admin/mesmav',
  170. { solicitud_datos: solicitud_datos },
  171. ]);
  172. }
  173. } else {
  174. if (solicitud_datos == '') {
  175. this.router.navigate(['/mesmpr']);
  176. } else {
  177. this.router.navigate([
  178. '/mesmav',
  179. {
  180. solicitud_datos: solicitud_datos,
  181. },
  182. ]);
  183. }
  184. }
  185. }
  186. getJWT() {
  187. return this.jwt;
  188. }
  189. getCurrentUser() {
  190. return this.current_user;
  191. }
  192. getRFCEmpresa() {
  193. return this._encService.desencriptar(
  194. JSON.parse(this.current_user).RFCEMPRESA
  195. );
  196. }
  197. }