Skip to content

Instantly share code, notes, and snippets.

@muzafarali
Created August 11, 2020 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muzafarali/8e8509e4dacca0d75b03e9c9594b599f to your computer and use it in GitHub Desktop.
Save muzafarali/8e8509e4dacca0d75b03e9c9594b599f to your computer and use it in GitHub Desktop.
barcode-keyboard
<button type="button" mat-raised-button color="primary" (click)="startScanner()">Encrypted QR-Code Login</button>
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { NGXLogger } from "ngx-logger";
import { SessionService } from '../session.service';
import { LocalStorage } from '../../libs/localstorage';
import { ToastrService } from 'ngx-toastr';
import { MatInput } from '@angular/material';
import { environment } from './../../environment';
import { isObject } from 'util';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.scss']
})
export class SigninComponent implements OnInit {
@ViewChild(MatInput) input: any;
ngAfterViewInit() {
setTimeout(() => {
if (this.input) {
this.input.focus();
}
}, 300);
}
public user;
public error = '';
public form: FormGroup;
public qrForm: FormGroup;
public currentURL;
constructor(
private _fb: FormBuilder,
private _router: Router,
private _logger: NGXLogger,
private _sessionService: SessionService,
public _localstorage: LocalStorage,
private toastr: ToastrService
) {
console.log("Signin Constructor!");
console.log(environment.locationId);
console.log(window.location.href.split("\#")[0]);
this.currentURL = 'niko.barcode.keyboard://scan/'+encodeURIComponent(window.location.href.split("\#")[0]+"#/session/qrcode/{#CODE}");
}
ngOnInit () {
this.qrForm = this._fb.group({
email: [null, Validators.compose([Validators.required])], //, CustomValidators.email
});
let qrCode = this._localstorage.getObject('qrCode');
console.log('qrCode');
console.log(qrCode);
if(qrCode){
this.loginWithBarCode(qrCode);
}
this.user = this._localstorage.getObject('user_token');
if (this.user.access_token) {
if (this.user.user && typeof this.user.user == 'object') {
let redirectUrl = '';
let keepGoing = true;
this.user.user.roles.map((value, key)=>{
if(keepGoing){
if (value['name'] =='administrator' || value['name'] =='superadmin' ){
redirectUrl = '/apps/list';
keepGoing = false;
} else if (value['name'] == 'transport-management' && this.user.user.last_login == null){
redirectUrl = '/session/reset/' + this.user.encrypt;
keepGoing = false;
} else if (this.user.user.roles.length == 1 && value['name'] == 'transport-officer'){
// console.log('to');
redirectUrl = '/apps/list';
keepGoing = false;
} else if (this.user.user.roles.length == 1 && value['name'] == 'transport-management' && this.user.user.last_login != null){
// console.log('tm');
redirectUrl = '/apps/transport-archive/undefined';
keepGoing = false;
} else if(this.user.user.roles.length == 1 && value['name'] == 'forklift-driver'){
redirectUrl = '/apps/transport';
keepGoing = false;
}else{
redirectUrl = '/apps/list';
keepGoing = false;
}
}
});
this._router.navigate([redirectUrl]);
}
}
this.form = this._fb.group({
email: [null, Validators.compose([Validators.required, CustomValidators.email])], //, CustomValidators.email
password: [null, Validators.compose([Validators.required])]
});
}
onSubmit () {
// this._logger.log(this.form.value);
if (this.form.valid) {
this._sessionService.login(this.form.value).subscribe(
res => {
// this._logger.log("login response");
// this._logger.log(res);
// this._logger.log("this._sessionService.isLoggedIn: " + this._sessionService.isLoggedIn);
// Navigate to the Redirect URL if exist or to dashboard
if (res.success) {
this.toastr.success('Benutzer erfolgreich angemeldet', 'BASF', {
timeOut: 2000
});
if (this._sessionService.isLoggedIn) {
// let redirectUrl = this._sessionService.redirectUrl == '/' ? this._sessionService.redirectUrl || '/apps/transport' : '/apps/transport';
// console.log("Asddddddd", this._sessionService.redirectUrl);
// console.log('res.utype');
// console.log(res.utype);
if(res.utype == 'transport-management'){
this._router.navigate(['/session/reset/'+res.data.encrypt]);
}else if(res.utype == 'tm'){
// console.log('tm');
this._router.navigate(['/apps/transport-archive/undefined']);
}else if(res.utype == 'fd'){
// console.log('fd');
this._router.navigate(['/apps/transport']);
}else{
this._router.navigate(['/apps/list']);
this._sessionService.lastLogin(this.form.value).subscribe(
res2 => {
this._logger.info("last login update");
});
}
}
} else {
this.toastr.error('Bitte versuchen Sie es erneut', 'Login fehlgeschlagen', {
timeOut: 2000
});
}
return false;
},
err => {
this.toastr.error('Bitte versuchen Sie es erneut', 'Login fehlgeschlagen', {
timeOut: 2000
});
}
);
}
}
processBarcode(barcode){
// Create div element and set the barcode value inside this div
//var div = document.createElement("div");
//div.innerHTML = barcode;
//document.body.appendChild(div);
}
nikoBarcodeListener(e){
console.log('e');
console.log(e);
// Event listener for processing scanned data
localStorage["nikoBarcodeKeyboard"] = "";
if(e.url.split("\#")[0] === window.location.href){
window.focus();
console.log('e.newValue');
console.log(e.newValue);
localStorage.setItem('barCode', e.newValue);
this.processBarcode(decodeURIComponent(e.newValue));
}
//window.removeEventListener("storage", this.nikoBarcodeListener, false);
}
startScanner(){
// This function will trigger the scanning process for the current url
// Set currentUrl so the scanner will know where to return the result
var currentUrl = window.location.href.split("\#")[0];
console.log('currentUrl');
console.log(currentUrl);
// Register event listener which will process the scanned data after scanning is completed
window.addEventListener("storage", this.nikoBarcodeListener, false);
// You need to add the {CODE} placeholder in your url string so the scanner can replace it with the value
window.open("niko.barcode.keyboard://scan/" + encodeURIComponent(currentUrl + "#/session/qrcode/{CODE}"), '_self');
//window.location.replace("niko.barcode.keyboard://scan/" + encodeURIComponent(currentUrl + "#/session/qrcode/{CODE}"));
}
loginWithBarCode(code){
console.log('code');
console.log(code);
this.qrForm.patchValue({
email: code,
});
console.log(this.isEmptyObject(code));
if (!this.isEmptyObject(code)) {
console.log('inside form');
this._sessionService.qrlogin(this.qrForm.value).subscribe(
res => {
// this._logger.log("qr code login response");
// this._logger.log(res);
// this._logger.log("this._sessionService.isLoggedIn: " + this._sessionService.isLoggedIn);
// Navigate to the Redirect URL if exist or to dashboard
if (res.success) {
this.toastr.success('Benutzer erfolgreich angemeldet', 'BASF', {
timeOut: 2000
});
if (this._sessionService.isLoggedIn) {
// let redirectUrl = this._sessionService.redirectUrl == '/' ? this._sessionService.redirectUrl || '/apps/transport' : '/apps/transport';
//console.log("Asddddddd", this._sessionService.redirectUrl);
this._router.navigate(['/apps/list']);
}
} else {
this.toastr.error('Bitte versuchen Sie es erneut', 'Login fehlgeschlagen', {
timeOut: 2000
});
}
return false;
},
err => {
this.toastr.error('Bitte versuchen Sie es erneut', 'Login fehlgeschlagen', {
timeOut: 2000
});
}
);
}
}
isEmptyObject(obj) {
console.log(Object.keys(obj).length);
return (obj && (Object.keys(obj).length === 0));
}
}
@muzafarali
Copy link
Author

signin.component.ts line #174 function nikoBarcodeListener() not calling after return from scan a code..
signin.component.ts line #192 startScanner() everytime open a new tab after scan a code..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment