Files
huly-platform/server/token/src/token.ts
T
2024-09-09 13:40:49 +05:00

34 lines
926 B
TypeScript

import { getWorkspaceId, WorkspaceId } from '@hcengineering/core'
import { getMetadata } from '@hcengineering/platform'
import { decode, encode } from 'jwt-simple'
import serverPlugin from './plugin'
/**
* @public
*/
export interface Token {
email: string
workspace: WorkspaceId
extra?: Record<string, any>
}
const getSecret = (): string => {
return getMetadata(serverPlugin.metadata.Secret) ?? 'secret'
}
/**
* @public
*/
export function generateToken (email: string, workspace: WorkspaceId, extra?: Record<string, string>): string {
return encode({ ...(extra ?? {}), email, workspace: workspace.name }, getSecret())
}
/**
* @public
*/
export function decodeToken (token: string, verify: boolean = true, secret?: string): Token {
const value = decode(token, secret ?? getSecret(), !verify)
const { email, workspace, ...extra } = value
return { email, workspace: getWorkspaceId(workspace), extra }
}