Skip to main content

Authentication

Overview​

The auth configuration is used to associate existing (external) users to the declo session. This enables baskets to be computed based on user data and is often used to make individual pricing or other individual options.

Setting up user association​

declo.config.ts
.auth({
getUser: (token: string) => {
if(!verifyToken(token, { secret: process.env.AUTH_SECRET })) return undefined;

const user = getUser(token);

return {
name: user.firstname,
country: user.country,
pricelist: user.pricelist
}
}
})

Computing with associated user​

When user is associated to the session, the returned user object is available in all compute functions being: data.defaults, all events, compute, validate.

The only configuration property that does not have access to the associated user, is the objects.

In compute​

Example using a custom vat factor belonging to the user

declo.config.ts
.compute((basket, { user }) => {
const totalPrice = basket.objects.reduce((acc, obj) => acc + obj.price, 0);
const totalVat = totalPrice * user.country.vat;

return {
totalVat,
totalPrice,
}
})

In validate​

Only allowing authenticated users to shop

declo.config.ts
.validate((basket, { user }) => {
return !!user
})

In data​

Using user data as data defaults

declo.config.ts
.data({
schema: z.object({
name: z.string()
}),
defaults: ({ user }) => ({
name: user.name || ""
})
})

Setting the user​

After auth.getUser has been implemented, the setToken from clients or directly on the WS api can be used to associate a session with a user.