import { Injectable } from '@angular/core'; import { StorageService } from './storage.service'; import { HttpClient, HttpHeaders, HttpEventType } from '@angular/common/http'; import { LoginUserRespose, UserForm, UserSession } from '../models/user.model'; import { environment } from 'src/environments/environment'; import { BehaviorSubject } from 'rxjs'; import { AlertController } from '@ionic/angular'; import { SessionStore } from '../store/session.service'; import { AESEncrypt } from '../services/aesencrypt.service'; import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service'; import { Router } from '@angular/router'; import { NfService } from 'src/app/services/chat/nf.service'; import { MessageService } from 'src/app/services/chat/message.service'; import { ProcessesService } from 'src/app/services/processes.service'; import { AttachmentsService } from 'src/app/services/attachments.service'; import { RoomService } from './chat/room.service'; import { Storage } from '@ionic/storage'; import { InitialsService } from './functions/initials.service'; import { PermissionService } from './permission.service'; import { ChatSystemService } from 'src/app/services/chat/chat-system.service'; import { HttpErrorHandle } from 'src/app/services/http-error-handle.service'; @Injectable({ providedIn: 'root' }) export class AuthService { userData$ = new BehaviorSubject(''); userId$ = new BehaviorSubject(''); headers: HttpHeaders = new HttpHeaders(); public wsValidatedUserChat:any; public isWsAuthenticated: boolean = false; opts:any; constructor( private http: HttpClient, private storageService:StorageService, public alertController: AlertController, private aesencrypt: AESEncrypt, private RochetChatConnectorService: RochetChatConnectorService, private router: Router, private NfService:NfService, private processesService: ProcessesService, private AttachmentsService: AttachmentsService, private storage: Storage, private initialsService: InitialsService, public p: PermissionService, public ChatSystemService: ChatSystemService, private httpErroHandle: HttpErrorHandle) { if (SessionStore.exist) { if(this.p.userPermission(this.p.permissionList.Chat.access) == true ) { this.loginToChatWs() } } } async login(user: UserForm, {saveSession = true}): Promise { user.BasicAuthKey = 'Basic ' + btoa(user.username + ':' + this.aesencrypt.encrypt(user.password,user.username )); this.headers = this.headers.set('Authorization', user.BasicAuthKey); this.opts = { headers: this.headers, } let response: any; try { response = await this.http.post(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise(); if(saveSession) { this.SetSession(response, user) } } catch (error) { this.httpErroHandle.httpStatusHandle(error) } finally { return response } } // async UpdateLogin() {} SetSession(response: LoginUserRespose, user:UserForm) { const session: UserSession = Object.assign(SessionStore.user, response) if (response) { if( session.RoleID == 100000014) { session.Profile = 'PR' } else if(session.RoleID == 100000011) { session.Profile = 'MDGPR' } else if(session.RoleID == 99999872) { session.Profile = 'Consultant' } else { session.Profile = 'Unknown' } session.Password = user.password session.BasicAuthKey = user.BasicAuthKey SessionStore.reset(session) // console.log(session) return true; } this.initialsService.getInitials(session.FullName); } loginToChatWs() { setTimeout(() => { if(SessionStore.user.ChatData?.data) { this.RochetChatConnectorService.connect(); this.RochetChatConnectorService.login().then((message: any) => { SessionStore.user.RochetChatUserId = message.result.id SessionStore.save() this.RochetChatConnectorService.setStatus('online') window['RochetChatConnectorService'] = this.RochetChatConnectorService setTimeout(() => { this.ChatSystemService.getAllRooms(); this.RochetChatConnectorService.setStatus('online') }, 200); }).catch((error) => { console.error(SessionStore.user.ChatData, 'web socket login',error) }) } // before sending a message with a attachment this.NfService.beforeSendAttachment = async (message: MessageService, room?: RoomService) => { if(message.hasFile) { if(message.file.type != 'application/webtrix') { const formData = message.temporaryData try { let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise() message.file.guid = guid.path message.downloadFileMsg() return true } catch(e) { console.error('BeforesendAtachment', e) return false } } else { try { const res = message.temporaryData let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise(); let url_no_options: string = url.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1"); message.attachments[0].title_link = url_no_options message.attachments[0].message_link = url_no_options return true } catch(e) { console.error('BeforesendAtachment', e) return false } } } return false } this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => { // let downloadFile = ""; if (message.file.type == "application/img") { const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise(); if (event.type === HttpEventType.DownloadProgress) { //this.downloadProgess = Math.round((100 * event.loaded) / event.total); return true } else if (event.type === HttpEventType.Response) { downloadFile = 'data:image/jpeg;base64,' + btoa(new Uint8Array(event.body).reduce((data, byte) => data + String.fromCharCode(byte), '')); message.file = { guid: message.file.guid, image_url: downloadFile, type: message.file.type } await this.storage.set(message.file.guid, downloadFile).then(() => { // }); return true } return false } }; }, 1) } autologout(expirationDate:number) { setTimeout(() => { this.logout(); }, expirationDate) } logout() { SessionStore.setInativity(false) SessionStore.setUrlBeforeInactivity(this.router.url); setTimeout(() => { this.router.navigateByUrl('/', { replaceUrl: true }); }, 100) } logoutChat() { } async presentAlert(message: string) { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: 'Mensagem do sistema', message: message, buttons: ['OK'] }); await alert.present(); } }