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(web): token never expiration #716

Merged
merged 4 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
2 changes: 1 addition & 1 deletion web/crux-ui/i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"/auth/settings/edit-profile": ["settings"],
"/auth/settings/change-password": ["settings"],
"/auth/settings/new-password": ["settings"],
"/auth/settings/tokens": ["settings"],
"/auth/settings/tokens": ["settings", "tokens"],
"/auth/verify": ["verify"],
"/projects": ["projects"],
"/projects/[projectId]": ["projects", "versions", "images", "deployments"],
Expand Down
6 changes: 3 additions & 3 deletions web/crux-ui/src/components/settings/create-token-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import { DyoHeading } from '@app/elements/dyo-heading'
import { DyoInput } from '@app/elements/dyo-input'
import { DyoLabel } from '@app/elements/dyo-label'
import { defaultApiErrorHandler } from '@app/errors'
import { GeneratedToken, GenerateToken } from '@app/models'
import { GeneratedToken, GenerateToken, TokenExpiration } from '@app/models'
import { API_TOKENS } from '@app/routes'
import { sendForm } from '@app/utils'
import { generateTokenSchema } from '@app/validations/token'
import { useFormik } from 'formik'
import useTranslation from 'next-translate/useTranslation'
import { MutableRefObject } from 'react'

const EXPIRATION_VALUES = [30, 60, 90]
const EXPIRATION_VALUES: TokenExpiration[] = [30, 60, 90, 'never']
robot9706 marked this conversation as resolved.
Show resolved Hide resolved

interface CreateTokenCardProps {
className?: string
Expand Down Expand Up @@ -81,7 +81,7 @@ const CreateTokenCard = (props: CreateTokenCardProps) => {
className="text-bright"
choices={EXPIRATION_VALUES}
selection={formik.values.expirationInDays}
converter={it => t('common:days', { days: it })}
converter={it => (it === 'never' ? t('common:never') : t('common:days', { days: it }))}
onSelectionChange={it => {
formik.setFieldValue('expirationInDays', it, false)
}}
Expand Down
4 changes: 3 additions & 1 deletion web/crux-ui/src/models/token.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export type TokenExpiration = number | 'never'

export class Token {
id: string

Expand All @@ -11,7 +13,7 @@ export class Token {
export class GenerateToken {
name: string

expirationInDays: number
expirationInDays: TokenExpiration
}

export class GeneratedToken extends Token {
Expand Down
2 changes: 1 addition & 1 deletion web/crux-ui/src/pages/auth/settings/tokens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const TokensPage = (props: TokensPageProps) => {
const itemTemplate = (item: GeneratedToken) => [
<a>{item.name}</a>,
<a>{utcDateToLocale(item.createdAt)}</a>,
<a>{utcDateToLocale(item.expiresAt)}</a>,
<a>{item.expiresAt ? utcDateToLocale(item.expiresAt) : t('common:never')}</a>,
<div className="flex flex-row justify-center">
<Image
className="cursor-pointer"
Expand Down
7 changes: 6 additions & 1 deletion web/crux-ui/src/validations/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,10 @@ import { nameRule } from './common'
// eslint-disable-next-line import/prefer-default-export
export const generateTokenSchema = yup.object().shape({
name: nameRule.required(),
expirationInDays: yup.number().required(),
expirationInDays: yup.mixed().test(
'is-token-expiration',
// eslint-disable-next-line no-template-curly-in-string
'${label} is not a valid token expiration',
value => value === 'never' || typeof value === 'number',
),
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Token" ALTER COLUMN "expiresAt" DROP NOT NULL;
12 changes: 6 additions & 6 deletions web/crux/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ model Team {
}

model Token {
id String @id @default(uuid()) @db.Uuid
userId String @db.Uuid
name String @db.VarChar(70)
createdAt DateTime @default(now()) @db.Timestamptz(6)
expiresAt DateTime @db.Timestamptz(6)
nonce String @db.Uuid
id String @id @default(uuid()) @db.Uuid
userId String @db.Uuid
name String @db.VarChar(70)
createdAt DateTime @default(now()) @db.Timestamptz(6)
expiresAt DateTime? @db.Timestamptz(6)
polaroi8d marked this conversation as resolved.
Show resolved Hide resolved
nonce String @db.Uuid

@@unique([userId, name, nonce])
}
Expand Down
2 changes: 1 addition & 1 deletion web/crux/src/app/token/pipes/token.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { GenerateTokenDto } from '../token.dto'
@Injectable()
export default class TokenValidationPipe implements PipeTransform {
async transform(req: GenerateTokenDto) {
if (req.expirationInDays <= 0) {
if (req.expirationInDays !== 'never' && req.expirationInDays <= 0) {
throw new CruxBadRequestException({
property: 'expirationInDays',
value: req.expirationInDays,
Expand Down
13 changes: 8 additions & 5 deletions web/crux/src/app/token/token.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Type } from 'class-transformer'
import { IsDate, IsInt, IsJWT, IsString, IsUUID, Min } from 'class-validator'
import { IsDate, IsDefined, IsJWT, IsString, IsUUID, Validate } from 'class-validator'
import IsTokenExpiration from './validation/token-expiration.validator'

export type TokenExpiration = number | 'never'

export class TokenDto {
@IsUUID()
Expand All @@ -10,7 +13,7 @@ export class TokenDto {

@Type(() => Date)
@IsDate()
expiresAt: Date
expiresAt?: Date

@Type(() => Date)
@IsDate()
Expand All @@ -21,9 +24,9 @@ export class GenerateTokenDto {
@IsString()
name: string

@IsInt()
@Min(1)
expirationInDays: number
@IsDefined()
@Validate(IsTokenExpiration)
expirationInDays: TokenExpiration
}

export class GeneratedTokenDto extends TokenDto {
Expand Down
16 changes: 12 additions & 4 deletions web/crux/src/app/token/token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ export default class TokenService {

async generateToken(req: GenerateTokenDto, identity: Identity): Promise<GeneratedTokenDto> {
const nonce = uuid()
const expirationDate = new Date(Date.now())
expirationDate.setDate(expirationDate.getDate() + req.expirationInDays)
this.logger.verbose(`Token expires at ${expirationDate.toISOString()}`)
const expirationDate =
req.expirationInDays === 'never' ? null : TokenService.getExpirationDate(req.expirationInDays)
this.logger.verbose(expirationDate ? `Token expires at ${expirationDate.toISOString()}` : 'Token never expries')

const payload: AuthPayload = {
sub: identity.id,
Expand All @@ -33,7 +33,9 @@ export default class TokenService {
},
})

const jwt = this.jwtService.sign({ exp: expirationDate.getTime() / 1000, data: payload })
const jwt = this.jwtService.sign(
expirationDate ? { exp: expirationDate.getTime() / 1000, data: payload } : { data: payload },
)

return this.mapper.generatedTokenToDto(newToken, jwt)
}
Expand Down Expand Up @@ -66,4 +68,10 @@ export default class TokenService {
},
})
}

private static getExpirationDate(days: number): Date {
const expirationDate = new Date(Date.now())
expirationDate.setDate(expirationDate.getDate() + days)
return expirationDate
}
}
20 changes: 20 additions & 0 deletions web/crux/src/app/token/validation/token-expiration.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'

@ValidatorConstraint({ name: 'token-expiration', async: false })
export default class IsTokenExpiration implements ValidatorConstraintInterface {
validate(value: any): boolean {
if (typeof value === 'number') {
return value > 0
}

if (typeof value !== 'string') {
return false
}

return value === 'never'
}

defaultMessage(): string {
return "$property must be a number in days (at least 1) or 'never'"
}
}