How to lock a website with password in google? - javascript

I'm trying to lock youtube for reasons I'm not going to detail and I tried this script, but it only asks for the password. Nothing else happens, not even the console.log(). Any suggestions?
var pass = prompt("YouTube is locked. Password to unlock");
if (pass != "password") {
document.getElementById('watch7-content').innerHTML = location.replace("google.com");
console.log('wrong');
}
What I'm trying to do is ask for the password with prompt() and if it's not the password it'll redirect to google.com. It uses the video player as a reference for the url replacement, but i don't know if it works. Again, I don't think it's even working because it won't even console.log()...

location.replace does perform a reload the page and this is the case why your console.log is not visible in console. If you move console.log on top of location.replace and you preserve console history (so it is not cleared between reloads) you will see it is executed successfully.
Also make sure to use full url with location.replace:
location.replace('https://google.com')

Related

How to check if a web page is open or not?

I have a website where users message each other through another website. My problem is that everytime user click on message item this action opens a new tab.
Having a lot of conversations makes this quite annoying, especially when using on a smartphone.
Is there any way to check if the website for texting is open?
If you are using window.open() you can add the target parameter.
A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.
example
window.open("https://www.mozilla.org/", "mozillaTab");
You are looking for postMessage. Synapsis:
postMessage(message, targetOrigin, transfer)
message is the actual message you want to send
targetOrigin specifies which domain is the target
transfer is a sequence of transferrable objects that are transmitted with the message
So, what you really want is to have this conversation:
Page1: are you there?
Page2: yes
or
Page1: are you there?
... (timeout)
I will call Page2 the page whose existence we wonder about and Page1 the page which wonders about Page2's existence.
First of all, you need a message handler at both Page1 and Page2. Synapsis:
window.addEventListener("message", (event) => {
if (event.origin !== "http://example.org:8080")
return;
//check event.data and see what happens
}, false);
On Page 2, your message handler will need to check whether the message asks about its existence and calls postMessage('Yes, I am here', event.origin); if so. Page1, on the other hand initiates the messaging by calling postMessage('Are you there?', theurl); (where you need to replace theurl with your value). Now, Page1 expects a message. If the message arrives, then Page2 exists. If not, then after a timeout you need to handle the nonexistence of Page2. So, you will have something like this at Page1:
var wasFound = false;
postMessage('Are you there', theurl);
setTimeout(function() {
if (!wasFound) {
//The page needs to be opened
}
}, 500);
Naturally, you will need to set wasFound to true when you receive a message from Page2 and you will need to make sure that the message handler sees the same wasFound variable that your timeout checks for.

Issue when using firebase.auth().onAuthStateChanged accross two pages

I am having a small problem with two html pages which used to work in the past.
First, I have a login page (login.html) containing this kind of code:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.open("main.html",'_self');
} else {
// No user is signed in.
prompt for login ....
......
}
});
Second, I also have this page (main.html) containing this sort of code:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
do serious work ....
......
} else {
// Let us double check:
let theUser = firebase.auth().currentUser;
if (!theUser) {
// No user is signed in.
window.open("login.html",'_self');
}
// We need some patience :)
......
}
});
Once a user is logged in, things are supposed to go to main.html; and this is how it used to work. But now, for some unknown reason; when I log in, even though I have provided my credentials, the flow goes to main.html (as it should) but immediately bounces back to login.html.
I have been able to check that the block (in the main.html):
firebase.auth().onAuthStateChanged(function(user) {...}
does not detect me as logged in. Why is that?
P.S.
I have verified that my domain is added in the list of Authorized domains in the Firebase console.
I am encountering the same issue. I narrowed it down to Chrome. It seems to think that Chrome isn't allowed to save cookies when it is (I checked the settings). Might be an issue with a recent Chrome update? Just as a sanity check, try it on Firefox and let me know if that works. It did for me.
UPDATE: This is what I get back when I console log the error
{code: "auth/web-storage-unsupported", message: "This browser is not
supported or 3rd party cookies and data may be disabled.", a: null}
UPDATE 2: Strangely enough, I disabled cookies, tried and it failed. Re-allowed cookies (just as it was initially) and it works now. I would suggest capturing this error and prompting users to ensure they check their browser settings. I'm going to do this in my app.

IE resubmitting authentication header on failed login

I am supporting an application that uses basic authentication and is working mostly correctly, but on IE it is sending the authentication header twice when the authentication attempt fails.
var authorizationBasic = btoa(stUsername + ":" + stPassword);
loginRequest.open("POST", stUrl, true,stUsername, stPassword);
loginRequest.setRequestHeader("WWW-Authenticate", "Basic "+authorizationBasic);
loginRequest.withCredentials = true;
loginRequest.onreadystatechange = function () {
if (loginRequest.readyState == 4){
... some logic....
}
}
loginRequest.send();
This code is working fine on other browsers, but IE uses 2 authentication attempts every time the user makes the call.
When I get to the first call in the onreadystate it already has sent the duplicated headers. Anyone knows how to fix this?
Thank you,
Update 1: checking the expected behavior the browser is supposed to send an opening request without the credentials:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
And on the 401 error is supposed to answer back with the credentials, this is the behavior I'm seeing on Chrome using fiddler, but IE sends the credentials on both requests causing the double hit to the login attempts counter. Is this a bug, or is there any way to modify this behavior?
After much searching I was able to find a hacked solution to this, please don't judge me for it and let me know if you find something better. I still think this is an IE bug and it might get fixed in the future.
var authorizationBasic = btoa(stUsername + ":" + stPassword);
document.execCommand("ClearAuthenticationCache", false); (1)
loginRequest.open("HEAD", vUrl, true,"whatever","blah"); (2)
loginRequest.setRequestHeader("WWW-Authenticate", "x-Basic "+authorizationBasic);
loginRequest.setRequestHeader("Authorization", "Basic "+authorizationBasic); (3)
loginRequest.withCredentials = true;
loginRequest.onreadystatechange = function () {
if (loginRequest.readyState == 4){
if (loginRequest.status == 200) {
var dummyReq = fGetRequest();
dummyReq.open("HEAD", vUrl, false,stUsername, stPassword);
dummyReq.setRequestHeader("WWW-Authenticate", "x-Basic "+authorizationBasic); (4)
window.location.href = vUrl;
Here's how it works:
This is the part that I hate the most, it clears authentication information of ALL open sessions on IE, have to use it with care, when I wasn't using it I was getting weird results, so I'm trying to modify my log out procedure to avoid the use of this instruction.
IE sends this username and password on the first request (the one that is supposed to have no authentication information), you can put whatever fake information here, just be sure you don't use a real username. If we don't send this information we'll get the login prompt.
Here goes the real authentication information, the status of the request on the readystatechange event will depend on this information.
After you have checked credentials do the regular login requests, if you don't do this you will get the login prompt.
I'm still using the regular authentication method with all other browsers. If you know of a better solution, please let me know.

Java script, PHP

I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code
<script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
location.href = 'Logout.php';
}
function pageHidden(evt){
if (str==='delete')
logout();
}
window.addEventListener("pagehide", pageHidden, false);
</script >
Examples I tried....
// 1st approach
//window.addEventListener("beforeunload", function (e) {
/// var confirmationMessage = "Do you want to leave?";
// (e || window.event).returnValue = confirmationMessage;
// return confirmationMessage;
// });
// 2nd approach
// window.onbeforeunload = myUnloadEvent;
// function myUnloadEvent() {
// console.log("Do your actions in here")
// }
// 3rd approach
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....
Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.
You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:
session_set_cookie_params(0);
session_start();
session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.
Hope this helps! :)
The correct way to logout is related to how they are logged in.
In PHP, the login state is typically managed by sessions. By default the timeout is 24 minutes of inactivity, but you can easily reduce it.
When a user logs out, you typically reset one or more session variables, and, while you’re at it, kill off the current session, and delete the session cookie.
However, you cannot rely on a user to log out, and many typically just wander off. This is why there is always a relatively short timeout on sessions.
If you want to automatically logout when the tab is closed, you will need JavaScript to intercept the process with window.onbeforeunload and then use Ajax to send the logout to the server.
As regards the database, you normally do not record the login state in the database. You may record the login time, and if you like, the logout time, but remember that may be never.

Meteor.js redirect to "dedicated" page before email is verified

I have this logic that I'm trying to implement and I'm failing to do so... Here is the deal. I have implemented the confirmation mail for new users and now with the code that I will paste bellow I'm basically blocking the user from login into the app before he confirms he's email address. Okay fairly clear. But now I want to send him to a dedicated "verifiaction" page where it will only be some kind of text like "You need to verify you email before you can login, click to resend the confirmation link, blablabla". Im also using iron router.
Im doing this for the check:
//(server-side) called whenever a login is attempted
Accounts.validateLoginAttempt(function(attempt){
if (attempt.user && attempt.user.emails && !attempt.user.emails[0].verified ) {
console.log('email not verified');
// Router.go('verification'); - some kind of my "logic" what I want to
}
return true;
});
There is a discussion with the same issue here and in the comments, a user suggests resending the verify email token and alerting the user, instead of redirecting to a page, which would be simpler. The code for that would look like:
Accounts.validateLoginAttempt(function(attempt){
if (attempt.user && attempt.user.emails && !attempt.user.emails[0].verified ) {
Accounts.sendVerificationEmail(user._id);
Alert('Your email has not been verified, we have re-sent the email. Please verify before logging in.');
//you could also use a modal or something fancy if you want.
}
return true;
});
If definitely want to create a page, there is an answer here about ways to do that, but how you do it it depends on whether you want it to be part of the layout or not.

Categories