Files
doneit-web/src/app/services/auth.service.ts
T

347 lines
10 KiB
TypeScript
Raw Normal View History

2023-06-30 15:46:41 +01:00
import { Injectable, ErrorHandler } from '@angular/core';
2021-02-25 10:25:46 +01:00
import { StorageService } from './storage.service';
2022-02-08 17:44:15 +01:00
import { HttpClient, HttpHeaders, HttpEventType } from '@angular/common/http';
2021-08-27 15:21:15 +01:00
import { LoginUserRespose, UserForm, UserSession } from '../models/user.model';
import { environment } from 'src/environments/environment';
2023-11-29 12:17:52 +01:00
import { BehaviorSubject, of } from 'rxjs';
2021-06-04 11:37:56 +01:00
import { AlertController } from '@ionic/angular';
2021-08-27 13:39:52 +01:00
import { SessionStore } from '../store/session.service';
2021-08-26 16:32:59 +01:00
import { AESEncrypt } from '../services/aesencrypt.service';
2022-09-30 15:13:36 +01:00
import { RochetChatConnectorService } from 'src/app/services/chat/rochet-chat-connector.service';
import { Router } from '@angular/router';
2022-10-04 16:04:23 +01:00
import { NfService } from 'src/app/services/chat/nf.service';
2022-02-07 17:55:00 +01:00
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';
2022-03-28 13:34:01 +01:00
import { InitialsService } from './functions/initials.service';
import { PermissionService } from './permission.service';
2022-09-30 15:13:36 +01:00
import { ChatSystemService } from 'src/app/services/chat/chat-system.service';
2023-03-09 09:09:10 +01:00
import { HttpErrorHandle } from 'src/app/services/http-error-handle.service';
2023-06-30 15:46:41 +01:00
import { captureException } from '@sentry/angular';
2023-07-10 12:32:01 +01:00
import { CPSession } from '../store/documentManagement';
2023-11-29 12:17:52 +01:00
import { catchError, tap } from 'rxjs/operators';
2020-08-06 14:31:07 +01:00
@Injectable({
providedIn: 'root'
})
export class AuthService {
userData$ = new BehaviorSubject<any>('');
2021-01-19 10:44:55 +01:00
userId$ = new BehaviorSubject<any>('');
2023-10-25 09:08:49 +01:00
headers: HttpHeaders = new HttpHeaders();
2023-10-20 17:05:39 +01:00
public wsValidatedUserChat: any;
2022-01-12 09:29:48 +01:00
public isWsAuthenticated: boolean = false;
2023-10-20 17:05:39 +01:00
opts: any;
2021-05-10 14:51:51 +01:00
2023-05-29 11:51:08 +01:00
tabIsActive = true
2023-09-29 16:40:50 +01:00
2020-08-06 14:31:07 +01:00
constructor(
private http: HttpClient,
2023-10-20 17:05:39 +01:00
private storageService: StorageService,
2021-06-04 11:37:56 +01:00
public alertController: AlertController,
2021-08-26 16:32:59 +01:00
private aesencrypt: AESEncrypt,
2022-09-30 15:13:36 +01:00
private RochetChatConnectorService: RochetChatConnectorService,
2022-02-07 17:55:00 +01:00
private router: Router,
2023-10-20 17:05:39 +01:00
private NfService: NfService,
2022-02-07 17:55:00 +01:00
private processesService: ProcessesService,
private AttachmentsService: AttachmentsService,
2022-03-28 13:34:01 +01:00
private storage: Storage,
private initialsService: InitialsService,
2022-07-21 18:05:29 +01:00
public p: PermissionService,
2023-03-09 09:09:10 +01:00
public ChatSystemService: ChatSystemService,
2023-06-30 15:46:41 +01:00
private httpErroHandle: HttpErrorHandle,
private errorHandler: ErrorHandler) {
2020-08-06 14:31:07 +01:00
2023-10-20 17:05:39 +01:00
if (SessionStore.exist) {
if (this.p.userPermission(this.p.permissionList.Chat.access) == true) {
this.loginToChatWs()
2021-05-10 14:51:51 +01:00
}
2023-05-29 11:51:08 +01:00
2023-10-20 17:05:39 +01:00
}
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
window.addEventListener('focus', (event) => {
if (!this.tabIsActive) {
this.tabIsActive = true
const data = SessionStore.getDataFromLocalStorage();
2023-08-08 16:32:57 +01:00
2023-10-20 17:05:39 +01:00
if (!data?.user?.Authorization && SessionStore?.user?.Authorization) {
window.location.reload();
2023-05-29 11:51:08 +01:00
}
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
if (window['all-process-gabinete']) {
window['all-process-gabinete']()
}
}
});
2023-05-29 11:51:08 +01:00
2023-10-20 17:05:39 +01:00
window.addEventListener('blur', (event) => {
this.tabIsActive = false
});
2021-07-22 17:07:04 +01:00
2023-10-20 17:05:39 +01:00
}
2021-02-18 12:44:35 +01:00
2023-10-20 17:05:39 +01:00
async login(user: UserForm, { saveSession = true }): Promise<LoginUserRespose> {
2023-11-29 12:17:52 +01:00
user.BasicAuthKey = btoa(user.username + ':' + this.aesencrypt.encrypt(user.password, user.username));
2021-07-22 17:07:04 +01:00
2023-10-20 17:05:39 +01:00
this.headers = this.headers.set('Authorization', user.BasicAuthKey);
2023-11-29 12:17:52 +01:00
2023-10-20 17:05:39 +01:00
this.opts = {
2023-11-29 12:17:52 +01:00
/* headers: this.headers, */
"Content-Type": "application/json",
"Accept": "application/json",
}
let body = {
"Auth": user.BasicAuthKey,
"ChannelId": 1
2023-10-20 17:05:39 +01:00
}
2023-10-20 17:05:39 +01:00
let response: any;
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
try {
2023-11-29 12:17:52 +01:00
response = await this.http.post<LoginUserRespose>(environment.apiURL + "UserAuthentication/Login", body, this.opts).toPromise();
2022-03-28 13:34:01 +01:00
2021-05-10 15:45:09 +01:00
2023-10-20 17:05:39 +01:00
if (saveSession) {
this.SetSession(response, user)
}
} catch (error) {
this.errorHandler.handleError(error);
this.httpErroHandle.loginHttpStatusHandle(error)
captureException(error);
} finally {
return response
2021-08-27 15:21:15 +01:00
}
2021-03-31 16:32:33 +01:00
2023-10-20 17:05:39 +01:00
}
2023-10-20 17:05:39 +01:00
async loginContenteProduction(user: UserForm, { saveSession = true }): Promise<LoginUserRespose> {
user.BasicAuthKey = 'Basic ' + btoa(user.username + ':' + this.aesencrypt.encrypt(user.password, user.username));
2023-10-20 17:05:39 +01:00
this.headers = this.headers.set('Authorization', user.BasicAuthKey);
this.opts = {
headers: this.headers,
}
2023-10-20 17:05:39 +01:00
let response: any;
2023-10-20 17:05:39 +01:00
try {
2023-11-29 12:17:52 +01:00
response = await this.http.post<LoginUserRespose>(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise();
2023-10-20 17:05:39 +01:00
console.log('JWT', response)
2023-07-12 15:15:56 +01:00
2023-10-20 17:05:39 +01:00
if (saveSession) {
/* this.SetSession(response, user) */
console.log('teste', response);
2023-07-06 13:13:23 +01:00
return response
2023-10-20 17:05:39 +01:00
}
} catch (error) {
this.httpErroHandle.httpStatusHandle(error)
} finally {
return response
}
2023-10-20 17:05:39 +01:00
}
// async UpdateLogin() {}
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
SetSession(response: LoginUserRespose, user: UserForm) {
const session: UserSession = Object.assign(SessionStore.user, response)
2022-05-09 15:01:23 +01:00
2023-10-20 17:05:39 +01:00
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 if (session.RoleID == 99999886) {
session.Profile = 'SGGPR'
} else {
session.Profile = 'Unknown'
2021-05-10 14:51:51 +01:00
}
2022-04-07 14:24:07 +01:00
2023-10-20 17:05:39 +01:00
session.Password = user.password
session.BasicAuthKey = user.BasicAuthKey
SessionStore.reset(session)
return true;
}
2020-08-06 14:31:07 +01:00
2023-10-20 17:05:39 +01:00
this.initialsService.getInitials(session.FullName);
}
loginToChatWs() {
setTimeout(() => {
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
if (SessionStore.user.ChatData?.data) {
this.RochetChatConnectorService.connect();
this.RochetChatConnectorService.login().then((message: any) => {
2023-11-29 12:17:52 +01:00
console.log('Chat login', message)
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
SessionStore.user.RochetChatUserId = message.result.id
SessionStore.save()
2022-03-03 22:57:33 +01:00
2023-10-20 17:05:39 +01:00
this.RochetChatConnectorService.setStatus('online')
window['RochetChatConnectorService'] = this.RochetChatConnectorService
setTimeout(() => {
this.ChatSystemService.getAllRooms();
2023-01-12 15:27:09 +01:00
this.RochetChatConnectorService.setStatus('online')
2023-10-20 17:05:39 +01:00
}, 200);
2023-09-29 16:40:50 +01:00
2023-01-12 15:27:09 +01:00
2023-10-20 17:05:39 +01:00
}).catch((error) => {
// console.error(SessionStore.user.ChatData, 'web socket login',error)
})
}
2023-09-29 16:40:50 +01:00
2022-02-07 17:55:00 +01:00
2023-10-20 17:05:39 +01:00
// before sending a message with a attachment
this.NfService.beforeSendAttachment = async (message: MessageService, room?: RoomService) => {
2023-10-20 17:05:39 +01:00
if (message.hasFile) {
if (message.file.type != 'application/webtrix') {
const formData = message.temporaryData
2022-02-07 17:55:00 +01:00
2023-10-20 17:05:39 +01:00
try {
let guid: any = await this.AttachmentsService.uploadFile(formData).toPromise()
message.file.guid = guid.path
2022-03-24 17:40:14 +01:00
2023-10-20 17:05:39 +01:00
message.downloadFileMsg()
message.uploadingFile = false
2022-03-22 16:11:30 +01:00
2023-10-20 17:05:39 +01:00
return true
} catch (e) {
window['e'] = e
console.error('BeforesendAtachment', e)
message.uploadingFile = false
return false
}
2022-02-07 20:18:48 +01:00
2023-10-20 17:05:39 +01:00
} else {
try {
const res = message.temporaryData
2022-05-27 13:36:37 +01:00
2023-10-20 17:05:39 +01:00
let url = await this.processesService.GetDocumentUrl(res.data.selected.Id, res.data.selected.ApplicationType).toPromise();
2022-05-27 13:36:37 +01:00
2023-10-20 17:05:39 +01:00
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
2022-05-27 13:36:37 +01:00
2023-10-20 17:05:39 +01:00
message.uploadingFile = false
2022-02-07 20:18:48 +01:00
2023-10-20 17:05:39 +01:00
return true
} catch (e) {
window['e'] = e
console.error('BeforesendAtachment', e)
message.uploadingFile = false
return false
2022-02-07 17:55:00 +01:00
}
}
}
2022-02-08 17:44:15 +01:00
2023-10-20 17:05:39 +01:00
return false
}
2022-02-08 17:44:15 +01:00
2023-10-20 17:05:39 +01:00
this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
2022-02-08 17:44:15 +01:00
2023-10-20 17:05:39 +01:00
//
let downloadFile = "";
if (message.file.type == "application/img") {
const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise();
2022-02-09 15:27:10 +01:00
2023-10-20 17:05:39 +01:00
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), ''));
2022-02-09 15:27:10 +01:00
2023-10-20 17:05:39 +01:00
message.file = {
guid: message.file.guid,
image_url: downloadFile,
type: message.file.type
2022-02-08 17:44:15 +01:00
}
2023-10-20 17:05:39 +01:00
return true
2022-02-08 17:44:15 +01:00
}
2023-10-20 17:05:39 +01:00
return false
}
};
2022-03-03 22:57:33 +01:00
2023-10-20 17:05:39 +01:00
}, 1)
}
2022-02-07 17:55:00 +01:00
2023-10-20 17:05:39 +01:00
autologout(expirationDate: number) {
setTimeout(() => {
this.logout();
}, expirationDate)
}
2023-10-20 17:05:39 +01:00
logout() {
2023-10-20 17:05:39 +01:00
SessionStore.setInativity(false)
SessionStore.setUrlBeforeInactivity(this.router.url);
setTimeout(() => {
this.router.navigateByUrl('/', { replaceUrl: true });
}, 100)
2023-10-20 17:05:39 +01:00
}
2023-10-20 17:05:39 +01:00
logoutChat() {
}
2023-09-29 16:40:50 +01:00
2023-10-20 17:05:39 +01:00
async presentAlert(message: string) {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Mensagem do sistema',
message: message,
buttons: ['OK']
});
2021-07-22 17:07:04 +01:00
2023-10-20 17:05:39 +01:00
await alert.present();
}
2023-11-29 12:17:52 +01:00
async logoutUser() {
this.headers = this.headers.set('Authorization', 'Bearer ' + SessionStore.user.Authorization);
this.opts = {
headers: this.headers,
}
let response: any;
try {
response = await this.http.delete<LoginUserRespose>(environment.apiURL + "userauthentication/Logout", this.opts).toPromise();
SessionStore.user.Authorization = "";
SessionStore.user.RefreshToken = "";
} catch (error) {
this.errorHandler.handleError(error);
this.httpErroHandle.loginHttpStatusHandle(error)
captureException(error);
} finally {
return response
}
}
refreshToken() {
return this.http
.put<any>(environment.apiURL + "UserAuthentication/RefreshToken", {
refreshToken: SessionStore.user.RefreshToken,
},)
.pipe(
tap((tokens) => {
console.log(tokens)
SessionStore.user.Authorization = tokens.Authorization;
SessionStore.user.RefreshToken = tokens.refreshToken;
}),
catchError((error) => {
this.logoutUser();
return of(false);
})
);
}
2020-08-06 14:31:07 +01:00
}