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

245 lines
7.4 KiB
TypeScript

import { Injectable } from '@angular/core';
import { StorageService } from './storage.service';
import { HttpClient, HttpHeaders } 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';
@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 ) {
this.headers = new HttpHeaders();
if (SessionStore.exist) {
this.ValidatedUser = SessionStore.user
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
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();
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'
}
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;
}
}
//Login to rocketChat server2
//user: UserForm
async loginChat(user: any) {
const expirationMinutes = 60;
let date = new Date().getTime();
let expirationDate = new Date(new Date().getTime() + expirationMinutes*60*1000);
let postData = {
"user": user.RochetChatUser,
"password": user.Password,
}
let responseChat = await this.httpService.post('login', postData).toPromise();
if(responseChat) {
this.loginToChatWs()
console.log('Login to Rocket chat OK');
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, user);
}
async autoLoginChat(expirationDate:number, user:any){
setTimeout(()=>{
this.loginChat(user);
}, expirationDate)
}
private loginToChatWs() {
setTimeout(()=>{
this.WsChatService.connect();
this.WsChatService.login().then((message) => {
console.log('rocket chat login successfully', message)
this.WsChatService.setStatus('online')
}).catch((message)=>{
console.log('rocket chat login failed', message)
})
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
await this.storage.set(guid.path, message.file.image_url).then(() => {
console.log('add picture to chat IMAGE SAVED')
message.getFileFromDb()
});
return true
} catch(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) {
return false
}
}
}
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();
}
}