Skip to content

Commit

Permalink
Personal access tokens backend (#2064)
Browse files Browse the repository at this point in the history
* First version ready

* Final

* Refactor

* Update pat store

* Website revert

* Website revert

* Update

* Revert website

* Revert docs to main

* Revert docs to main

* Fix eslint

* Test

* Fix table name
  • Loading branch information
sjaanus committed Sep 16, 2022
1 parent 26c88ff commit 1cf42d6
Show file tree
Hide file tree
Showing 26 changed files with 664 additions and 34 deletions.
5 changes: 3 additions & 2 deletions .eslintignore
Expand Up @@ -3,11 +3,12 @@ docker
bundle.js
website/blog
website/build
website/core
website/docs
website/node_modules
website/i18n/*.js
website/translated_docs
website/core
website/pages
website/translated_docs
website
setupJest.js
frontend
3 changes: 2 additions & 1 deletion .prettierignore
@@ -1 +1,2 @@
CHANGELOG.md
CHANGELOG.md
website/docs
2 changes: 2 additions & 0 deletions src/lib/db/index.ts
Expand Up @@ -30,6 +30,7 @@ import UserSplashStore from './user-splash-store';
import RoleStore from './role-store';
import SegmentStore from './segment-store';
import GroupStore from './group-store';
import PatStore from './pat-store';
import { PublicSignupTokenStore } from './public-signup-token-store';

export const createStores = (
Expand Down Expand Up @@ -90,6 +91,7 @@ export const createStores = (
eventBus,
getLogger,
),
patStore: new PatStore(db, getLogger),
};
};

Expand Down
87 changes: 87 additions & 0 deletions src/lib/db/pat-store.ts
@@ -0,0 +1,87 @@
import { Knex } from 'knex';
import { Logger, LogProvider } from '../logger';
import { IPatStore } from '../types/stores/pat-store';
import Pat, { IPat } from '../types/models/pat';
import NotFoundError from '../error/notfound-error';

const TABLE = 'personal_access_tokens';

const PAT_COLUMNS = [
'secret',
'user_id',
'expires_at',
'created_at',
'seen_at',
];

const fromRow = (row) => {
if (!row) {
throw new NotFoundError('No PAT found');
}
return new Pat({
secret: row.secret,
userId: row.user_id,
createdAt: row.created_at,
seenAt: row.seen_at,
expiresAt: row.expires_at,
});
};

const toRow = (user: IPat) => ({
secret: user.secret,
user_id: user.userId,
expires_at: user.expiresAt,
});

export default class PatStore implements IPatStore {
private db: Knex;

private logger: Logger;

constructor(db: Knex, getLogger: LogProvider) {
this.db = db;
this.logger = getLogger('pat-store.ts');
}

async create(token: IPat): Promise<IPat> {
const row = await this.db(TABLE).insert(toRow(token)).returning('*');
return fromRow(row[0]);
}

async delete(secret: string): Promise<void> {
return this.db(TABLE).where({ secret: secret }).del();
}

async deleteAll(): Promise<void> {
await this.db(TABLE).del();
}

destroy(): void {}

async exists(secret: string): Promise<boolean> {
const result = await this.db.raw(
`SELECT EXISTS(SELECT 1 FROM ${TABLE} WHERE secret = ?) AS present`,
[secret],
);
const { present } = result.rows[0];
return present;
}

async get(secret: string): Promise<Pat> {
const row = await this.db(TABLE).where({ secret }).first();
return fromRow(row);
}

async getAll(): Promise<Pat[]> {
const groups = await this.db.select(PAT_COLUMNS).from(TABLE);
return groups.map(fromRow);
}

async getAllByUser(userId: number): Promise<Pat[]> {
const groups = await this.db
.select(PAT_COLUMNS)
.from(TABLE)
.where('user_id', userId);
return groups.map(fromRow);
}
}
2 changes: 1 addition & 1 deletion src/lib/db/segment-store.ts
Expand Up @@ -4,8 +4,8 @@ import { Logger, LogProvider } from '../logger';
import { Knex } from 'knex';
import EventEmitter from 'events';
import NotFoundError from '../error/notfound-error';
import User from '../types/user';
import { PartialSome } from '../types/partial';
import User from '../types/user';

const T = {
segments: 'segments',
Expand Down
4 changes: 4 additions & 0 deletions src/lib/openapi/index.ts
Expand Up @@ -113,6 +113,8 @@ import { proxyMetricsSchema } from './spec/proxy-metrics-schema';
import { setUiConfigSchema } from './spec/set-ui-config-schema';
import { edgeTokenSchema } from './spec/edge-token-schema';
import { validateEdgeTokensSchema } from './spec/validate-edge-tokens-schema';
import { patsSchema } from './spec/pats-schema';
import { patSchema } from './spec/pat-schema';
import { publicSignupTokenCreateSchema } from './spec/public-signup-token-create-schema';
import { publicSignupTokenSchema } from './spec/public-signup-token-schema';
import { publicSignupTokensSchema } from './spec/public-signup-tokens-schema';
Expand Down Expand Up @@ -178,6 +180,8 @@ export const schemas = {
overrideSchema,
parametersSchema,
passwordSchema,
patSchema,
patsSchema,
patchesSchema,
patchSchema,
permissionSchema,
Expand Down
31 changes: 31 additions & 0 deletions src/lib/openapi/spec/pat-schema.ts
@@ -0,0 +1,31 @@
import { FromSchema } from 'json-schema-to-ts';

export const patSchema = {
$id: '#/components/schemas/patSchema',
type: 'object',
properties: {
secret: {
type: 'string',
},
expiresAt: {
type: 'string',
format: 'date-time',
nullable: true,
},
createdAt: {
type: 'string',
format: 'date-time',
nullable: true,
},
seenAt: {
type: 'string',
format: 'date-time',
nullable: true,
},
},
components: {
schemas: {},
},
} as const;

export type PatSchema = FromSchema<typeof patSchema>;
22 changes: 22 additions & 0 deletions src/lib/openapi/spec/pats-schema.ts
@@ -0,0 +1,22 @@
import { FromSchema } from 'json-schema-to-ts';
import { patSchema } from './pat-schema';

export const patsSchema = {
$id: '#/components/schemas/patsSchema',
type: 'object',
properties: {
pats: {
type: 'array',
items: {
$ref: '#/components/schemas/patSchema',
},
},
},
components: {
schemas: {
patSchema,
},
},
} as const;

export type PatsSchema = FromSchema<typeof patsSchema>;
7 changes: 6 additions & 1 deletion src/lib/routes/admin-api/index.ts
Expand Up @@ -7,7 +7,7 @@ import StrategyController from './strategy';
import EventController from './event';
import PlaygroundController from './playground';
import MetricsController from './metrics';
import UserController from './user';
import UserController from './user/user';
import ConfigController from './config';
import { ContextController } from './context';
import ClientMetricsController from './client-metrics';
Expand All @@ -23,6 +23,7 @@ import UserSplashController from './user-splash';
import ProjectApi from './project';
import { EnvironmentsController } from './environments';
import ConstraintsController from './constraints';
import PatController from './user/pat';
import { PublicSignupController } from './public-signup';
import { conditionalMiddleware } from '../../middleware/conditional-middleware';

Expand Down Expand Up @@ -61,6 +62,10 @@ class AdminApi extends Controller {
new ClientMetricsController(config, services).router,
);
this.app.use('/user', new UserController(config, services).router);
this.app.use(
'/user/tokens',
new PatController(config, services).router,
);
this.app.use(
'/ui-config',
new ConfigController(config, services).router,
Expand Down
105 changes: 105 additions & 0 deletions src/lib/routes/admin-api/user/pat.ts
@@ -0,0 +1,105 @@
import { Response } from 'express';
import Controller from '../../controller';
import { Logger } from '../../../logger';
import { IUnleashConfig, IUnleashServices } from '../../../types';
import { createRequestSchema } from '../../../openapi/util/create-request-schema';
import { createResponseSchema } from '../../../openapi/util/create-response-schema';
import { OpenApiService } from '../../../services/openapi-service';
import { emptyResponse } from '../../../openapi/util/standard-responses';

import PatService from '../../../services/pat-service';
import { NONE } from '../../../types/permissions';
import { IAuthRequest } from '../../unleash-types';
import { serializeDates } from '../../../types/serialize-dates';
import { PatSchema, patSchema } from '../../../openapi/spec/pat-schema';
import { patsSchema } from '../../../openapi/spec/pats-schema';

export default class PatController extends Controller {
private patService: PatService;

private openApiService: OpenApiService;

private logger: Logger;

constructor(
config: IUnleashConfig,
{
openApiService,
patService,
}: Pick<IUnleashServices, 'openApiService' | 'patService'>,
) {
super(config);
this.logger = config.getLogger('lib/routes/auth/pat-controller.ts');
this.openApiService = openApiService;
this.patService = patService;
this.route({
method: 'get',
path: '',
handler: this.getPats,
permission: NONE,
middleware: [
openApiService.validPath({
tags: ['admin'],
operationId: 'getPats',
responses: { 200: createResponseSchema('patsSchema') },
}),
],
});
this.route({
method: 'post',
path: '',
handler: this.createPat,
permission: NONE,
middleware: [
openApiService.validPath({
tags: ['admin'],
operationId: 'createPat',
requestBody: createRequestSchema('patSchema'),
responses: { 200: createResponseSchema('patSchema') },
}),
],
});

this.route({
method: 'delete',
path: '/:secret',
acceptAnyContentType: true,
handler: this.deletePat,
permission: NONE,
middleware: [
openApiService.validPath({
tags: ['admin'],
operationId: 'deletePat',
responses: { 200: emptyResponse },
}),
],
});
}

async createPat(req: IAuthRequest, res: Response): Promise<void> {
const pat = req.body;
const createdPat = await this.patService.createPat(pat, req.user);
this.openApiService.respondWithValidation(
201,
res,
patSchema.$id,
serializeDates(createdPat),
);
}

async getPats(req: IAuthRequest, res: Response<PatSchema>): Promise<void> {
const pats = await this.patService.getAll(req.user);
this.openApiService.respondWithValidation(200, res, patsSchema.$id, {
pats: serializeDates(pats),
});
}

async deletePat(
req: IAuthRequest<{ secret: string }>,
res: Response,
): Promise<void> {
const { secret } = req.params;
await this.patService.deletePat(secret);
res.status(200).end();
}
}
@@ -1,10 +1,10 @@
import supertest from 'supertest';
import { createServices } from '../../services';
import { createTestConfig } from '../../../test/config/test-config';
import { createServices } from '../../../services';
import { createTestConfig } from '../../../../test/config/test-config';

import createStores from '../../../test/fixtures/store';
import getApp from '../../app';
import User from '../../types/user';
import createStores from '../../../../test/fixtures/store';
import getApp from '../../../app';
import User from '../../../types/user';

const currentUser = new User({ id: 1337, email: 'test@mail.com' });

Expand Down
@@ -1,21 +1,21 @@
import { Response } from 'express';
import { IAuthRequest } from '../unleash-types';
import Controller from '../controller';
import { AccessService } from '../../services/access-service';
import { IAuthType, IUnleashConfig } from '../../types/option';
import { IUnleashServices } from '../../types/services';
import UserService from '../../services/user-service';
import UserFeedbackService from '../../services/user-feedback-service';
import UserSplashService from '../../services/user-splash-service';
import { ADMIN, NONE } from '../../types/permissions';
import { OpenApiService } from '../../services/openapi-service';
import { createRequestSchema } from '../../openapi/util/create-request-schema';
import { createResponseSchema } from '../../openapi/util/create-response-schema';
import { meSchema, MeSchema } from '../../openapi/spec/me-schema';
import { serializeDates } from '../../types/serialize-dates';
import { IUserPermission } from '../../types/stores/access-store';
import { PasswordSchema } from '../../openapi/spec/password-schema';
import { emptyResponse } from '../../openapi/util/standard-responses';
import { IAuthRequest } from '../../unleash-types';
import Controller from '../../controller';
import { AccessService } from '../../../services/access-service';
import { IAuthType, IUnleashConfig } from '../../../types/option';
import { IUnleashServices } from '../../../types/services';
import UserService from '../../../services/user-service';
import UserFeedbackService from '../../../services/user-feedback-service';
import UserSplashService from '../../../services/user-splash-service';
import { ADMIN, NONE } from '../../../types/permissions';
import { OpenApiService } from '../../../services/openapi-service';
import { createRequestSchema } from '../../../openapi/util/create-request-schema';
import { createResponseSchema } from '../../../openapi/util/create-response-schema';
import { meSchema, MeSchema } from '../../../openapi/spec/me-schema';
import { serializeDates } from '../../../types/serialize-dates';
import { IUserPermission } from '../../../types/stores/access-store';
import { PasswordSchema } from '../../../openapi/spec/password-schema';
import { emptyResponse } from '../../../openapi/util/standard-responses';

class UserController extends Controller {
private accessService: AccessService;
Expand Down

0 comments on commit 1cf42d6

Please sign in to comment.