LoopBack 4 Todo application with JWT authentication and authorization.
OTHER License
Learning in progress. So the application is still working in progress
LoopBack 4 Todo application with JWT authentication and authorization.
Built on top of todo-jwt LoopBack 4 application. Therefore, if you're not familiar with that application, it's better to go there first.
There are a few slight modification on the application/scenario from the todo-jwt application.
owner
property in the Todo model, so that we can set the corresponding rights to Todo items created by the users.We'd like to introduce 3 roles:
Let's follow the instruction on how to customize the User model: https://github.com/strongloop/loopback-next/tree/master/extensions/authentication-jwt#customizing-user
Modify the todo application so that the Todo model includes the owner of the todo.
In the User model, add an additional property owner
.
@property({
type: 'string',
})
owner?: string;
In src/controllers/todo.controller.ts
, when someone create a todo, the owner
property is set to the current user.
import {SecurityBindings, UserProfile} from '@loopback/security';
//...
constructor(
@repository(TodoRepository) protected todoRepository: TodoRepository,
@inject(SecurityBindings.USER) public currentUserProfile: UserProfile,
) {}
createTodo
function,todo.owner = this.currentUserProfile[securityId]; // ADD THIS LINE
return this.todoRepository.create(todo);
Let's test it out what's changed.
Start the application using npm start
. Go to http://localhost:3000/explorer.
Log in through POST /users/login
.
After logging in, copy the token and set it in the Authorize dialog (click the Authorize button at the top of the page).
After setting the JWT, let's create a todo item. e.g.
{
"title": "buy apples",
"desc": "buy 10 apples",
"isComplete": false
}
Go to data/db.json and you'll see there's an additional owner
property appear which is the user that's logged in while creating that todo item.