I use CodeIgniter for my backend and ExtJS 4.1 for the frontend. In a controller in CI I check if an users session is over and if so I perform
redirect('login');
However what actually happen is - I stop to get response from the server but my ExtJS is still working and I don't get the loginpage. How can I redirect from ExtJS when I see on the server side that session is over?
Thanks
Leron
var runner = new Ext.util.TaskRunner();
// poll some page every 10 seconds
var task = runner.start({
run: function() {
Ext.Ajax.request({
url: 'is_logged_out.php',
success: function(response){
var json = Ext.JSON.decode(response.responseText);
// is we are logged out then redirect somewhere
if (json.isLoggedOut) {
task.destroy();
location.href = json.redirectToPage;
}
}
})
},
interval: 10000
})
You also can add special logic to handle 403 errors (presumably if your ExtJs session has expire on the backend, but client still have page opened - next request should get back Not Authorized message).
Check out singleton class Ext.Ajax for how to subscribe to global Ajax events.
When an user's session is over, typically is done by the user himself by performing a certain behaviour: for example, the user push the logout button. Well, at that time, the client (ExtJS) should be forward an AJAX request to the server as follows:
Ext.Ajax.request ({
url: serverUrl + 'logout' ,
success: function (response) {
location.href = serverUrl + 'login';
} ,
failure: function (response) {
// Something here to handle the failure
}
});
When an user logout, that request is reached by the server: your CI app will over the session and response to the client with '200 OK HTTP/1.1' and the client provide to redirect the user to the login page.
Ciao.
Wilk
Related
I'd like to build a site that has only HTML/jQuery in the frontend and PHP/MySQL in the backend.
How can I manage the user sessions (login/logout) and work with session variables using only HTML/jQuery?
Thanks
Using jQuery you could perform AJAX calls to a page in php with method to login, logout and query for session variables.
Also. If your app is not working with server at regultar intervals make request to server to keep session alive.
Login example
JQuery
$.ajax({
dataType: "json",
url: "http://yoursite.com/ajax.php?method=login",
data: yourloginData,
success: yourSuccesAction
});
PHP
<?php
if(isset($_GET['method']){
if ($_GET['method'] == 'login'){
// do login here and print response to server
// for example in json with json_encode
}
}
More information see:
Demo: jQuery Ajax Call to PHP Script with JSON Return
jQuery ajax request with json response, how to?
Situation :
My web application is password protected.For each http request we make to server, it is being checked against session existence. If session has been expired then the user is forwarded to login page.
This goes fine for http requests. But if it is an AJAX request, then just like http request, if session has been expired, it is also forwarded to login page.
Problem :
if we are directly showing AJAX response in browser, then in place of our expected response will show the login page content in your browser.And if you would be fetching data of any expected format, then it would throw JavaScript error.
My Code :
<script>
function details() {
var xyz = document.getElementById("name").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name=' + xyz;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "user.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("content").innerHTML=html;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status === 401) {
location.href = 'index.php';
}
}
});
return false;
}
</script>
on Session time out when i call Ajax request through my code. It loads the login.php content into the current page instead of forwarded the user to login Page.
Guide me where i am doing something wrong.
Thanks.
If your are working with multiple ajax request, then you can use jquery ajaxComplete function.
This function run every time after ajax call but before the success or failure function attached to that ajax event.
eg for this code is :
jQuery("body").ajaxComplete(
function(event, request, options) {
if (request.responseText == "login_required") {
window.location.href = "login.php";
}
}
);
And on your server side, you just have to check if the request is an ajax request and if user is not logged in, just print "login_required" and stop the execution of code(exit the code).
User will redirect to login.php page
I have an app that has a full angularjs frontend with a codeigniter backend (with thishttps://github.com/philsturgeon/codeigniter-restserver)
I am using the codeigniter backend just to make api requests essentially.
The problem I am having now is managing a navigation view based on whether or not a user is logged in.
I have the navigation in its own navCtrl with a userService and loginCtrl.
I am storing loggedIn true or false in a cookie with a $watch on it in the navCtrl so it will update the navigations appropriately.
Any insight on why this may not be working? Any code i need to provide to clarify? Is there a "better" way to do this?
EDIT: The $watch is not actually catching when I update the value using the userService.
Thank you!
We have a very similar setup as you. What we do is have Codeigniter send a HTTP Status code of 419 (not logged in) or something like that. And then you'll use Angular Interceptors to 'listen' for the response from the backend.
app.factory('loggedIn',function($q,$location){
return {
/*
* Intercept all response errors & handle them
*/
responseError: function(response) {
if (response.status == 419) {
console.error("You are not logged in");
$location.path('/login');
}
return $q.reject(response);
}
};
});
Then push it to the $httpProvider:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('loggedIn');
}]);
This should handle your front-end navigation pretty easily.
There are also other things that you can do for the $http requests before sending & before response is returned. Makes for a slick setup.
Checking sessions in Angularjs and CI using AJAX:
Javascript function called in angular js controllers:
function check_session()
{
$.get(base_url+"admin/check_session/check", function(data, status){
if(data=="1") /* error 1 => un-athorized user */
{
window.location.href=base_url+"login";
}
});
}
Expaining AJAX request:
check_session is CI controller and check is function in that.
I am using the Backbone.js Paginator plugin. It does infinite scroll pagination well by defining its own Collection for the models involved in the pagination. If the user is logged in, the PHP backend will return the Backbone object with an additional attribute is_liked to cause that item to have a different CSS styling.
Problem: When the Paginator plugin (with its own Collection Backbone.Paginator.requestPager) does a GET fetch request on the backend, the backend is not able to determine if the user is logged in! However, when I use the usual Backbone.Collection, the backend is able to determine whether the user is logged in! It works with a $.post() too. This makes me think the problem lies in the plugin's Backbone.Paginator.requestPager
I am checking the results by using the Network section of Chrome's developer tools. If the authentication check works, api/test can be seen to return some data about the user. If login status cannot be determined, it returns null
UPDATE: The GET request sent by Backbone.Paginator.requestPager collection does not include the Cookie info in the headers that is found in the GET request sent by Backbone.Collection. Could this be the problem? How can I force Backbone.Paginator.requestPager to not strip out the cookie data from the headers?
What is happening here? And how can I solve this (without rewriting my own pagination code)?
Auth Test using PHP Backend (Laravel Framework)
Route::any('api/test', function() {
// This will return some data of the user if logged in
return json_encode(Auth::user());
});
Typical Backbone Collection [Works]
SimilarUserCollection = Backbone.Collection.extend({
model: User,
url: 'api/test'
});
Paginator's Collection [Doesnt Work]
PhotoCollection = Backbone.Paginator.requestPager.extend({
model: Photo,
paginator_core: {
type: 'GET',
dataType: 'json',
url: 'api/test'
},
paginator_ui: {
firstPage: 1,
currentPage: 1,
perPage: 7,
totalPages: 10
},
server_api: {
'page': function() { return this.currentPage; }
},
parse: function (response) {
return response;
}
});
This is a crossdomain issue:
One Request is to this URL:
http://www.mysite.com/api/test?page=1
And the other to this:
http://mysite.com/api/test
For the browsers www.mysite.com is totally different so if the Cookie is generated on www.mysite.com requests to mysite.com will not contain it. Be sure that both requests goes to the same domain and you will not have the Cookie issue.
I'm sure you're all familiar with the voting systems that use AJAX (Um... look right over there <----)
I have something similar and when you vote up or down it uses AJAX to request the new value from votes.php. The problem is that I am using a session to get the userid so a person can only vote once. What happens if they sit on the page for an hour and then vote so the session is no longer there? What would be a good way of handling this situation? Should I redirect their page to the login screen? If so, how can I do that from the votes.php page that is being referenced by the AJAX request? Am I overlooking a good way of handling this situation? Any advice would be helpful.
Consider returning an http status of 401, and a JSON object detailing the reason. If you're using jQuery, that'll drop you to the error() callback, which you can then parse your object.
$.ajax({
data: {},
dataType: 'html',
success: function(data) {
// do whatever here
},
type: 'POST',
url: 'myserver.com',
error: function(XMLHttpRequest, textStatus, errorThrown) {
// XMLHttpRequest.responseText has your json string
// XMLHttpRequest.status has the 401 status code
if (XMLHttpRequest.status === 401) {
location.href = 'login.php';
}
}
});
I'm not familiar with PHP anymore, but this should work for just about any environment. You may have to suppress any automatic login form redirection though. In asp.net mvc the framework will see the 401 and push the default login form back, with a status of 200.
You should only store a link to the users identity in the session. Use sessions to identify a user as x and then get user x's information from the database.
If your problem is with users sessions timing out then you should reconsider how you're using your sessions. Perhaps make them last until the browser closes? If you really want to make them a duration, then perhaps ping the server in intervals to keep the session alive.
Decide in your php script whether or not the user should be able to vote. If the session isn't set, or if they have already voted, return a message that you can identify with on the client side. If they already voted perhaps return "voted":"true" in a JSON object. Use JS to parse this object and understand what it means, taking the appropriate action. If the session isn't set, perhaps return "session_set":"false", and then make javascript redirect with a window.location = "login.php" etc.
Only increment the counter for the user on a successful return of a counted vote.
This is an old thread, but I wanted to share my solution that is working really well.
In my framework the system redirects the user to the login form any time they try to access a page and the session has timed out or is not valid.
I added to the top of the login form the following html comment:
<!--LOGINFORM-->
I created a wrapper for jQuery's $.ajax function which checks for this string on every request, and if it is there it shows a dialog popup saying that their session has timed out.
You can use this by just calling:
ajax.get('http://someurl.com', function(data){
//Do stuff
});
Hope it helps someone.
var ajax = {
check_login : function(resp){
if (resp.substring(0, 16) === "<!--LOGINFORM-->"){
// Show a popup or redirect them to login page!
return true;
}
return false;
},
get : function(url, success){
if (typeof data =='undefined'){
data = null;
}
$.ajax({
url: url,
type : 'GET',
success : function(resp){
if (!ajax.check_login(resp)) {
success(resp);
}
},
});
}
};
You structure the Javascript code that makes the Ajax request to accept a special result (say, -1 where a >=0 number would normally be, such as, a count of votes) to mean "sorry bub, you're timed out" and redirect to the re-login page (which can take as an optional parameter a message explaining to the user they timed out, &c).
You could create a javascript function that could ping the server every 10 minutes via something like
setTimeout("Ping()", 60000);
If you want to navigate the user to the login page if they connect with a faulty session then I would first verify the session and if it fails send a
header("Location: ...");
http://ca2.php.net/manual/en/function.header.php
From a user perspective, the best solution is to pop up a message and login form, saying something like "You are not logged in or your session timed out". Digg does this very well.
As for the actual AJAX implementation, swilliams' 401 suggestion is solid. Alternatively, you can simply return a specific string on failure.