-
-
Notifications
You must be signed in to change notification settings - Fork 441
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(core): create PAT #6388
Merged
Merged
feat(core): create PAT #6388
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { type PersonalAccessToken, PersonalAccessTokens } from '@logto/schemas'; | ||
import { type CommonQueryMethods, sql } from '@silverhand/slonik'; | ||
|
||
import { buildInsertIntoWithPool } from '#src/database/insert-into.js'; | ||
import { DeletionError } from '#src/errors/SlonikError/index.js'; | ||
import { convertToIdentifiers } from '#src/utils/sql.js'; | ||
|
||
import { buildUpdateWhereWithPool } from '../database/update-where.js'; | ||
|
||
const { table, fields } = convertToIdentifiers(PersonalAccessTokens); | ||
|
||
export class PersonalAccessTokensQueries { | ||
public readonly insert = buildInsertIntoWithPool(this.pool)(PersonalAccessTokens, { | ||
returning: true, | ||
}); | ||
|
||
public readonly update = buildUpdateWhereWithPool(this.pool)(PersonalAccessTokens, true); | ||
|
||
constructor(public readonly pool: CommonQueryMethods) {} | ||
|
||
async findByValue(value: string) { | ||
return this.pool.maybeOne<PersonalAccessToken>(sql` | ||
select ${sql.join(Object.values(fields), sql`, `)} | ||
from ${table} | ||
where ${fields.value} = ${value} | ||
`); | ||
} | ||
|
||
async getTokensByUserId(userId: string) { | ||
return this.pool.any<PersonalAccessToken>(sql` | ||
select ${sql.join(Object.values(fields), sql`, `)} | ||
from ${table} | ||
where ${fields.userId} = ${userId} | ||
`); | ||
} | ||
|
||
async deleteByName(appId: string, name: string) { | ||
const { rowCount } = await this.pool.query(sql` | ||
delete from ${table} | ||
where ${fields.userId} = ${appId} | ||
and ${fields.name} = ${name} | ||
`); | ||
if (rowCount < 1) { | ||
throw new DeletionError(PersonalAccessTokens.table, name); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
packages/core/src/routes/admin-user/personal-access-token.openapi.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
{ | ||
"tags": [ | ||
{ | ||
"name": "Dev feature" | ||
} | ||
], | ||
"paths": { | ||
"/api/users/{userId}/personal-access-tokens": { | ||
"post": { | ||
"summary": "Add personal access token", | ||
"description": "Add a new personal access token for the user.", | ||
"requestBody": { | ||
"content": { | ||
"application/json": { | ||
"schema": { | ||
"properties": { | ||
"name": { | ||
"description": "The personal access token name. Must be unique within the user." | ||
}, | ||
"expiresAt": { | ||
"description": "The epoch time in milliseconds when the token will expire. If not provided, the token will never expire." | ||
} | ||
} | ||
} | ||
} | ||
} | ||
}, | ||
"responses": { | ||
"201": { | ||
"description": "The personal access token was added successfully." | ||
}, | ||
"422": { | ||
"description": "The personal access token name is already in use." | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
46 changes: 46 additions & 0 deletions
46
packages/core/src/routes/admin-user/personal-access-token.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { PersonalAccessTokens } from '@logto/schemas'; | ||
import { generateStandardSecret } from '@logto/shared'; | ||
import { z } from 'zod'; | ||
|
||
import RequestError from '#src/errors/RequestError/index.js'; | ||
import koaGuard from '#src/middleware/koa-guard.js'; | ||
import assertThat from '#src/utils/assert-that.js'; | ||
|
||
import { type ManagementApiRouter, type RouterInitArgs } from '../types.js'; | ||
|
||
export default function adminUserPersonalAccessTokenRoutes<T extends ManagementApiRouter>( | ||
...[router, { queries }]: RouterInitArgs<T> | ||
) { | ||
router.post( | ||
'/users/:userId/personal-access-tokens', | ||
koaGuard({ | ||
params: z.object({ userId: z.string() }), | ||
body: PersonalAccessTokens.createGuard.pick({ name: true, expiresAt: true }), | ||
response: PersonalAccessTokens.guard, | ||
status: [201, 400], | ||
}), | ||
async (ctx, next) => { | ||
const { | ||
params: { userId }, | ||
body, | ||
} = ctx.guard; | ||
|
||
assertThat( | ||
!body.expiresAt || body.expiresAt > Date.now(), | ||
new RequestError({ | ||
code: 'request.invalid_input', | ||
details: 'The value of `expiresAt` must be in the future.', | ||
}) | ||
); | ||
|
||
ctx.body = await queries.personalAccessTokens.insert({ | ||
...body, | ||
userId, | ||
value: `pat_${generateStandardSecret()}`, | ||
}); | ||
ctx.status = 201; | ||
|
||
return next(); | ||
} | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
packages/integration-tests/src/tests/api/admin-user.personal-access-tokens.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
import { HTTPError } from 'ky'; | ||
|
||
import { createPersonalAccessToken, deleteUser } from '#src/api/admin-user.js'; | ||
import { createUserByAdmin } from '#src/helpers/index.js'; | ||
import { devFeatureTest, randomString } from '#src/utils.js'; | ||
|
||
devFeatureTest.describe('personal access tokens', () => { | ||
it('should throw error when creating PAT with existing name', async () => { | ||
const user = await createUserByAdmin(); | ||
const name = randomString(); | ||
await createPersonalAccessToken({ userId: user.id, name }); | ||
|
||
const response = await createPersonalAccessToken({ userId: user.id, name }).catch( | ||
(error: unknown) => error | ||
); | ||
|
||
expect(response).toBeInstanceOf(HTTPError); | ||
expect(response).toHaveProperty('response.status', 422); | ||
expect(await (response as HTTPError).response.json()).toHaveProperty( | ||
'code', | ||
'user.personal_access_token_name_exists' | ||
); | ||
|
||
await deleteUser(user.id); | ||
}); | ||
|
||
it('should throw error when creating PAT with invalid user id', async () => { | ||
const name = randomString(); | ||
const response = await createPersonalAccessToken({ | ||
userId: 'invalid', | ||
name, | ||
}).catch((error: unknown) => error); | ||
|
||
expect(response).toBeInstanceOf(HTTPError); | ||
expect(response).toHaveProperty('response.status', 404); | ||
}); | ||
|
||
it('should throw error when creating PAT with empty name', async () => { | ||
const user = await createUserByAdmin(); | ||
const response = await createPersonalAccessToken({ | ||
userId: user.id, | ||
name: '', | ||
}).catch((error: unknown) => error); | ||
|
||
expect(response).toBeInstanceOf(HTTPError); | ||
expect(response).toHaveProperty('response.status', 400); | ||
|
||
await deleteUser(user.id); | ||
}); | ||
|
||
it('should throw error when creating PAT with invalid expiresAt', async () => { | ||
const user = await createUserByAdmin(); | ||
const name = randomString(); | ||
const response = await createPersonalAccessToken({ | ||
userId: user.id, | ||
name, | ||
expiresAt: Date.now() - 1000, | ||
}).catch((error: unknown) => error); | ||
|
||
expect(response).toBeInstanceOf(HTTPError); | ||
expect(response).toHaveProperty('response.status', 400); | ||
|
||
await deleteUser(user.id); | ||
}); | ||
|
||
it('should be able to create multiple PATs', async () => { | ||
const user = await createUserByAdmin(); | ||
const name1 = randomString(); | ||
const name2 = randomString(); | ||
const pat1 = await createPersonalAccessToken({ | ||
userId: user.id, | ||
name: name1, | ||
expiresAt: Date.now() + 1000, | ||
}); | ||
const pat2 = await createPersonalAccessToken({ | ||
userId: user.id, | ||
name: name2, | ||
}); | ||
|
||
expect(pat1).toHaveProperty('name', name1); | ||
expect(pat2).toHaveProperty('name', name2); | ||
|
||
await deleteUser(user.id); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: wondering would it be helpful if we put the userId as a prefix, e.g. `pat_${uid}_${generateStandardSecret()}