mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-18 20:47:54 +00:00
316 lines
10 KiB
TypeScript
316 lines
10 KiB
TypeScript
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 { HttpService } from './http.service';
|
|
import { BehaviorSubject } from 'rxjs';
|
|
import { AuthConnstants } from '../config/auth-constants';
|
|
import { AlertController } from '@ionic/angular';
|
|
import { SessionStore } from '../store/session.service';
|
|
import { AESEncrypt } from '../services/aesencrypt.service';
|
|
import { CookieService } from 'ngx-cookie-service';
|
|
import { WsChatService } from 'src/app/services/chat/ws-chat.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';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthService {
|
|
userData$ = new BehaviorSubject<any>('');
|
|
userId$ = new BehaviorSubject<any>('');
|
|
headers: HttpHeaders;
|
|
public ValidatedUser: UserSession;
|
|
public wsValidatedUserChat:any;
|
|
public ValidatedUserChat:any = {}
|
|
public isWsAuthenticated: boolean = false;
|
|
opts:any;
|
|
|
|
constructor(
|
|
private http: HttpClient,
|
|
private httpService: HttpService,
|
|
private storageService:StorageService,
|
|
public alertController: AlertController,
|
|
private aesencrypt: AESEncrypt,
|
|
private cookieService: CookieService,
|
|
private WsChatService: WsChatService,
|
|
private router: Router,
|
|
private NfService:NfService,
|
|
private processesService: ProcessesService,
|
|
private AttachmentsService: AttachmentsService,
|
|
private storage: Storage,
|
|
private initialsService: InitialsService,
|
|
public p: PermissionService, ) {
|
|
|
|
this.headers = new HttpHeaders();
|
|
|
|
if (SessionStore.exist) {
|
|
this.ValidatedUser = SessionStore.user
|
|
|
|
if(this.p.userPermission(this.p.permissionList.Chat.access) == true ){
|
|
this.loginToChatWs()
|
|
}
|
|
}
|
|
|
|
if (localStorage.getItem("userChat") != null) {
|
|
this.ValidatedUserChat = JSON.parse(localStorage.getItem('userChat'));
|
|
}
|
|
|
|
}
|
|
|
|
async login(user: UserForm, {saveSession = true}): Promise<LoginUserRespose> {
|
|
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<LoginUserRespose>(environment.apiURL + "UserAuthentication/Login", '', this.opts).toPromise();
|
|
console.log(response);
|
|
|
|
if(saveSession) {
|
|
this.SetSession(response, user)
|
|
}
|
|
} catch (error) {
|
|
|
|
} finally {
|
|
return response
|
|
}
|
|
|
|
}
|
|
|
|
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 if(session.RoleID == 99999873) {
|
|
session.Profile = 'Assistant'
|
|
}
|
|
else if(session.RoleID == 99999874) {
|
|
session.Profile = 'Department boss'
|
|
}
|
|
else if(session.RoleID == 99999875) {
|
|
session.Profile = 'Director'
|
|
}
|
|
else if(session.RoleID == 99999876) {
|
|
session.Profile = 'Deputy Director'
|
|
}
|
|
else if(session.RoleID == 99999885) {
|
|
session.Profile = 'Secretariat'
|
|
}
|
|
else if(session.RoleID == 99999886) {
|
|
session.Profile = 'General secretary'
|
|
}
|
|
|
|
session.Password = user.password
|
|
session.RochetChatUser = user.username.split('@')[0]
|
|
|
|
session.BasicAuthKey = user.BasicAuthKey
|
|
|
|
SessionStore.reset(session)
|
|
this.ValidatedUser = SessionStore.user;
|
|
this.storageService.store(AuthConnstants.USER, response);
|
|
|
|
return true;
|
|
}
|
|
|
|
this.initialsService.getInitials(session.FullName);
|
|
}
|
|
|
|
//Login to rocketChat server2
|
|
//user: UserForm
|
|
async loginChat() {
|
|
|
|
const expirationMinutes = 30;
|
|
let date = new Date().getTime();
|
|
let expirationDate = new Date(new Date().getTime() + expirationMinutes*60*1000);
|
|
|
|
let postData = {
|
|
"user": SessionStore.user.RochetChatUser,
|
|
"password": SessionStore.user.Password,
|
|
}
|
|
|
|
let responseChat = await this.httpService.post('login', postData).toPromise();
|
|
|
|
if(responseChat) {
|
|
|
|
this.ValidatedUserChat = responseChat;
|
|
localStorage.setItem('userChat', JSON.stringify(responseChat));
|
|
this.storageService.store(AuthConnstants.AUTH, responseChat);
|
|
}
|
|
else{
|
|
console.log('Network error');
|
|
this.presentAlert('Network error');
|
|
}
|
|
|
|
this.autoLoginChat(expirationDate.getTime() - date);
|
|
}
|
|
|
|
async autoLoginChat(expirationDate:number) {
|
|
setTimeout(()=>{
|
|
this.loginChat();
|
|
}, expirationDate)
|
|
}
|
|
|
|
loginToChatWs() {
|
|
setTimeout(()=>{
|
|
|
|
this.WsChatService.connect();
|
|
this.WsChatService.login().then((message: any) => {
|
|
|
|
SessionStore.user.RochetChatUserId = message.result.id
|
|
SessionStore.save()
|
|
|
|
// console.log('user session', SessionStore.user)
|
|
|
|
|
|
this.WsChatService.setStatus('online')
|
|
|
|
}).catch((message) => {
|
|
console.log('rocket chat login failed', message)
|
|
})
|
|
|
|
|
|
// 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
|
|
|
|
console.log('========================================',guid)
|
|
// await this.storage.set(guid.path, message.file.image_url).then(() => {
|
|
// console.log('add picture to chat IMAGE SAVED')
|
|
// // message.getFileFromDb()
|
|
// });
|
|
|
|
message.downloadFileMsg()
|
|
|
|
return true
|
|
} catch(e) {
|
|
console.log('failed to upload to server', 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.log(e)
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
this.NfService.downloadFileMsg = async (message: MessageService, room?: RoomService) => {
|
|
|
|
// console.log('FILE TYPE', message.file.type)
|
|
let downloadFile = "";
|
|
if (message.file.type == "application/img") {
|
|
const event: any = await this.AttachmentsService.downloadFile(message.file.guid).toPromise();
|
|
|
|
console.log('FILE TYPE 22', message.file.guid)
|
|
|
|
if (event.type === HttpEventType.DownloadProgress) {
|
|
//this.downloadProgess = Math.round((100 * event.loaded) / event.total);
|
|
// console.log('FILE TYPE 33', message.file.type)
|
|
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(() => {
|
|
// console.log('IMAGE SAVED')
|
|
});
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
};
|
|
|
|
}, 1)
|
|
}
|
|
|
|
autologout(expirationDate:number) {
|
|
setTimeout(()=>{
|
|
this.logout();
|
|
}, expirationDate)
|
|
}
|
|
|
|
logout() {
|
|
|
|
this.ValidatedUser = null;
|
|
localStorage.removeItem('userChat');
|
|
|
|
SessionStore.setInativity(false)
|
|
SessionStore.setUrlBeforeInactivity(this.router.url)
|
|
setTimeout(() => {
|
|
this.router.navigateByUrl('/', { replaceUrl: true });
|
|
}, 100)
|
|
|
|
}
|
|
|
|
//Get user data from RocketChat | global object
|
|
getUserData() {
|
|
this.storageService.get(AuthConnstants.AUTH).then(res=>{
|
|
this.userData$.next(res);
|
|
});
|
|
}
|
|
|
|
logoutChat() {
|
|
//this.storageService.clear();
|
|
/* this.storageService.removeStorageItem(AuthConnstants.AUTH).then(res =>{
|
|
this.userData$.next('');
|
|
this.router.navigate(['']);
|
|
}) */
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|