Files
doneit-web/src/app/pages/login/login.page.ts
T
Peter Maquiran 762b6b9f83 Improve
2021-06-09 16:34:14 +01:00

299 lines
7.7 KiB
TypeScript

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { User, UserForm } from 'src/app/models/user.model';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from 'src/environments/environment';
import { AlertController, AnimationController, ModalController } from '@ionic/angular';
import { StorageService } from 'src/app/services/storage.service';
import { AuthConnstants } from 'src/app/config/auth-constants';
import { PhotoService } from 'src/app/services/photo.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import crypto from 'crypto-js'
import { SuccessMessagePage } from 'src/app/shared/popover/success-message/success-message.page';
import { BadRequestPage } from 'src/app/shared/popover/bad-request/bad-request.page';
//import { Token } from '../../models/token.model';
//import { FCM } from 'cordova-plugin-fcm-with-dependecy-updated/ionic/ngx';
/* import { Plugins, PushNotification, PushNotificationToken, PushNotificationActionPerformed } from '@capacitor/core';
const { PushNotifications } = Plugins;
*/
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
logstatus: boolean;
username: string = environment.defaultuser;
password: string = environment.defaultuserpwd;
userattempt: UserForm;
code = []
setPint = false
pin = false
userLoginPreference: any
constructor(
private http: HttpClient,
private notificatinsservice: NotificationsService,
private router: Router,
private authService: AuthService,
private storageService: StorageService,
private toastService: ToastService,
private photoService: PhotoService,
public alertController: AlertController,
private modalController: ModalController,
private animationController: AnimationController,
//private fcm: FCM
) {
let userData = JSON.parse(localStorage.getItem('UserData')) || {}
if (userData.hasOwnProperty('loginPreference')) {
this.userLoginPreference = userData.loginPreference
this.pin = true
} else {
this.userLoginPreference = ''
this.setPint = false
this.pin = false
}
}
ngOnInit() {}
//Function to validade the login inputs
validateUsername() {
return (
this.username.trim().length > 0
);
}
validatePassword() {
return (
this.password.trim().length > 0
);
}
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();
}
/* loginRocketChat() {
let postData = {
"user": this.username,
"password": this.password,
}
this.authService.loginChat(postData).subscribe((res: any) => {
console.log(res.data);
this.storageService.store(AuthConnstants.AUTH, res.data);
console.log('Login to Rocket chat OK');
}, (error: any) => {
console.log('Network error');
this.presentAlert('Network error ' + error);
});
} */
getToken() {
// this.notificatinsservice.getAndpostToken(this.username);
}
async Login() {
if (this.validateUsername()) {
if(this.validatePassword()){
this.userattempt = {
username: this.username,
password: this.password,
domainName: environment.domain,
BasicAuthKey: ""
}
let attempt = await this.authService.login(this.userattempt);
console.log(JSON.stringify(attempt));
if (attempt) {
//this.loginRocketChat();
this.authService.loginChat(this.userattempt);
//this.getToken();
if(!this.pin) {
this.setPint = true
this.pin = true
} else {
this.router.navigate(['/home/events']);
}
}
else {
this.toastService.badRequest('O nome de utilizador e/ou palavra-passe estão incorretas ou verifique a sua conexão com a internet e volte a tentar');
}
}
else{
this.toastService.badRequest('Por favor, insira a sua palavra-passe');
}
}
else {
this.toastService.badRequest('Por favor, insira o seu nome de utilizador');
}
}
setCode(code: string) {
if(this.code.length < 4) {
this.code.push(code)
}
if(this.code.length == 4) {
const code = this.code.join('')
const encrypted = crypto.SHA1(code)
if(this.setPint) {
this.storePin()
} else {
this.pinLogin()
}
}
}
clearCode() {
this.code =[]
}
pinLogin() {
const code = this.code.join('')
const encrypted = crypto.SHA1(code)
if( encrypted == localStorage.getItem('PIN')) {
//this.successMessage()
this.router.navigate(['/home/events']);
} else {
this.badRequest('Pin incorreto')
this.code = []
}
}
storePin() {
const code = this.code.join('')
const encrypted = crypto.SHA1(code)
localStorage.setItem('PIN', encrypted)
this.router.navigate(['/home/events']);
}
async successMessage(message?: string, callback?) {
const enterAnimation = (baseEl: any) => {
const backdropAnimation = this.animationController.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = this.animationController.create()
.addElement(baseEl.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '1', right: '-100%' },
{ offset: 1, opacity: '1', right: '0px' }
]);
return this.animationController.create()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
}
const leaveAnimation = (baseEl: any) => {
return enterAnimation(baseEl).direction('reverse');
}
const modal = await this.modalController.create({
enterAnimation,
leaveAnimation,
component: SuccessMessagePage,
componentProps: {
message: message || 'Processo efetuado' ,
},
cssClass: 'notification-modal'
});
modal.present()
setTimeout(()=>{
if (callback) {
callback()
}
modal.dismiss()
},7000)
}
async badRequest(message?: string, callback?) {
const enterAnimation = (baseEl: any) => {
const backdropAnimation = this.animationController.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', '0.01', 'var(--backdrop-opacity)');
const wrapperAnimation = this.animationController.create()
.addElement(baseEl.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, opacity: '1', right: '-100%' },
{ offset: 1, opacity: '1', right: '0px' }
]);
return this.animationController.create()
.addElement(baseEl)
.easing('ease-out')
.duration(500)
.addAnimation([backdropAnimation, wrapperAnimation]);
}
const leaveAnimation = (baseEl: any) => {
return enterAnimation(baseEl).direction('reverse');
}
const modal = await this.modalController.create({
enterAnimation,
leaveAnimation,
component: BadRequestPage,
componentProps: {
message: message || 'Processo não efetuado' ,
},
cssClass: 'notification-modal'
});
modal.present()
setTimeout(()=> {
modal.dismiss()
},3000)
}
}