Files
doneit-web/src/app/services/auth.service.ts
T
2022-01-14 09:58:18 +01:00

174 lines
5.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';
@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) {
this.headers = new HttpHeaders();
if (SessionStore.exist) {
this.ValidatedUser = SessionStore.user
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
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)
})
}
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;
}
}
logout() {
this.ValidatedUser = null;
}
//Login to rocketChat server
async loginChat(user: UserForm) {
let postData = {
"user": user.username,
"password": user.password,
}
setTimeout(()=>{
console.log('login', SessionStore.user.RochetChatUser, SessionStore.user.Password)
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)
})
}, 1)
let responseChat = await this.httpService.post('login', postData).toPromise();
if(responseChat) {
console.log('Login to Rocket chat OK');
this.ValidatedUserChat = responseChat;
localStorage.setItem('userChat', JSON.stringify(responseChat));
localStorage.setItem('Meteor.loginToken', responseChat['data'].authToken);
localStorage.setItem('Meteor.userId',responseChat['data'].userId);
this.cookieService.set('rc_token', responseChat['data'].authToken);
this.cookieService.set('rc_uid', responseChat['data'].userId);
this.storageService.store(AuthConnstants.AUTH, responseChat);
return true;
}
else{
console.log('Network error');
this.presentAlert('Network error');
return false;
}
}
//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();
}
}