CakePHP 3 login with AngularJs — Part 2

Frontend with AngularJS

Angular application

In 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 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 . It’s a basic application which only demonstrate how I used CakePHP and Angular to create login application

Written by

Senior ReactJs/Angular engineer at Accenture

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store