Active tab password protection - javascript

I have some JS for when the user leaves the web app tab and comes back it should prompt a password.
We have the same web app open in multiple tabs for different users and I want to:
When a user changes tabs I want to prompt that a password is needed
The screen should be white before the user enters the password
Sometimes this works and sometimes it doesn't and I don't know why.
I tried clearing my cache, but it didn't appear to work either. Perhaps I should set the page timeout? I just don't want the page to time out because it may be executing processes.
<script type="text/javascript">
// set the password that the user must enter
const password = "12";
// check if the user has already entered the correct password
let authenticated = false;
if (sessionStorage.getItem("authenticated") === password) {
authenticated = true;
}
// function to prompt the user to enter the password
function promptPassword() {
const input = prompt("Please enter the password:");
if (input === password) {
authenticated = true;
sessionStorage.setItem("authenticated", password);
document.removeEventListener("visibilitychange", handleVisibilityChange);
showPage();
} else {
setTimeout(promptPassword, 1);
}
}
// function to hide the page until the user enters the correct password
function hidePage() {
document.body.style.display = "none";
}
// function to show the page after the user enters the correct password
function showPage() {
document.body.style.display = "block";
}
// function to handle tab visibility changes (e.g. when the user switches tabs or minimizes the browser window)
function handleVisibilityChange() {
if (document.hidden) {
authenticated = false;
sessionStorage.removeItem("authenticated");
hidePage();
} else {
if (!authenticated) {
promptPassword();
document.addEventListener("visibilitychange", handleVisibilityChange);
}
}
}
// initialize the page visibility system
if (!authenticated) {
hidePage();
promptPassword();
document.addEventListener("visibilitychange", handleVisibilityChange);
}
</script>

Try this - although it won't run inside this web page because of the sandbox rules
const password = '12'
function clearAuthentication() {
sessionStorage.removeItem('password')
}
function checkAuthentication() {
const authenticated = (sessionStorage.getItem('password')===password)
setBodyVisible(authenticated)
if(!authenticated) setTimeout(promptPassword, 1)
}
function promptPassword() {
sessionStorage.setItem("password", prompt("Please enter the password:"))
checkAuthentication()
}
function setBodyVisible(v) {
document.getElementById('content').style.visibility = v ? 'visible' : 'hidden'
document.getElementById('container').style.backgroundColor = v ? 'lightgreen' : 'lightcoral'
}
window.addEventListener("visibilitychange", ()=>document.hidden ? clearAuthentication() : checkAuthentication())
checkAuthentication()
#container {
width: 600px;
min-height: 100px;
}
<div id="container">
<div id="content">secret document contents here</div>
</div>

Related

How to redirect after phoneNumber linking in firebase?

I need help. I dont know how to detect if the phoneNumber was successfully linked to the user. I want to redirect to other page if action was success. My code is this. *My code works but if I add a function to redirect it doesnt works.
function verifyNumber(){
var user = firebase.auth().currentUser;
var phoneNumber = document.getElementById('phoneNumber');
var signInButtonElement = document.getElementById('sign-in-button');
var inputCode = document.getElementById('code');
var codeButton = document.getElementById('confirm-code');
if(!user.phoneNumber){
// You also need to provide a button element signInButtonElement
// which the user would click to complete sign-in.
// Get recaptcha token. Let's use invisible recaptcha and hook to the button.
var appVerifier = new firebase.auth.RecaptchaVerifier(
signInButtonElement, {size: 'invisible'});
// This will wait for the button to be clicked the reCAPTCHA resolved.
user.linkWithPhoneNumber(phoneNumber.value, appVerifier)
.then(function(confirmationResult) {
// Ask user to provide the SMS code.
phoneNumber.style.display = 'none';
signInButtonElement.style.display = 'none';
//inputCode.style.display = 'inline-block'
//codeButton.style.display = 'inline-block'
var code = window.prompt('Provide your SMS code');
// Complete sign-in.
return confirmationResult.confirm(code);
//updateStatus() doesnt work
});
}
}
function updateStatus(){
var user = firebase.auth().currentUser;
if(user.phoneNumber){
window.location.href = "../home/home.html";
}else{
alert('Ha ocurrido un error');
}
}
You have to wait for the async function confirmationResult.confirm to complete before checking and redirecting.
user.linkWithPhoneNumber(phoneNumber.value, appVerifier)
.then(function(confirmationResult) {
// Ask user to provide the SMS code.
phoneNumber.style.display = 'none';
signInButtonElement.style.display = 'none';
//inputCode.style.display = 'inline-block'
//codeButton.style.display = 'inline-block'
var code = window.prompt('Provide your SMS code');
// Complete sign-in.
return confirmationResult.confirm(code);
})
.then(() => {
// Wait for linking to complete before redirecting.
updateStatus();
});
}

Signout Then Reload Page Automatic Sign In

On my multi-page HTML website (hosted by Firebase), I have a sign in/out button. Whenever I press sign out, the sign out button becomes the sign in button, thanks to my CSS, and the console reports "user not logged in".
However, when I reload the page or navigate to a different one (Ctrl+R and Ctrl+Shift+R make no difference), the sign out button reappears, and the console reports "user logged in", as if the server doesn't remember the user should be signed out, and not automatically signed in after the page reloads.
Here's what I use for sign in. Note that setButtons() is my code to change the CSS to show what button I need to. gLogin() is called when the Sign In button is pressed, and gLogout is called when the Sign Out button is pressed.
var signedIn;
var curUser = null;
function updateUser(user)
{
if (user) {
curUser = user;
signedIn = true;
console.log("User is logged in");
// User is signed in.
} else {
curUser = null;
signedIn = false;
console.log("User is not logged in");
// No user is signed in.
}
setButtons(signedIn);
}
firebase.auth().onAuthStateChanged(updateUser);
function gLogin() {
firebase.auth().signInWithPopup(gProvider).then(function (result) {
var token = result.credential.accessToken;
var user = result.user;
signedIn = true;
location.reload(true);
}).catch(function (error) {
console.log(error);
});
}
function gLogout() {
firebase.auth().signOut().then(function () {
signedIn = false;
updateUser(null);
}).catch(function (error) {
console.log(error);
});
}
I figured it out: Apparently, the issue was that I didn't set a default auth persistence state. From what I understand, this meant that persistence would have undocumented behavior. Here's what I added to each of my pages' scripts:
firebase.auth()
.setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function() {
console.log("Persistence set");
}).catch(function(error) {
console.log(error);
});

Navigate stop only when going to another website

I am using following code to trigger the are you sure leaving website alert but for some reason its not recognising my if else condition in it and only works if I only put return true in window.onbeforeunload = function() { return true } . Is there a way I can trigger this alert only when user is navigating away from my website cause at the moment without if else condition its asking if user tries to navigate in the same website as well?
window.onbeforeunload = function() {
var location = window.document.activeElement.href;
if (typeof location != 'undefined')
{
console.log(location);
} else { reutn true; }
};
You can set a flag and toggle that flagged based on host of links that are clicked
var host = location.hostname,
allowNavigate = false;
window.onbeforeunload = function() {
if (!allowNavigate) {
return 'Message string';// not what actually gets displayed in most browsers these days
}
//don't return anything
return;
};
window.onload = function() {
document.querySelectorAll('a').forEach(function(a) {
a.addEventListener('click', function(e) {
allowNavigate = this.hostname === host;
});
});
};
The hostname on this page for example is "stackoverflow.com"
DEMO
You can add the "window.onbeforeunload" dynamically for the links you want to see the prompt message
and remove the "window.onbeforeunload" for the links you don't want prompt
<a onClick="a(true)" href="https://www.w3schools.com">Click here to get promt before navigate</a>
<br>
<a onClick="a(false)" href="https://jsfiddle.net/">Click here to navigate without promt </a>
<script>
function a(showPrompt){
window.onbeforeunload = showPrompt ? function(e) {return '';}: null;
}
</script>
https://jsfiddle.net/vqsnmamy/1/

Angular: When does app.config get called?

I am creating a chrome extension UI using angular. I want to make it so when the user clicks the icon in the upper right the correct screen appears. If the user is not logged in they should go to the login page. If the user is logged in and in drawing mode then they should go to the drawing screen, if they are logged in and not drawing then they should go to the main menu.
My main problem is checking whether or not they are already in drawing mode. I am sending a message to my content scripts to check whether or not I am in drawing mode, but for some reason this callback is never getting called! Very disappointing. I'm not sure when code in app.config gets called; when does it?
app.js
app.config(function($stateProvider, $urlRouterProvider) {
var rootRef = new Firebase(mysterious_url);
var user = rootRef.getAuth();
chrome.tabs.sendMessage('isInDrawingMode', {action: 'isInDrawingMode'}, function(response) {
if (!user) {
$urlRouterProvider.otherwise('/login');
} else if (response.inDrawingMode) {
$urlRouterProvider.otherwise('/draw');
} else {
$urlRouterProvider.otherwise('/main');
}
});
contentscripts.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse){
// Toggle User Canvas Messages
if ( request.toggle === 'off' ){
// toggleUserCanvasOff();
disableDrawingMode();
sendResponse({confirm:'canvas turned off'});
} else if ( request.toggle === 'on' ){
enableDrawingMode();
// toggleUserCanvasOn();
sendResponse({confirm:'canvas turned on'});
// Initialize toggle status for popup button
} else if ( request.getStatus === true ){
sendResponse({status:toggle});
} else if (request.canvasData) { // new Canvas data
onCanvasData(request.site, request.user, request.data);
} else if (request.erase){
eraseUserCanvas();
} else if (request.changeColor){
lineColor = request.changeColor;
} else if (request.image){
getCurrentUser(function(user){
var userCanvas = $('.'+ user);
addOneTimeClickEvent(userCanvas, addImage, request.image);
});
} else if (request.action) {
sendResponse({inDrawingMode: "true"});
}
}
);

jQuery mobile pageshow event not firing on first $.mobile.changePage()

I'm writing a phonegap/jquery mobile app and have an issue I cant seem to solve.
When the app loads (device ready and jqm_mobile_init) fire and the app creates/opens a database and checks if a user is signed in (just a flag in the db). If so the app calls $.mobile.changePage("#home", {transition:"none"}); to redirect them to the "home" page.
Then on the "home" page pageshow event I grab a load of info from the db and append it to a listview within the home page.
However, the first time this runs (with the $.mobile.changePage event) the pageshow event isn't trigged (so none of my data gets appended to the listview). If I navigate around the app and then visit the page the data shows fine. This only happens when using $.mobile.changePage to change to the home page.
How can I make pageshow() fire on $.mobile.changePage? or is there another way to do it?
Heres my code:
/************************************************
Try to create/open the DB, if not catch the error
***********************************************/
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'test';
var version = '1.0';
var displayName = 'test Database';
var maxSize = 200000; // in bytes
// database instance in db.
var db = openDatabase(shortName, version, displayName, maxSize);
// Create tables
createTables(db);
// Check if there is a signedin user
isUserSignedInQuery(db);
}
} catch(e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
// Universal null/blank data handler
function nullDataHandler(transaction, results) { }
// Universal error callback
function errorHandler(error) {
//alert("Error processing SQL: " +error.message+ " Error Code: " +error.code);
}
// Create tables if dont already exist
function createTables(db) {
db.transaction(
function (transaction) {
// create tables
}
);
}
/**********************************************************************************************
Check if there is a signed in user, if so redirect to listings page, if not display login page
**********************************************************************************************/
function isUserSignedInQuery(db) {
db.transaction(
function (transaction) {
transaction.executeSql("SELECT * FROM USERS WHERE signedIn=1;",
[], // array of values for the ? placeholders
isUserSignedInDataHandler, errorHandler);
}
);
}
function isUserSignedInDataHandler(transaction, results) {
// Handle the results
if (results.rows.length > 0) {
//console.log("someones logged in!");
// Assign signed in user to global var
console.log("logged in user = " + results.rows.item(0).id);
window.currentSignedInUserId = results.rows.item(0).id;
$.mobile.changePage( "#home", { transition: "none"} );
} else {
$.mobile.changePage( "#login", { transition: "none"} );
}
}
/**********************************************************************************************
Sign in page:
**********************************************************************************************/
function doesSigningInUserAlreadyExistQuery(db) {
db.transaction(
function (transaction) {
transaction.executeSql("SELECT * FROM USERS WHERE username='"+usernameValue+"' ORDER BY id LIMIT 0,1;",
[], // array of values for the ? placeholders
doesSigningInUserAlreadyExistDataHandler, errorHandler);
}
);
}
function doesSigningInUserAlreadyExistDataHandler(transaction, results) {
// User exists, sign them in.
if (results.rows.length > 0) {
//console.log("user exists");
// Find number of rows
var len = results.rows.length;
//console.log(len);
for (var i=0; i<len; i++){
//console.log(results.rows.item(i));
db.transaction(
function (transaction) {
transaction.executeSql('UPDATE USERS SET signedIn = 1 WHERE username="'+usernameValue+'"');
}
);
// Assign signed in user to global var
window.currentSignedInUserId = results.rows.item(0).id;
// Redirect to home/listings page
$.mobile.changePage( "#home", { transition: "slidefade"} );
}
// User is new, create them and sign them in
} else {
db.transaction(
function (transaction) {
transaction.executeSql('INSERT INTO USERS (username, password, userId, defaultHandler, autoSync, updateCaseTypes'
+', updateHistorical, updateFavorite, signedIn) '
+'VALUES ("'+usernameValue+'", "eclipse", "userid321", "Another User", 1, 1, 1, 1, 1);', [],
function (transaction, resultSet) {
if (!resultSet.rowsAffected) {
// Previous insert failed.
alert('No rows affected!');
return false;
}
alert('insert ID was '+resultSet.insertId);
//Assign signed in user to global var
window.currentSignedInUserId = resultSet.insertId;
});
}
);
// Redirect to home/listings page
$.mobile.changePage( "#home", {
reloadPage: true,
transition: "slidefade"} );
}
}
$('#login').live('pageshow', function(event) {
console.log(window.currentSignedInUserId); // This is empty - global var not working
// Should this be tap??????? Find out. -----------
$('a#signIn').click(function() {
// Get values of all fields & buld vars
var username = $('#login-username');
var password = $('#login-password');
// Check if fields are empty
if( !username.val() ) {
username.addClass('empty');
$('label.login-username').addClass('blank');
}
if( !password.val() ) {
password.addClass('empty');
$('label.login-password').addClass('blank');
}
// If both not empty, check if user exists, if so sql update if not sql insert
if (username.val() && password.val()) {
// Get username
usernameValue = username.val();
// Run function
doesSigningInUserAlreadyExistQuery(db);
}
});
});
$('#home').live('pageshow', function(event) {
console.log("Page show fired on recordings page");
db.transaction(getRecordingsQuery, getRecordingsDataHandler, errorHandler);
// get stuff, loop through it and append
// Refresh the list to add JQM styles etc
$('#recordings-list').listview('refresh');
}
});
I've managed to resolve it, its not really a proper fix but it works at the expense of a screen flicker whilst the screen refreshes.
If it helps anyone, I added allowSamePageTransitions: true which solved the issue (at the expense of a flicker).
You should be using on() instead of live(). live() has been deprecated.
Have you tried putting it in the beforepageshow instead of pageshow? It seems like a better place to put data gathering/dynamic page element generation.

Categories