Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(license-service): Barcode session #17541

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import {
TOKEN_EXPIRED_ERROR,
} from '@island.is/services/license'
import { UserAgent } from '@island.is/nest/core'
import { ProblemError } from '@island.is/nest/problem'
import { ProblemType } from '@island.is/shared/problem'

const LOG_CATEGORY = 'license-service'

Expand Down Expand Up @@ -286,7 +288,7 @@ export class LicenseService {
const msg = `Invalid license type. "${type}"`
this.logger.warn(msg, { category: LOG_CATEGORY })

throw new InternalServerErrorException(msg)
throw new InternalServerErrorException(msg)
}

return client
Expand Down Expand Up @@ -469,6 +471,10 @@ export class LicenseService {
)
}

getBarcodeSessionKey(licenseType: LicenseType, sub: string) {
return `${licenseType}-${sub}`
}
magnearun marked this conversation as resolved.
Show resolved Hide resolved

async createBarcode(
user: User,
genericUserLicense: GenericUserLicense,
Expand All @@ -478,6 +484,20 @@ export class LicenseService {
const licenseType = this.mapLicenseType(genericUserLicenseType)
const client = await this.getClient<typeof licenseType>(licenseType)

const barcodeSessionKey = this.getBarcodeSessionKey(licenseType, user.sub)
const activeBarcodeSession = await this.barcodeService.getSessionCache(barcodeSessionKey)

magnearun marked this conversation as resolved.
Show resolved Hide resolved
if (activeBarcodeSession && activeBarcodeSession !== user.sid) {
// If the user has an active session for the license type, we should not create a new barcode
this.logger.info(
`User has an active session for license: ${licenseType}`,
)

throw new ProblemError({
type: ProblemType.BAD_SUBJECT,
title: `User has an active session for license type: ${licenseType}`,
})
}
magnearun marked this conversation as resolved.
Show resolved Hide resolved
if (
genericUserLicense.license.pkpassStatus !==
GenericUserLicensePkPassStatus.Available
Expand Down Expand Up @@ -518,6 +538,7 @@ export class LicenseService {
licenseType,
extraData,
}),
user.sub ? this.barcodeService.setSessionCache(barcodeSessionKey, user.sid) : undefined,
])

return tokenPayload
Expand Down
3 changes: 2 additions & 1 deletion libs/auth-nest-tools/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
} from '@island.is/shared/types'

export interface Auth {
sub?: string
sub: string
sid: string
nationalId?: string
scope: string[]
authorization: string
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/current-actor.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const getCurrentActor = (context: ExecutionContext): User => {
: {
...user.actor,
sub: user.sub,
sid: user.sid,
client: user.client,
authorization: user.authorization,
ip: user.ip,
Expand Down
3 changes: 2 additions & 1 deletion libs/auth-nest-tools/src/lib/jwt.payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ export interface JwtAct {
}

export interface JwtPayload {
sub?: string
sub: string
sid: string
magnearun marked this conversation as resolved.
Show resolved Hide resolved
nationalId?: string
scope: string | string[]
client_id: string
Expand Down
2 changes: 2 additions & 0 deletions libs/auth-nest-tools/src/lib/jwt.strategy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ describe('JwtStrategy#validate', () => {

fakePayload = {
nationalId: '1234567890',
sub: 'sub',
sid: 'sid',
scope: ['test-scope-1'],
client_id: 'test-client',
delegationType: [AuthDelegationType.Custom],
Expand Down
1 change: 1 addition & 0 deletions libs/auth-nest-tools/src/lib/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {

return {
sub: payload.sub,
sid: payload.sid,
nationalId: payload.nationalId,
scope: this.parseScopes(payload.scope),
client: payload.client_id,
Expand Down
2 changes: 2 additions & 0 deletions libs/auth-nest-tools/src/lib/mock-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export class MockAuthGuard implements CanActivate {
this.auth = {
nationalId: '0101302989',
authorization: '',
sid: '',
sub: '',
client: 'mock',
scope: [],
...auth,
Expand Down
1 change: 1 addition & 0 deletions libs/services/license/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export {
LicenseTokenData,
TOKEN_EXPIRED_ERROR,
BARCODE_EXPIRE_TIME_IN_SEC,
BARCODE_SESSION_EXPIRE_TIME_IN_SEC,
} from './lib/barcode.service'
export { LicenseConfig } from './lib/license.config'
export { LICENSE_SERVICE_CACHE_MANAGER_PROVIDER } from './lib/licenseCache.provider'
18 changes: 16 additions & 2 deletions libs/services/license/src/lib/barcode.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import {
} from '@island.is/clients/license-client'
import { ConfigType } from '@nestjs/config'
import { Inject, Injectable } from '@nestjs/common'
import { Cache as CacheManager } from 'cache-manager'
import { Cache as CacheManager, Milliseconds } from 'cache-manager'
import { sign, VerifyOptions, verify } from 'jsonwebtoken'
import { LICENSE_SERVICE_CACHE_MANAGER_PROVIDER } from './licenseCache.provider'
import { LicenseConfig } from './license.config'

export const BARCODE_EXPIRE_TIME_IN_SEC = 60
export const BARCODE_SESSION_EXPIRE_TIME_IN_SEC = 1800 // 30 minutes
magnearun marked this conversation as resolved.
Show resolved Hide resolved
export const TOKEN_EXPIRED_ERROR = 'TokenExpiredError'
export const BARCODE_ACTIVE_SESSION_KEY = 'activeSession'

/**
* License token data used to generate a license token
* The reason for the one letter fields is to keep the token as small as possible, since it will be used to generate barcodes
Expand Down Expand Up @@ -91,11 +94,22 @@ export class BarcodeService {

async setCache<Type extends LicenseType>(
key: string,
value: BarcodeData<Type>,
value: BarcodeData<Type> | string,
) {
return this.cacheManager.set(key, value, BARCODE_EXPIRE_TIME_IN_SEC * 1000)
magnearun marked this conversation as resolved.
Show resolved Hide resolved
}

async setSessionCache(
key: string,
value: string,
) {
return this.cacheManager.set(`${BARCODE_ACTIVE_SESSION_KEY}:${key}`, value, BARCODE_SESSION_EXPIRE_TIME_IN_SEC * 1000)
}

async getSessionCache(key: string): Promise<string | undefined> {
return this.cacheManager.get(`${BARCODE_ACTIVE_SESSION_KEY}:${key}`)
}

magnearun marked this conversation as resolved.
Show resolved Hide resolved
async getCache<Type extends LicenseType>(
key: string,
): Promise<BarcodeData<Type> | undefined> {
Expand Down
Loading