Skip to content
Snippets Groups Projects
LoginSystem.vue 9.62 KiB
<!--
    
  Copyright (c) 2022 NIBIO <http://www.nibio.no/>. 
  
  This file is part of VIPSObservationApp.
  VIPSObservationApp is free software: you can redistribute it and/or modify
  it under the terms of the NIBIO Open Source License as published by 
  NIBIO, either version 1 of the License, or (at your option) any
  later version.
  
  VIPSObservationApp is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  NIBIO Open Source License for more details.
  
  You should have received a copy of the NIBIO Open Source License
  along with VIPSObservationApp.  If not, see <http://www.nibio.no/licenses/>.
    
  Author: Bhabesh Bhabani Mukhopadhyay
  Author: Tor-Einar Skog <tor-einar.skog@nibio.no>
  Dated : 19-Aug-2021
    
-->
<template>
	<div>
		<div v-if="$root.sharedState.uuid" style="margin-top: 15px;">
			<font-awesome-icon style="font-size: large; color: #3d8052; padding-left: 5px;" icon="fa-user" /> <span
				v-text="userLoggedInName"></span>
			<br />
			<a class="vips-btn" v-on:click="handleLogout()">{{ $t("logout.button.label")}}</a>
		</div>
		<div v-else>
			<form class="my-2 my-lg-0">
				<div class="form-group">
					<input class="form-control mr-sm-2" type="text"
						:placeholder="$t('login.username.field.placeholder')"
						:aria-label="$t('login.username.field.placeholder')" v-model="username"
						v-on:keyup.enter="handleLogin()" />
				</div>
				<div class="form-group">
					<input class="form-control mr-sm-2" type="password" :placeholder="$t('login.pwd.field.placeholder')"
						:aria-label="$t('login.pwd.field.placeholder')" v-model="password"
						v-on:keyup.enter="handleLogin()" />
				</div>

				<button class="btn btn-primary" type="button" v-on:click="handleLogin()"
					v-on:keyup.enter="handleLogin()">
					{{ $t("login.button.label")}}
				</button>
				<div v-show="errMsg" class="alert alert-warning alert-dismissible fade show">
					{{errMsg}}
					<button type="button" class="close" data-dismiss="alert" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div v-show="isLogginFail" class="text-danger">
					{{ $t("login.systems.wrong.credential") }}
				</div>
			</form>

		</div>

		<!-- <Sync :isSyncNeeded="isSyncNeeded"/>  -->
		<Sync ref="Sync" />
		<common-util ref="CommonUtil" />
	</div>

</template>

<script>
	import CommonUtil from "@/components/CommonUtil";
	import Sync from '@/components/Sync';


	export default {
		name: "LoginSystem",
		components: {Sync, CommonUtil},
		props: {
			isWelcome: Boolean,

		},
		data() {
			return {
				CONST_URL_DOMAIN: '',
				jsonServerResponse: '',
				userLoggedInName: this.$root.sharedState.user.firstName + " " + this.$root.sharedState.user.lastName,
				username: "",
				password: "",
				appUser: {},
				isSyncNeeded: false,
				errMsg: '',
				isLogginFail: false,
			};
		},
		//emits: {},
		methods: {
			/** Get  user details from local storage */
			getUserFromStorage() {

				let strUser = localStorage.getItem(CommonUtil.CONST_STORAGE_USER_DETAIL);
				if (strUser && strUser != 'undefined') {
					let user = JSON.parse(strUser);
					this.appUser = user; //This user will require in Sync process
					this.$root.sharedState.userId = user.userId;
					this.$root.sharedState.uuid = user.userUuid;
					this.$root.sharedState.user.firstName = user.firstName;
					this.$root.sharedState.user.lastName = user.lastName;
					this.userLoggedInName = this.$root.sharedState.user.firstName + " " + this.$root.sharedState.user.lastName;
				}
				/** Firing event to parent (main.js)  */
				//this.$emit(CommonUtil.CONST_EVENT_LOGIN_USER_DETAIL,user.userUuid, user.firstName,user.lastName);
			},

			/** Check uuid first */
			checkValidUUID() {
				if (localStorage.getItem(CommonUtil.CONST_STORAGE_UUID)) {
					let userUUID = localStorage.getItem(CommonUtil.CONST_STORAGE_UUID);
					/** Fetch to get details */
					let jsonHeader = {Authorization: userUUID};

					fetch(this.CONST_URL_DOMAIN + CommonUtil.CONST_URL_AUTH_UUID, {
						method: "GET",
						headers: jsonHeader,
					}).then((response) => {

						if (response.status != 200 && response.status != 201) {
							this.$root.sharedState.uuid = '';
						} else {

							this.getUserFromStorage();
							/** Sync Operation for valid timestamp */
							this.$refs.Sync.syncOneWayDifferentTimeStamp(this.appUser);
						}
					});
				}
			},

			/** Login process . sending user credential */
			handleLogin() {
				let This = this;

				this.$root.sharedState.uuid = '';
				localStorage.setItem(CommonUtil.CONST_STORAGE_UUID, "");
				let jsonBody = JSON.stringify({"username": this.username, "password": this.password});
				/** Fetch to get UUID */
				fetch(
					this.CONST_URL_DOMAIN + CommonUtil.CONST_URL_AUTH_LOGIN,
					{
						method: "POST",
						headers: {
							"Content-Type": "application/json"
						},
						body: jsonBody
					}
				)
					.then(function (response) {
						if (response.status === 200 || response.status === 201) {
							This.isLogginFail = false;
							return response.json();
						}
						else {
							This.isLogginFail = true;
							return false;
						}
					})
					.then((data) => {
						let jsonServerResponse = '';
						this.jsonServerResponse = data;
						if (this.jsonServerResponse.success) {
							this.username = '';
							this.password = '';
							localStorage.setItem(CommonUtil.CONST_STORAGE_UUID, data.UUID);
						}

						/** Fetch to get details */
						let uuid = localStorage.getItem(CommonUtil.CONST_STORAGE_UUID);
						if (uuid != null && uuid != undefined && uuid.trim() != "") {
							let jsonHeader = {Authorization: uuid};
							fetch(
								this.CONST_URL_DOMAIN + CommonUtil.CONST_URL_AUTH_UUID,
								{
									crossDomain: true,
									method: "GET",
									headers: {
										"Content-Type": "application/json",
										'Authorization': uuid
									}
								}
							)
								.then(response => response.json())
								.then((data) => {
									let loggedUser = data;
									if (loggedUser || loggedUser != 'undefined') {
										localStorage.setItem(CommonUtil.CONST_STORAGE_USER_DETAIL, JSON.stringify(loggedUser));
										this.getUserFromStorage();
										$('.offcanvas-collapse').removeClass('open');
										this.$refs.Sync.isSyncOnewayNeeded(loggedUser);
										this.$refs.Sync.syncTwoWayAtLogin();
										localStorage.setItem(CommonUtil.CONST_STORAGE_UUID, uuid);
										if (this.$router.currentRoute.path != "/") {
											this.$router.push('/')
										}
									}
									
									this.createIndexedDB();
								}
								); // END inner fetch
						}
					}); // END outer fetch
			},
			createIndexedDB() {
				// User is successfully logged in. We create the database (indexedDB)
				// for storing images
				
				// Load the database, in case we need to create the schema
				let dbRequest = indexedDB.open(CommonUtil.CONST_DB_NAME, CommonUtil.CONST_DB_VERSION);
				
		
				dbRequest.onupgradeneeded = function (event) {
					CommonUtil.logInfo("No/outdated IndexedDB database found. Updating schema.");
					// Define the database schema here
					let db = event.target.result;
					if(!db.objectStoreNames.contains(CommonUtil.CONST_DB_ENTITY_PHOTO))
					{
						let store = db.createObjectStore(CommonUtil.CONST_DB_ENTITY_PHOTO, {keypath: "fileName"});
						store.createIndex('observationId', 'observationId', {unique: false});
						store.createIndex('organismId', 'organismId', {unique: false});
					}
					db.close();
				}
			},
			handleLogout() {
				this.$root.sharedState.uuid = '';                           // remove global uuid for other (e.g. menu items etc)
				/** Remove stored data from app in local system - server data still preserve */
				this.removeStoredData();

				this.$emit(CommonUtil.CONST_EVENT_LOGIN_USER_DETAIL, '');
				$('.offcanvas-collapse').removeClass('open');
				this.$router.push('/logout');
			},
			/** Remove stored data on logout */
			removeStoredData() {
				/* Remove localstorage */
				localStorage.removeItem(CommonUtil.CONST_STORAGE_OBSERVATION_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_UUID);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_USER_DETAIL);
				localStorage.removeItem(CommonUtil.CONST_STORE_TIMESTAMP);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_CROP_CATEGORY);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_CROP_ID_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_CROP_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_PEST_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_CROP_PEST_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_IMAGE_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_POI_LIST);
				localStorage.removeItem(CommonUtil.CONST_STORAGE_VISIBILITY_POLYGON);

				/* Remove from IndexedDB */
				//let dbRequest = null;
				/*dbRequest = indexedDB.open(CommonUtil.CONST_DB_NAME, CommonUtil.CONST_DB_VERSION);
				dbRequest.onsuccess = function (evt) {
					let db = evt.target.result;
					db.close();
				}
				*/
				let delReq = indexedDB.deleteDatabase(CommonUtil.CONST_DB_NAME);
				delReq.onsuccess = function() {
					CommonUtil.logInfo("Database was successfully deleted!");
				}
				delReq.onerror = function () {
					CommonUtil.logInfo('could not delete database');
				}
				delReq.onblocked = function () {
					CommonUtil.logInfo('delete DB not successful because of operation block');
				}

			}

		},
		mounted() {
			this.CONST_URL_DOMAIN = CommonUtil.CONST_URL_DOMAIN;
			if (navigator.onLine) {
				this.checkValidUUID();
			}
			else {
				this.getUserFromStorage();
			}
		},
	};
</script>

<style scoped>
</style>