I am making a website that uses the Javascript Parse SDK and calling Parse.User.current() only works some of the times causing my redirect to kick users back to the login page even though Parse.User.logOut() has not been called. I am using the User class and not having them login through Facebook.
Function to see if there is an active session. If there is, the page loads, otherwise the user should be redirected to the main page:
function checkUser(){
var currentUser = Parse.User.current();
if (currentUser) {
//the page loads
} else {
//redirect user to the login page
window.location = 'login-url';
}
}
The above code is called in the <head> tag of each page:
<script>checkUser()</script>
When the user logs in, I check to make sure Parse.User.current() is not null and then redirect them to the main page. The first time they are sent to the main page, the checkUser() function does not find a user, and they are sent back to the login page where my redirect() function (below) sends them back to the main page because Parse.User.current() is not null when it checks it. The second time they are sent to the main page, Parse.User.current() has a user, so they stay on this page.
To a user logging in, the above is not a problem, since after logging in, they end up on the right page, but the real issue arises when the user tries to navigate to a different page using the tabs name. When one of these is clicked, checkUser() on the new page does not find a user so the user is pushed back to the login page, where redirect() does find a user and sends them back to the main page where checkUser() finds a user as well, so they end up back on the main page again.
I do not know what the issue is, but I think it has something to do with initially changing the pages programatically because if I log in and then type the url of a different page into my address bar instead of clicking on a tab, the checkUser() finds a user and then I can use the tabs to switch pages without a problem. Additionally, it all occasionally works perfectly when I am using Chrome (this problem always occurs with Firefox) and then I log out and log back in and the same issue comes back.
My login code:
$("#login").submit(function(event){
event.preventDefault();
var name=$("#username").val();
var password=$("#password").val();
Parse.User.logIn(name, password, {
success: function(user){
if(Parse.User.current()){
window.location="main-page";
} else{
alert("no user");
}
}, error: function(user, error){
alert("login error:" + error.message);
}
});
});
Redirect called on the login page:
function redirect(){
var currentUser = Parse.User.current();
if (currentUser) {
//a user is found, so they are taken to the main page
window.location = 'main-page';
} else {
//the user has to log in
}
}
I was able to solve my problem by storing the userid in a cookie instead of relying on Parse.User.current(). I essentially just followed the steps outlined in http://www.w3schools.com/js/js_cookies.asp and since the login function I was using has a callback with the object, I could easily get the user's id when they log in using user.id.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
//stay on page
} else {
window.location.href="login-url";
}
}
function removeCookie() {
setCookie("userid", "", -1); //setting the userid to an empty string
//and setting the expiration time to have passed
}
On the login and signup callback, I set the cookie and then redirect to the main page
setCookie('userid', user.id, 1);
window.location.href="main-page-url";
On all pages that require a user to be logged in, I check the cookie by calling checkCookie(); in the <head>. On the signin page, I also have a redirect so that if the user is signed in, they are redirected to the main page. This function is the same as checkCookie(), but I redirect when there is a user instead of when there is not one.
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
window.location.href="main-page-url";
}
}
When the user logs out, I still call Parse.User.logOut(); but I also call removeCookie(); before redirecting to the log in screen.
Related
The following function is to redirect the user to "Select Stream.html" when the user logs in.It keeps on replacing the location over and over again.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
window.location.replace("Select Stream.html");
// User is signed in.
} else {
// No user is signed in.
window.location.replace("index.html");
}
});
I am new to coding.
Here is the Log in Function
function login()
{
var userEmail=document.getElementById("email-field").value;
var userPassword=document.getElementById("password-field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
/* window.location='Select Stream.html'; */
window.alert("Error : " + errorMessage);
// ...
});
}
The Login function will be triggered when the signin-button is clicked.
<input onclick="login()" type="submit" name="signin-button" value="Sign In"/>
First, change the name of Select Stream.html to have no spaces or capital letters. This is common practice, and I recommend changing the name of the file to select_stream.html.
Before opening select_stream.html or index.html, check whether the user is already on that page to prevent the page from refreshing, like this:
if (user) {
// User is signed in.
if(window.location.href.indexOf("select_stream.html") == -1){
window.location.replace("select_stream.html");
}
} else {
// No user is signed in.
if(window.location.href.indexOf("index.html") == -1){
window.location.replace("index.html");
}
}
The window.location.href variable refers to the URL of the current page, and the .indexOf function allows you to check if a value is contained inside the URL. The .indexOf function returns -1 if the specified value could not be found within the string, so this code simply only redirects if the user is not already on the redirect page.
I am trying to submit a form and upon submitting the form the page should be redirected to a different URL. This is working fine, BUT the toast message appears right after the user hits SAVE button and then the page redirects to a different URL and the toast message vanishes.
However I want to redirect to display toast message after getting into the redirect URL and stay there for about 1 second. Here is my javascript code.
function submitForm(event) {
if ($('#expenseTypeAddForm').valid()) {
preloaderOption.On();
var url = $('#expenseTypeAddForm').attr('action');
ohrmAjaxHandler.url = url;
ohrmAjaxHandler.type = 'POST';
ohrmAjaxHandler.dataType = 'JSON';
ohrmAjaxHandler.data = $('#expenseTypeAddForm').serialize();
ohrmAjaxHandler.success = saveExpenseTypeSuccess;
ohrmAjaxHandler.call();
}
else {
console.log("Form is not valid");
}
};
function saveExpenseTypeSuccess(data) {
if (data['redirectUrl']) {
window.location = (data['redirectUrl']);
}
preloaderOption.Off();
toast.show(data['state'], data['responseMsg']);
}
You can use session of javascript
sessionStorage.setItem("showmsg", "1");
and check if session exists then display message on other page and then reset the session
if(sessionStorage.getItem("showmsg")=='1'){
alert('success');
sessionStorage.removeItem("showmsg");
}
I have login with google on my site which is working correctly except for one thing. If I'm logged into my gmail account in the browser, the login script will automatically log me into my website too. Despite executing log out function successfully, the rendered button still says "Signed In" and then logs me in. Here's how login is setup
<script src="js/script.js"></script>
<script src="https://apis.google.com/js/platform.js?onload=googleLoad" async defer></script>
In my script.js file
function googleLoad() {
gapi.load('auth2', function() {
gapi.auth2.init();
});
};
function googleSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("Email: " + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
// console.log("ID Token: " + id_token);
var fullName = profile.getName(),
imageUrl = profile.getImageUrl(),
email = profile.getEmail(),
provider = 'Google';
};
function loggedOut(href){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
document.location = href;
});
};
$('#log-out').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
loggedOut(href);
});
When you load the page, the googleSignIn functions get's executed and I log in. Apparently this is the name of the default function that is executed on load. If I change the name of the function, it wouldn't run. That would solve the problem but how do I (when do I) execute the function manually?
Then there's the log out button, which when clicked does console the message and logs me out successfully. But on next page load I would just get logged in again because of googleSignIn. What am I doing wrong?
Alas there was nothing wrong with the code. I discovered that the logout function doesnot work on localhost. Tested it on the live server and everything was fine.
Thanks to #class who mentioned it on another related question
I have used the Asp.Net Identity framework in my app.There is a need, when the session expires give a prompt message, and then jump to the login page instead of directly jump to the login page.Prompt information using custom styles.
Because my app's left menus load the view with ajax,so I overried the AuthorizeAttribute.HandleUnauthorizedRequest methord to return a json.Now when users click left menus, it can work properly.But if users refresh the page by click F5,the page will still jump directly to the login page.
I have already overrided AuthorizeAttribute.HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var httpContext = filterContext.HttpContext;
string sintab = httpContext.Request["inTab"];
if (!string.IsNullOrEmpty(sintab) && bool.Parse(sintab))
{
var result = new JsonResult();
result.Data = new
{
Authorize = false,
Url = LOGIN_URL
};
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result =result;
return;
}
if (filterContext.Controller.GetType() != typeof(Controllers.HomeController) &&
!filterContext.ActionDescriptor.ActionName.Equals("Index", StringComparison.OrdinalIgnoreCase))
{
string returnUrl = "/" + filterContext.Controller.GetType().Name.Replace("Controller","") + "/Index" ;
returnUrl = httpContext.Server.UrlEncode(returnUrl);
httpContext.Response.Redirect("~/Account/Login?ReturnUrl="+returnUrl);
return;
}
base.HandleUnauthorizedRequest(filterContext);
}
The code of left menus' loadView js
$.get(url, null, function (html) {
html = html.replace(/#%/g, "\"").replace(/%#/g, "\"");
var json;
try {
json = eval("(" + html + ")");
} catch (e) {
}
if (json && !json.Authorize) {
// give an message
layer.alert("Session timeout, please re login.", function (index) {
window.location.href = json.Url + "?returnurl=" + encodeURI(hash);
});
}
else {
$("#content").empty().html(html);
_initModalButton();
$("#content").show();
}
}, 'html');
The page looks like this image
I want to know if there are some better ways to do this because there are a lot of other button need to check authorize status and show message before jump to the login page,and how to give the message when users refresh the page?
Thanks very much!
I think you're looking for are Global Ajax Events.
Please, check this, I think this make your job easier.
I want to link to a page and when the user clicks on the link his username and password are already there for him. However where i am linking too i don't control that pages code.
Is it possible to have my javascript execute there after the user clicks the link?
$("#link").click(function() {
alert( "Handler for .click() called." );
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("j_username");
var passwordTextBox = document.getElementById("j_password");
usernameTextBox.value = username;
passwordTextBox.value = password;
});
See my JSfiddle
You can't actually execute it from another page, you can however use the following.
The best way to do this is with a cookie, storing the username, and pointing to an encrypted file with an encrypted password. But you can store the encrypted password in a cookie too, as long as it's encrypted before putting it in the cookie.
I originally developed this for a function that will keep a user logged in to a page that redirected to a login whenever it is accessed, it will click the button and bring them to the page after the login page.
working example: Will need to be edited to fit exact elements on any page, and run on the page, probally through a property or permission gained through a download or web app etc.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function stayLoggedIn() {
setCookie("logged_in","true",30);
setCookie("username", username,30);
setCookie("password",encryptedPassword,30);
return null;
}
window.onload {
var loggedIn = getCookie("logged_in");
if(loggedIn == true) {
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("username");
var passwordTextBox = document.getElementById("password");
//decrypt password here.
usernameTextBox.value = username;
passwordTextBox.value = password;
}
else {}
}
Explained:
first, we set a function to set a cookie and get one, I took these from here
then, I set the function stayLoggedIn() this sets the cookie with the value of "logged_in" to true, so when the user comes to the page, and window.onload runs it's block, the if statement is triggered, and the username and password fields are filled in.
Then, click(element) is called on the logginButton, this can click on php, or html buttons or submit forms etc. This simulates the button being clicked, and the user logging in.
Also: You need to call the function stayLoggedIn() after the link is clicked (like through a google or firefox extension)