Angularjs + Codeigniter user authentication - php

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.

Related

can not make call to Controller function via ajax call

I know similar question has been answered in this forum. I have tried many of the solutions provided in stackoverflow for the problem, yet could not solve it. So I am expecting some suggestions from your expertise.
I am trying to make a call to AjaxController function on form submit via ajax call using Cakephp 3. The issue here is i am getting 403 error. I have not yet found out the fix for this. I can see that form is passing the value but Ajax call can not reach the controller function . I get following error
POST http://localhost/shoppingCart/ajax/ajaxTest 403 (Forbidden)
AjaxController:
public function ajaxTest(){
$result = "hello";
return $result;
}
script:(view.ctp of AjaxController)
$(document).ready(function(){
$('button').click(function(event){
var form_data = $(this).serialize();
var hidden_value = $('[name="id"]').val();
// alert("your form data "+hidden_value);//works fine here
event.preventDefault();
$.ajax({
url:'../ajaxTest',
type:'POST',
data : hidden_value,
success:function(result){
alert('success');
$("#result").text(result);
},
error:function(error){
alert('error ='+(error.Message));
}
});
});
});
// });
</script>
According to Cakephp:
If authenticator returns null, AuthComponent redirects user to the
login action. If it’s an AJAX request and config ajaxLogin is
specified that element is rendered else a 403 HTTP status code is
returned.
I think you didn't specify any authorization scheme. That why according to cakephp you are getting 403 error.
If you don’t use an authorization scheme, make sure to check
authorization yourself in your controller’s beforeFilter or with
another component.
You can make actions public (in beforeFilter or initialize) using:
// Allow all actions
$this->Auth->allow();
// Allow only the index action.
$this->Auth->allow('ajaxTest');
// Allow only the view and index actions.
$this->Auth->allow(['ajaxTest', 'index']);
CakePhp > Authentication > Handling Unauthenticated Requests
CakePhp > Authentication > Using No Authorization

How can i make full post-back request from angularJS to phalcon php

I have an angularJS + PHP application. What i would like to achieve is a "Full Post" request to Phalcon PHP controller.
Angular:
$http.post('/controller/sampleAction/', {params}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
});
Phalcon PHP:
public function sampleAction()
{
ControllerBase::indexAction();
if ($this->request->isPost() == true) {
// Access POST data
$this->view->paramA = $this->request->getPost("paramA");
$this->view->paramB= $this->request->getPost("paramB");
}
}
I am getting to phalcon controller, setting my view params but the view is not rendered because its an AJAX request. How can i still use POST function and redirect/render the sampleAction view?
Here are my findings and solution for my problem:
Apparently Phalcon does return the view.
The reason that the view was not rendered as a full post-back response is that Angular is a Single-Page JS framework, so if i want to use it i should build my app accordingly.
So, instead of requesting a full page from Phalcon i changed my architecture, so i will only get relevant Json data from Phalcon while rendering the view purely in angularJS using a directive.
but the view is not rendered because its an AJAX request
False. Unsless you have disabled view by yourself in case of ajax request. Check out your code, share us whats happening in ControllerBase::indexAction() and in initialize() if defined and something related to requests/view.

How to pass facebook login response from javascript to php page?

I am trying to add loing with facebook feature to my website, I used javascript to connect to facebook API, As you know facebook sends object named "response", I want to pass this object to my index.php page to read its content their.
could you please tell me how to pass and read this opject
If you need to work with facebook from your server, you can't use just js auth.
You need to implement "server login", described at Login for Server-side Apps
You need not implement all that complicated things, just find any library from internet, FB have its own library for php as I know, and use it to make server login. You can find many examples how to do it.
You can done with it by using jQuery.ajax() or jQuery.post() function. but it is not secured. Because js is open for all browser. Bad guys can send unexpected data and take chances to harm your app / web. Anyway it is your choice.
You can add a function here i have used replace_login() in FB.getLoginStatus() as following:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
replace_login();
} else if (response.status === 'not_authorized') {
// not_authorized
} else {
// not_logged_in
}
});
Now write replace_login() in same file and after FB.getLoginStatus() as below:
function replace_login(){
FB.api('/me', function(response) {
$.post("http://yourdomain.com/ajax_post_login",{ username: response.username, name: response.name, fb_res: response }, function(data) {
alert(data);
})
});
}
Check facebook server-side-login, it will help you more.

Cannot detect if User is Logged in when using Paginator (backbone.js)

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.

ExtJS 4 logout from ExtJS after session is over

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

Categories