In this tutorial i try to explain a very important concept of application development: authorization. Authorization in application is simply the function of specifying access rights/privileges to resources of the application. The approches we can use to implement auth system are different from framework to another. Total.js framework supports a very simple authorization mechanism. It's a one delegate function system via AUTH(function($))
that i am going to break down for you.
The easierst way to describe the role of AUTH()
is to take it like the guard of the gates of your application. AUTH()
is there to check the requests that are coming to your application. All requests via HTTP or Websocket protocol are evaluated by AUTH
according to your predefined access rights policy. The picture below describes it better.
Before we dive deep into our usual hands-on practice, it is important to keep that AUTH
accepts two types of parameters. If typeof
parameter is an object AUTH({})
, then it will try to use the predifined auth implementation. Learn more about it here. If typeof
parameter is a function, then we are able to write our own authorization policy. Let's try that in four steps:
AUTH(function($))
guard;Start a total.js project
Now you can open your project in your favorite code editor and move to the next step.
Resource endpoint
Output:
If you open your browser you must see Hello world
in your screen.
Simple login
We are making some small configurations first.
Now we will update /controllers/default.js
file to add a simple login function.
This is usefull for creating a session.
Notice the +/-
characters
+
character in ROUTE('+GET /*', home)
means user must be authorized for access everything (/*
);-
character in ROUTE('-GET /*', login)
means that all unauthorized requests must open login form;The AUTH()
guard
Now we need to add the AUTH()
guard to start checking our requests.
Output:
http://localhost:8000/?login=admin&password=admin
. The output is awsome:The application has created a cookie and sent it back to the browser. You can check it in browser dev tools via use Option + ⌘ + J
(on macOS), or Shift + CTRL + J
(on Windows/Linux). You can check.
From now, your browser will attach this cookie in your next requests to server, except if the cookie has expired.
Total.js doesn't limit you. This tutorial focused on explaining the basic concepts of AUTH
. But everything depends on the requerements of your application. Read documentation here to learn more. Alternatively, you can use the predefined auth mechanism. Read about it here