Skip to content

Commit

Permalink
Renamed short-term session to session-token
Browse files Browse the repository at this point in the history
  • Loading branch information
corbadoman committed Oct 15, 2024
1 parent 461acb1 commit 070962f
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 29 deletions.
16 changes: 8 additions & 8 deletions examples/basic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ app.get('/', async (_, res) => {
// Protecting routes //
//////////////////////////////////////////////////////////////////////////////////////////////

// Retrieve the short-term session value from the Cookie (e.g. req.cookies.cbo_short_session)
const shortTermSessionValue = '<Your short-term session value>';
// Retrieve the session-token from cookie (e.g. req.cookies.cbo_session_token)
const sessionToken = '<Your session-token>';

if (!shortTermSessionValue) {
// If the short-term session value is empty (e.g. the cookie is not set or
if (!sessionToken) {
// If the session-token is empty (e.g. the cookie is not set or
// expired), the user is not authenticated. e.g. redirect to login page.

console.log('User not authenticated');
Expand All @@ -43,7 +43,7 @@ app.get('/', async (_, res) => {
let user;

try {
user = await sdk.sessions().validateToken(shortTermSessionValue);
user = await sdk.sessions().validateToken(sessionToken);

console.log(`User with ID ${user.userId} is authenticated!`);
} catch (err) {
Expand All @@ -61,10 +61,10 @@ app.get('/', async (_, res) => {
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Getting user data from short-term session (represented as JWT) //
// Getting user data from session-token //
//////////////////////////////////////////////////////////////////////////////////////////////

user = await sdk.sessions().validateToken(shortTermSessionValue);
user = await sdk.sessions().validateToken(sessionToken);

console.log('UserID', user.userId);
console.log('Full Name', user.fullName);
Expand All @@ -73,7 +73,7 @@ app.get('/', async (_, res) => {
// Getting user data from Corbado Backend API //
//////////////////////////////////////////////////////////////////////////////////////////////

user = await sdk.sessions().validateToken(shortTermSessionValue);
user = await sdk.sessions().validateToken(sessionToken);

const fullUser = await sdk.users().get(user.userId);

Expand Down
15 changes: 11 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ export interface ConfigInterface {
APISecret: string;
FrontendAPI: string;
BackendAPI: string;
ShortSessionCookieName: string;
SessionTokenCookieName: string;
CacheMaxAge: number;
}

export const DefaultClient = axios.create();
export const DefaultShortSessionCookieName = 'cbo_short_session';
export const DefaultSessionTokenCookieName = 'cbo_session_token';
export const DefaultCacheMaxAge = 10 * 60 * 1000; // 10 * 60 * 1000 = 60000 milliseconds, which is equivalent to 10 minutes.

class Config implements ConfigInterface {
Expand All @@ -24,7 +24,7 @@ class Config implements ConfigInterface {

BackendAPI: string;

ShortSessionCookieName: string = DefaultShortSessionCookieName;
SessionTokenCookieName: string = DefaultSessionTokenCookieName;

Client: AxiosInstance;

Expand All @@ -43,10 +43,17 @@ class Config implements ConfigInterface {
this.BackendAPI = backendAPI;
}

// @deprecated
public setShortSessionCookieName(shortSessionCookieName: string): void {
Assert.notEmptyString(shortSessionCookieName, 'shortSessionCookieName');

this.ShortSessionCookieName = shortSessionCookieName;
this.SessionTokenCookieName = shortSessionCookieName;

Check warning on line 50 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L50

Added line #L50 was not covered by tests
}

public setSessionTokenCookieName(sessionTokenName: string): void {
Assert.notEmptyString(sessionTokenName, 'sessionTokenName');

Check warning on line 54 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L53-L54

Added lines #L53 - L54 were not covered by tests

this.SessionTokenCookieName = sessionTokenName;

Check warning on line 56 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L56

Added line #L56 was not covered by tests
}

public setHttpClient(client: AxiosInstance): void {
Expand Down
2 changes: 1 addition & 1 deletion src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class SDK {
this.axiosClient = this.createClient(config);

this.session = new Session(
config.ShortSessionCookieName,
config.SessionTokenCookieName,
config.FrontendAPI,
`${config.FrontendAPI}/.well-known/jwks`,
config.CacheMaxAge,
Expand Down
20 changes: 10 additions & 10 deletions src/services/sessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Assert } from '../helpers/index.js';
import ValidationError, { ValidationErrorNames } from '../errors/validationError.js';

export interface SessionInterface {
validateToken(shortSession: string): Promise<{ userId: string; fullName: string }>;
validateToken(sessionToken: string): Promise<{ userId: string; fullName: string }>;
}

interface MyJWTPayload extends JWTPayload {
Expand All @@ -14,7 +14,7 @@ interface MyJWTPayload extends JWTPayload {
sub: string;
}

const MIN_SHORT_SESSION_LENGTH = 10;
const MIN_SESSION_TOKEN_LENGTH = 10;

class Session implements SessionInterface {
private issuer: string;
Expand All @@ -25,8 +25,8 @@ class Session implements SessionInterface {

private projectID: string;

constructor(shortSessionCookieName: string, issuer: string, jwksURI: string, cacheMaxAge: number, projectID: string) {
if (!shortSessionCookieName || !issuer || !jwksURI) {
constructor(sessionTokenCookieName: string, issuer: string, jwksURI: string, cacheMaxAge: number, projectID: string) {
if (!sessionTokenCookieName || !issuer || !jwksURI) {
throw new Error('Required parameter is empty');
}

Expand All @@ -41,19 +41,19 @@ class Session implements SessionInterface {
}

/**
* Validate the short session token and return the user ID and full name
* @param {any} shortSession:string
* Validate the session token and return the user ID and full name
* @param {any} sessionToken:string
* @returns {any} { userId: string; fullName: string }
*/
public async validateToken(shortSession: string): Promise<{ userId: string; fullName: string }> {
Assert.notEmptyString(shortSession, 'shortSession not given');
public async validateToken(sessionToken: string): Promise<{ userId: string; fullName: string }> {
Assert.notEmptyString(sessionToken, 'sessionToken not given');

if (shortSession.length < MIN_SHORT_SESSION_LENGTH) {
if (sessionToken.length < MIN_SESSION_TOKEN_LENGTH) {
throw new ValidationError(ValidationErrorNames.InvalidShortSession);
}

try {
const { payload } = await jwtVerify(shortSession, this.jwkSet);
const { payload } = await jwtVerify(sessionToken, this.jwkSet);

const { iss, name, sub } = payload as MyJWTPayload;

Expand Down
6 changes: 3 additions & 3 deletions tests/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DefaultCacheMaxAge, DefaultShortSessionCookieName } from '../src/config.js';
import {DefaultCacheMaxAge, DefaultSessionTokenCookieName} from '../src/config.js';
import { BaseError } from '../src/errors/index.js';
import { Config } from '../src/index.js';

Expand All @@ -25,7 +25,7 @@ describe('Configuration class', () => {
expect(config.APISecret).toBe(apiSecret);
expect(config.FrontendAPI).toBe(`https://${projectID}.frontendapi.cloud.corbado.io`);
expect(config.BackendAPI).toBe(backendAPI);
expect(config.ShortSessionCookieName).toBe(DefaultShortSessionCookieName);
expect(config.SessionTokenCookieName).toBe(DefaultSessionTokenCookieName);
expect(config.CacheMaxAge).toBe(DefaultCacheMaxAge);
};

Expand All @@ -38,7 +38,7 @@ describe('Configuration class', () => {
const config = new Config(projectID, apiSecret, frontendAPI, backendAPI);
expect(config.BackendAPI).toBe(backendAPI);
expect(config.FrontendAPI).toBe(frontendAPI);
expect(config.ShortSessionCookieName).toBe(DefaultShortSessionCookieName);
expect(config.SessionTokenCookieName).toBe(DefaultSessionTokenCookieName);
expect(config.CacheMaxAge).toBe(DefaultCacheMaxAge);
});

Expand Down
6 changes: 3 additions & 3 deletions tests/unit/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async function generateJWT(

function createSessionService(issuer: string): SessionService {
return new SessionService(
'cbo_short_session',
'cbo_session_token',
issuer,
`http://localhost:${PORT}/jwks`,
10,
Expand All @@ -87,10 +87,10 @@ describe('Session Service Unit Tests', () => {
expect(() => new SessionService('', 'https://pro-1.frontendapi.cloud.corbado.io', `http://localhost:${PORT}/jwks`, 10, 'pro-1')).toThrow(
'Required parameter is empty',
);
expect(() => new SessionService('cbo_short_session', '', `http://localhost:${PORT}/jwks`, 10, 'pro-1')).toThrow(
expect(() => new SessionService('cbo_session_token', '', `http://localhost:${PORT}/jwks`, 10, 'pro-1')).toThrow(
'Required parameter is empty',
);
expect(() => new SessionService('cbo_short_session', 'https://pro-1.frontendapi.cloud.corbado.io', '', 10, 'pro-1')).toThrow(
expect(() => new SessionService('cbo_session_token', 'https://pro-1.frontendapi.cloud.corbado.io', '', 10, 'pro-1')).toThrow(
'Required parameter is empty',
);
});
Expand Down

0 comments on commit 070962f

Please sign in to comment.