am using javascript to connect user login to my website - javascript

am using a JavaScript to connect users to the homepage after the processing page have finish loading and sent the user to the homepage of welcome.html but the fact is how do i end the session after the click the log out button, because after signing out and if they hit back they will still get back the welcome.html, i have try disabling the back button in the browser but that's not awesome, i just need to kill the session so that it won't get them back to the welcome.html after they sign out instead it goes back to login page and require them to sign back in to access the welcome.html, and in this fact am not using php or DB to connect the user login, am using javascript, i don't know if it could work maybe with php simple line of codes or tags.
Here is my JavaScript code, i use to connect the users:
function Login(FORM){
var done=0;
var username=document.login.username.value;
username=username.toLowerCase();
var password=document.login.password.value;
password=password.toLowerCase();
if (username=="jonson111" && password=="happy111") { window.location="HomeAccess_uche/processing.html"; done=1;}
if (username=="wilsonqaz" && password=="open123qaz") { window.location="HomeAccess_wilson/processing.html"; done=1; }
if (done==0) { alert("USERNAME OR PASSWORD IS NOT IN THE DATABASE PLEASE TRY AGAIN!"); }
}
am using dreamweaver and yes i know i will encrypt the Java codes so that users will not understand it, but i just need to end the session after they sign out, this have given me a hard time to figure out i have search everywhere in Google but nothing, anyone can help?

what ever you wrote is all about client side code. there is no point in worry about session , because you don't have a session at all. you are just using javascript. you don't have any server side code to handle session. anybody can see the user name and password by looking at your javascript code. More over once you redirect the page by window.location="HomeAccess_wilson/processing.html"; your " done=1; " and all the javascript variable will reset.

DISCLAIMER: This is a TERRIBLE IDEA. Your site will be completely unsecure. I am ONLY explaining a way to make it work so that a completely innocent, naive user would get the intended effect. Also, this will only work in modern browsers supporting local storage.
function save_login() {
localStorage.loggedIn = true;
}
function save_logout() {
localStorage.loggedIn = false;
}
Call those functions when they log in or log out, and then on every "secure" (but not really, this is totally unsecure) page you do
if (localStorage.loggedIn == false) {
window.location.href = "yoursite.com/login" //or whatever page you
//want to send them to
}

Related

How to stop users from accessing other pages without login permission in Firebase Auth

I have a website that has multiple pages and uses Firebase as backend. I've already implemented firebase auth for the login and I have knowledge of using onAuthChangeState. The problem is now I am trying to find a way to stop the users from accessing other pages without the login page. I want to have some kind of like a "session or token" in php that acts as a key in order for the user to access the page. NOTE! I did not use php because I am also using firebase as a means for hosting my site. BTW Most of the sources I saw only uses a single page and uses a lot of style.display = "none or block", I don't want to go this route, As I like to be more organized and have a proper management in terms of code segregation. That is why I have multiple pages eg; Login.html, Page2.html.
I know how to use javascript redirect
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser){
window.location.href = "page2.html";
}else{
window.location.href = "page1.html";
}
});
But the user might just type https://mysite.firebaseapp.com/page2.html
and access it. Which is what I am trying to prevent.
The solution is that I just needed to create a script that has
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
//Here you can place the code that you want to run if the user is logged in
} else {
window.location.href = "login.html";
}
});
and include it on all the pages just as Harith suggested.
If I understand you correctly, you want to check if a user is logged in or not. If the user is logged in, you want to display the pages, and if the user is not logged in you want to redirect him to the login-page. Correct me if I understood you wrong, but I will give an example of doing what I described above.
This code has to be placed on every page that you won't let users access without logging in.
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
//Here you can place the code that you want to run if the user is logged in
} else {
window.location.href = "login.html";
}
});

Refresh page on new user sign in when using Google oAuth 2.0

I'm trying to make a website using Google Sign For Websites. Mostly just for the sake of learning about how it works.
I've followed the steps outlined in that tutorial Google Provides which works fine. Users can successfully sign into my site, it is able to pass the users ID to the backend and then verify the ID server side using a php script.
Php then creates a session for the user on the website. What I can't figure out is how would I refresh the page when a user clicks the Google Sign in button and the sign in is successful. Refreshing the page would allow the home page to be reloaded with the new php session data.
<div class="g-signin2 signin-button" data-onsuccess="onSignIn" data-theme="dark"></div>
function onSignIn(googleUser){
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://mywebsite.com/tokensignin.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
};
I've tried using simply location.reload() inside of the onload = function() portion of the code. This causes the page to just infinately refresh every time it is loaded however since Google verifys that the user is signed in through this xhr variable every time.
I've tried looking through their reference to use GoogleAuth.isSignedIn.listen(listener) to monitor any changes but it doesn't seem to fullfull what I want it to or I'm not using it correctly since I don't exactly know what the listener should be.
The other option might be to use their GoogleAuth.attachClickHandler(container, options, onsuccess, onfailure) function but I'm not entirely sure how the properly configure the options field/variable.
If someone could provide some insight as to how this world work I would greatly appreciate it.
To summarize if the user is already signed into my website using Google I want the page to do nothing, if they click the signin button, after the sign in is successful I want to refresh the page they are on.
You could add a listener to xhr with a callback function.
xhr.addEventListener("load", loginComplete);
And then create a function:
function loginComplete(evt) {
console.log("Login Complete");
window.location.reload();
}
EDIT:
Ok. Since the listener doesn't help. You will need to check if the user is already logged in. To save that information one thing I could think of would be using cookies.
So you could store the Auth Token you receive from Google and set a cookie for it and check everytime before you make your POST.
Here is a nice js cookie library: https://github.com/js-cookie/js-cookie
Then onload you save the id:
xhr.onload = function() {
Cookie.set('google_token', id_token);
window.location.reload();
};
And the onSignIn function would be like:
function onSignIn(googleUser){
var cookie = Cookie.get('google_token');
if(cookie != undefined){
//cookie is set
return;
}
...
//rest of the function
}
Of course you need to improve this code, for example, check if the token stored in the cookies is still valid, some cases you can just refresh it instead of making the user log in again (the oAuth API provide such things).
Make some security measures to be sure the token is not being injected and etc..
My approach was the same as yours and I indeed ran into the same problem with constant refreshing.
I tried a couple of solutions, the best working one was as follows:
User signs in using GAPI2 triggering callback onGoogleSignIn
Backend checks ID token validity, and signs user in through session on my webapp
If successful, I log the user out using GAPI2, preventing infinite reload, because onGoogleSignIn is never called again
Then I refresh the page and replace the sign-in button with a logout button for my webapp
This solution is of course pretty much useless if you want to manipulate some data on user's Google account, but I found no use for this functionality.
Code for signing someone out of their google account.
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
Why not have your back end redirect (or send info so the page so it can redirect on success)?
What is the need for reloading the login screen?
You could also check out the listener documentation it seems like this may solve what you want. ie. listen for user change and trigger a function or redirect.
https://developers.google.com/identity/sign-in/web/listeners

Prompt for code name when entering a HTML page

I am trying to prompt users to enter a code in order to get into my website. The problem is I am using the following code but some of my user see the prompt window, instead there will be a flashing page. Is there a alternate way to do it?
<script type="text/javascript">
function show_prompt() {
var txtcode = prompt("Please enter your code", "");
txtcode.toLowerCase();
if (txtcode != null && txtcode == "special") {
confirm;
}
else {
window.location = "http://happylemon.asp";
}
}
Instead of a prompt, you should create a proper login page with a form that is submitted to the server and validated. If valid, the user can then be directed to the homepage.
If you use PHP, there are a ton of resources to help with creating a secure login: http://www.google.ca/search?aq=f&sourceid=chrome&ie=UTF-8&q=php+login+page
Why not make a regular authenticate page, but instead of username/password ask for the code? Then submit to server and compare there.
It's NOT safe to put your secret code in Javascript.
There are some typing errors:
I am trying to prompt users to enter a code in order to get into my website.
Should be
I want to keep visitors away from my website.
Just create a normal login page with a login form, and validate the data on the server. No need to ugly (and completely useless) authentication pop-ups.

Show content based on user selection

Im building a site at the moment.
On the layout there are 3 flags for different countries.
Im wondering how i would go about displaying content based on what the user selects, and keeping that selection each time they come back to the site.
Obviously the first time they come to the site the default english will be shown, but once they click on a flag it would change.
Im taking im going to have to use javascript and cookies, i have been looking around and cant seem to find any examples, im wondering if someone could show me how to go about this.
Thanks
Cookies seems like the right idea:
http://www.google.co.uk/search?q=javascript+cookies
There are (probably) only two ways of doing this:
Cookies (i.e. mostly anonymous users)
Registration and getting users to login
For your needs, it sounds as though cookies would be enough.
http://www.quirksmode.org/js/cookies.html is absolutely worth reading from beginning to end.
I am giving a abstract idea of how i might do it..
In the html you write, put a javascript function which sets the flag's id in the browser cookie when you click the flag and then submit the request..
function setCookie(flag_id) //call this when the flag is clicked
{
var allcookies = document.cookie;
if(allcookies)
{
document.cookie += ';flagId=' + flag_id;
}
else
{
document.cookie='flagId=' + flag_id;
}
/*submit the form or whatever you would like to do when the flag is clicked*/
}
Thats it on the client part. You can specify the expiration time for the cookie as well.. for details you can refer the w3schools website. The cookie will stay in the browser and sent to the server on every request.
Now, on the server side, if you are using servlets, just use the following code to get the cookie in the doPost or doGet (in your case when the first request comes from the client).
.....
Cookies[] cookies = request.getCookies();
String flagId = null;
if(cookies != null)
{
for(String cookie:cookies)
{
if(cookie.getName().equals("flagId"))
{
flagId = cookie.getValue();
}
}
}
//use the flag id to decide your content here..
....
Hope this answers your question.

Facebook Connect - Single Sign On Causes Infinite Loop :(

I have a Facebook Connect (FBML) web application that has been live for a while now.
All is working well, however user's are reporting issues with the single sign on (and i have seen the issue on their computer, but have not been able to replicate locally).
With FBC, there is a "event" you can hook into to automatically determine if the user is authenticated to Facebook.
That is achieved via this:
FB.Connect.ifUserConnected(onUserConnected, null);
The onUserConnected function can then do whatever it needs to attempt a single sign on.
For me, what i do is a AJAX call to the server to see if the user has an active website account (based on the Facebook details - user id, which i store in my system when they connect).
If they do, i show a jQuery modal dialog ("Connecting with Facebook") and do a window.location.reload().
The server then kicks in, and does the Single Sign On. This code is executed on every page:
public static void SingleSignOn(string redirectUrl)
{
if (!HttpContext.Current.Request.IsAuthenticated) // If User is not logged in
{
// Does this user have an Account?
if (ActiveFacebookUser != null)
{
// Get the user.
var saUser = tblUserInfo.GetUserByUserId(ActiveFacebookUser.IdUserInfo);
if (saUser != null)
{
// Get the Membership user.
MembershipUser membershipUser = Membership.GetUser(saUser.UserID);
if (membershipUser != null && membershipUser.IsApproved)
{
// Log Them Automically.
FormsAuthentication.SetAuthCookie(membershipUser.UserName, true);
// At this point, the Forms Authentication Cookie is set in the HTTP Response Stream.
// But the current HTTP Context (IsAuthenticated) will read HTTP Request Cookies (which wont have the new cookie set).
// Therefore we need to terminate the execution of this current HTTP Request and refresh the page to reload the cookies.
HttpContext.Current.Response.Redirect(
!string.IsNullOrEmpty(redirectUrl) ? redirectUrl : HttpContext.Current.Request.RawUrl,
true);
}
else
{
HandleUnregisteredFacebookUser();
}
}
else
{
HandleUnregisteredFacebookUser();
}
}
else
{
HandleUnregisteredFacebookUser();
}
}
}
I have never experienced an issue with this, but user's are reporting an "infinite" loop where the dialog gets shown, the window is refreshed, dialog is shown, window is refreshed, etc.
Basically, my AJAX call is saying the user exists, but my single sign on isn't.
Which is hard to believe because the code is very similar:
This is the AJAX Web Service:
if (!HttpContext.Current.Request.IsAuthenticated) // If user is not yet authenticated
{
if (FacebookConnect.Authentication.IsConnected) // If user is authenticated to Facebook
{
long fbId;
Int64.TryParse(Authentication.UserId, out fbId);
if (fbId > 0)
{
tblFacebook activeUser = tblFacebook.Load(facebookUniqueId: fbId);
if (activeUser != null && activeUser.IsActive) // If user has an active account
{
return true;
}
}
}
}
So if the response of this WS is 'true', i do a window.location.reload();
So i have no idea what the issue is (as i cant replicate), sounds like the Single Sign On isn't adding the Forms Authentication cookie properly to the response stream, or the Response.Redirect(Request.RawUrl) isn't reloading the cookie properly.
How do other's handle this?
This is what should happen:
User logs into Facebook (on Facebook itself)
User comes to my site (which has been previously authorised)
My site compares the FBID with the FBID in my DB, and signs them in.
My site is an ASP.NET 4.0 Web Forms application, using the "old" Facebook Connect JavaScript API (FeatureLoader.js), and Forms Authentication.
The only other solution to an AJAX call/window.reload i can think of is an AJAX UpdatePanel.
Can anyone help me out?
EDIT
Also, i realise that i can also use 'reloadIfSessionStateChanged':true to do the reload (which stops the infinite loop), but the problem with this is i cannot show my nice fancy dialog.
So i found a couple of issues.
Firstly, i shouldn't be setting a persistent cookie:
FormsAuthentication.SetAuthCookie(membershipUser.UserName, true);
We should only do this when the user ticks a box such as "Remember Me".
Secondly, i was checking the FB Auth status on every page on the server, so this could have been getting out of sync in the client-side.
Here is my new solution - which is better, and has a failsafe for the dreaded 'infinite loop'.
I no longer check the FB Auth status on the server, i do on the client:
FB.Connect.ifUserConnected(onUserConnected, null); // runs on every page request, on client-side
In the onUserConnection function i do the following:
Call web service to see if user CAN be signed in automatically (same WS as above)
If ok, check a special "Single Sign On" cookie has not been set.
If it hasn't been set, redirect to FacebookSingleSignOn.aspx.
FacebookSingleSignOn.aspx does the following:
Signs the user in using Forms Authentication (same as above)
Creates a special "Single Sign On" cookie to signify a SSO has been attempted
Redirects to the homepage
So, at point 3 above - this is where the infinite loop "could" happen. (as the onUserConnected will run again)
But it is now impossible (i hope) for it to happen, as it will only attempt to do the SSO if they havent already tried.
I clear the SSO cookie on the Facebook Logout action.
Now works well, logic makes sense - and it's done on the client-side (where it should be, as this is where FB does it's magic).
Hope that helps someone else out.

Categories

Resources