Authentication
In this lesson, we’ll implement a basic sign-in mechanism using cookie session.
Let’s add a shared/AuthController.ts
file and include the following code:
Code Explanation
- We import the necessary modules from
remult
and types forexpress
andcookie-session
. - We extend the
RemultContext
interface to include an optionalrequest
property of typeexpress.Request
. - Remult will automatically set the
request
with the current request. Since Remult works with any server framework, we need to type it to the correct server, which in this case is Express. This typing gives us access to the request object and its session, managed bycookie-session
. - This
request
can be accessed usingremult.context.request
.
Next, we’ll add a static list of users and a sign-in method. (In a real application, you would use a database, but for this tutorial, a static list will suffice.)
Code Explanation
- We define a static list of valid users.
- The
signIn
method is decorated with@BackendMethod({ allowed: true })
, making it accessible from the frontend. - The method checks if the provided
name
exists in thevalidUsers
list. If it does, it setsremult.user
to an object that conforms to theUserInfo
type from Remult and stores this user in the request session. - If the user is not found, it throws an error.
Next, we’ll add the sign-out method:
Code Explanation
- The
signOut
method clears the user session, making the user unauthenticated.
Next, we’ll adjust the backend/index.ts
file:
Code Explanation
- The
signOut
method clears the user session, making the user unauthenticated. - We import
session
fromcookie-session
andAuthController
. - We enable
trust proxy
for reverse proxy scenarios like StackBlitz. - We’ve set
signed: false
in the session configuration due to an issue in StackBlitz that causes problems with signed cookies. This is for development purposes only and in production, you should removesigned: false
and encrypt the cookie using a secret by setting thesecret
option (e.g.,secret: process.env['SESSION_SECRET'] || 'my secret'
). - We register
AuthController
in thecontrollers
array. - We add
getUser: (request) => request.session?.['user']
to extract the user from the session.
Frontend Authentication
In frontend/Auth.tsx
, we’ll call the AuthController
to sign in, sign out, etc.
Code Explanation
- The
signIn
function callsAuthController.signIn
and sets the current user if successful. - The
signOut
function callsAuthController.signOut
to clear the current user. - The
useEffect
hook uses theinitUser
method to fetch the current user when the component mounts.
Try It Out
Try signing in as Alex
or Jane
and verify that you can perform CRUD operations on tasks. Sign out and ensure that you can no longer access the tasks.
Files
Preparing Environment
- Installing dependencies
- Starting http server