FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.89k stars 139 forks source link

Know if the user is authenticated on the client side when using cookies. #843

Closed LoicPoullain closed 3 years ago

LoicPoullain commented 3 years ago

Issue

When using session authentication with cookies, the client app cannot read the auth cookie to know if a user is authenticated. This is due to the cookie directive httpOnly: true to prevent from some XSS attacks.

This has however a drawback. In a case of a SPA, the client cannot know if the user is authenticated or still authenticated (the session might have expired). It has to make another request to the server to see if it gets a 401 error. This is not really handy.

Also, the client may want to access some properties of the user (like permissions to manage the display of the UI) without making a request eachtime to see if the local user data is up-to-date.

Solution

Add another cookie accessible from the frontend to know if the user is authenticated.

Example 1

@UserSessions({
  user: fetchUser(User),
  cookie: true,
  clientUser: true
})

Cookies

SESSIONID=xxxxxxxx
user=true

Example 2

@UserSessions({
  user: fetchUser(User),
  cookie: true,
  clientUser: ctx => ({ email: ctx.user.email, isAdmin, ctx.user.isAdmin })
})

Cookies

SESSIONID=xxxxxxxx
user={ email: 'foobar@foalts.org', isAdmin: true }
LoicPoullain commented 3 years ago

Feature added in v2.2