Skip to main content

Managing roles and sessions

After you create a role and assign it to as user, you can add the role information to their session. You can then use this information to read and verify the role and permissions in your API and website routes

Adding roles to a session#

We can set the user's role in the access token by overriding the createNewSession function in the init function:

import SuperTokens from "supertokens-node";import Session from "supertokens-node/recipe/session";import UserRoles from "supertokens-node/recipe/userroles";
SuperTokens.init({    supertokens: {        connectionURI: "...",    },    appInfo: {        apiDomain: "...",        appName: "...",        websiteDomain: "..."    },    recipeList: [        Session.init({            override: {                functions: (originalImplementation) => {                    return {                        ...originalImplementation,                        createNewSession: async function (input) {                            let userId = input.userId;
                            let roles = await UserRoles.getRolesForUser(userId);
                            input.accessTokenPayload = {                                ...input.accessTokenPayload,                                roles                            };
                            return originalImplementation.createNewSession(input);                        },                    };                },            },        })    ]});

You can also set the permissions to their session directly by fetching the list of permissions assigned to a role (refer to the Managing Roles and Permissions Page)

Updating roles in a session#

Post session verification, you can use the updateAccessTokenPayload function to update the user's role:

import { verifySession } from "supertokens-node/recipe/session/framework/express";import express from "express";import { SessionRequest } from "supertokens-node/framework/express";import UserRoles from "supertokens-node/recipe/userroles";
let app = express();"/set-role", verifySession(), async (req: SessionRequest, res) => {
    let userId = req.session!.getUserId();
    // Add the "admin" role to the user    const response = await UserRoles.addRoleToUser(userId, "admin");
    if (response.status === "UNKNOWN_ROLE_ERROR") {        // No such role exists        return;    }
    // Get the updated list of roles that the user is assigned    let roles = (await UserRoles.getRolesForUser(userId)).roles;
    let currAccessTokenPayload = req.session!.getAccessTokenPayload();
    await req.session!.updateAccessTokenPayload(        { ...currAccessTokenPayload, roles }    );