CakePHP 3 login with AngularJs — Part 2

Frontend with AngularJS

Jan Ranostaj
Sep 18, 2015 · 2 min read

Angular application

In Part 1 we have prepared our backed API to handle our application requests. Now it’s time to get into frontend stuff.

Modules

Let’s start by definig our App modules in main.js:

For routes I’ll use ui-router. Since this is a very simple application just for login demonstration, rouets are simple:

so we have only 2 routes /login and /app/home — accessible only when user log into our application otherwise redirect user to /login route

To check whether user can access restricted area or not we need to make sure that user is still logged in whenever route state is changed as in our application run time:

Next step is to create AuthInterceptor Factory to modify application requests and responses in one place

Factory has 3 methods request, responseError, response. Each one of these methods represent state where we can modify response/request behavior.

Request — change header configuration so our request sends user Auth token to the backend application. First we check if token exists, and if does it is assigned to Authorization property like so: config.headers.Authorization = ‘Bearer ‘ + token;

config.headers.Authorization = ‘Bearer ‘ + token;

ResponsEerror — handle response errors from backend application. This method checks for response codes and sets appropriate url state.

To avoid circular dependency we inject $state in $timeout function:

 $timeout(function () { 
$state = $injector.get('$state');
});

When backend application returns 403 resp. 401 the user is forced to /login state

Response — just return normal response object

Now we need to push AuthInterceptor into $HttpProvider configuration:

Complete AuthInterceptor

Login Factory

So far we prepared our simple angular application setup. We defined modules, routes configuration, run configuration and solved application request/response behavior via AuthInterceptor

The next step is to create basic user authentication factory

Login Controller

Now we just create login controller to connect login form with loginFactory.

Login template

Conclusion

So we build frontend application to communicate to our backend described in Part 1. It’s a basic application which only demonstrate how I used CakePHP and Angular to create login application

Jan Ranostaj

Written by

Senior AngularJS engineer at Accenture

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade