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 all 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
4 changes: 2 additions & 2 deletions web/crux-ui/src/components/settings/create-token-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { useFormik } from 'formik'
import useTranslation from 'next-translate/useTranslation'
import { MutableRefObject } from 'react'

const EXPIRATION_VALUES = [30, 60, 90]
const EXPIRATION_VALUES = [30, 60, 90, 0]

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 === 0 ? t('common:never') : t('common:days', { days: it }))}
onSelectionChange={it => {
formik.setFieldValue('expirationInDays', it, false)
}}
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
2 changes: 1 addition & 1 deletion web/crux-ui/src/validations/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ 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.number().min(0).required(),
})
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 < 0) {
throw new CruxBadRequestException({
property: 'expirationInDays',
value: req.expirationInDays,
Expand Down
4 changes: 2 additions & 2 deletions web/crux/src/app/token/token.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class TokenDto {

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

@Type(() => Date)
@IsDate()
Expand All @@ -22,7 +22,7 @@ export class GenerateTokenDto {
name: string

@IsInt()
@Min(1)
@Min(0)
expirationInDays: number
}

Expand Down
15 changes: 11 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,8 @@ 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 === 0 ? 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 +32,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 +67,10 @@ export default class TokenService {
},
})
}

private static getExpirationDate(days: number): Date {
const expirationDate = new Date(Date.now())
expirationDate.setDate(expirationDate.getDate() + days)
return expirationDate
}
}
Loading