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: Implement users/me API endpoint #1591

Merged
merged 2 commits into from
Feb 13, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { renderObject } from '../../../../helpers/renderer.js';

export default async (request, response) => {
renderObject(response, request.currentUser);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expect, beforeEach } from 'vitest';
import request from 'supertest';
import app from '../../../../app.js';
import createAuthTokenByUserId from '../../../../helpers/create-auth-token-by-user-id';
import { createUser } from '../../../../../test/factories/user';
import userPayload from '../../../../../test/payloads/user';

describe('GET /api/v1/users/me', () => {
let role, currentUser, token;

beforeEach(async () => {
currentUser = await createUser();
role = await currentUser.$relatedQuery('role');
token = createAuthTokenByUserId(currentUser.id);
});

it('should return current user info', async () => {
const response = await request(app)
.get('/api/v1/users/me')
.set('Authorization', token)
.expect(200);

const expectedPayload = userPayload(currentUser, role);
expect(response.body).toEqual(expectedPayload);
});
});
8 changes: 8 additions & 0 deletions packages/backend/src/helpers/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ export const isAuthenticated = async (_parent, _args, req) => {
}
};

export const authenticateUser = async (request, response, next) => {
if (await isAuthenticated(null, null, request)) {
next();
} else {
return response.status(401).end();
}
};

const isAuthenticatedRule = rule()(isAuthenticated);

export const authenticationRules = {
Expand Down
11 changes: 11 additions & 0 deletions packages/backend/src/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,17 @@ class User extends Base {
},
});

$formatJson(json) {
json = super.$formatJson(json);

delete json.password;
delete json.deletedAt;
delete json.resetPasswordToken;
delete json.resetPasswordTokenSentAt;

return json;
}

login(password) {
return bcrypt.compare(password, this.password);
}
Expand Down
9 changes: 9 additions & 0 deletions packages/backend/src/routes/api/v1/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Router } from 'express';
import { authenticateUser } from '../../../helpers/authentication.js';
import getCurrentUserAction from '../../../controllers/api/v1/users/get-current-user.js';

const router = Router();

router.get('/me', authenticateUser, getCurrentUserAction);

export default router;
2 changes: 2 additions & 0 deletions packages/backend/src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import webhooksRouter from './webhooks.js';
import paddleRouter from './paddle.ee.js';
import healthcheckRouter from './healthcheck.js';
import automatischRouter from './api/v1/automatisch.js';
import usersRouter from './api/v1/users.js';

const router = Router();

Expand All @@ -12,5 +13,6 @@ router.use('/webhooks', webhooksRouter);
router.use('/paddle', paddleRouter);
router.use('/healthcheck', healthcheckRouter);
router.use('/api/v1/automatisch', automatischRouter);
router.use('/api/v1/users', usersRouter);

export default router;
6 changes: 2 additions & 4 deletions packages/backend/test/factories/config.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { faker } from '@faker-js/faker';
import Config from '../../src/models/config';

export const createConfig = async (params = {}) => {
const configData = {
key: params?.key || faker.lorem.word(),
value: params?.value || { data: 'sampleConfig' },
};

const [config] = await global.knex
.table('config')
.insert(configData)
.returning('*');
const config = await Config.query().insert(configData).returning('*');

return config;
};
6 changes: 2 additions & 4 deletions packages/backend/test/factories/connection.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import appConfig from '../../src/config/app';
import { AES } from 'crypto-js';
import Connection from '../../src/models/connection';

export const createConnection = async (params = {}) => {
params.key = params?.key || 'deepl';
Expand All @@ -16,10 +17,7 @@ export const createConnection = async (params = {}) => {
appConfig.encryptionKey
).toString();

const [connection] = await global.knex
.table('connections')
.insert(params)
.returning('*');
const connection = await Connection.query().insert(params).returning('*');

return connection;
};
4 changes: 2 additions & 2 deletions packages/backend/test/factories/execution-step.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ExecutionStep from '../../src/models/execution-step';
import { createExecution } from './execution';
import { createStep } from './step';

Expand All @@ -8,8 +9,7 @@ export const createExecutionStep = async (params = {}) => {
params.dataIn = params?.dataIn || { dataIn: 'dataIn' };
params.dataOut = params?.dataOut || { dataOut: 'dataOut' };

const [executionStep] = await global.knex
.table('executionSteps')
const executionStep = await ExecutionStep.query()
.insert(params)
.returning('*');

Expand Down
6 changes: 2 additions & 4 deletions packages/backend/test/factories/execution.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Execution from '../../src/models/execution';
import { createFlow } from './flow';

export const createExecution = async (params = {}) => {
Expand All @@ -6,10 +7,7 @@ export const createExecution = async (params = {}) => {
params.createdAt = params?.createdAt || new Date().toISOString();
params.updatedAt = params?.updatedAt || new Date().toISOString();

const [execution] = await global.knex
.table('executions')
.insert(params)
.returning('*');
const execution = await Execution.query().insert(params).returning('*');

return execution;
};
3 changes: 2 additions & 1 deletion packages/backend/test/factories/flow.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Flow from '../../src/models/flow';
import { createUser } from './user';

export const createFlow = async (params = {}) => {
Expand All @@ -6,7 +7,7 @@ export const createFlow = async (params = {}) => {
params.createdAt = params?.createdAt || new Date().toISOString();
params.updatedAt = params?.updatedAt || new Date().toISOString();

const [flow] = await global.knex.table('flows').insert(params).returning('*');
const flow = await Flow.query().insert(params).returning('*');

return flow;
};
6 changes: 2 additions & 4 deletions packages/backend/test/factories/permission.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Permission from '../../src/models/permission';
import { createRole } from './role';

export const createPermission = async (params = {}) => {
Expand All @@ -6,10 +7,7 @@ export const createPermission = async (params = {}) => {
params.subject = params?.subject || 'User';
params.conditions = params?.conditions || ['isCreator'];

const [permission] = await global.knex
.table('permissions')
.insert(params)
.returning('*');
const permission = await Permission.query().insert(params).returning('*');

return permission;
};
4 changes: 3 additions & 1 deletion packages/backend/test/factories/role.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import Role from '../../src/models/role';

export const createRole = async (params = {}) => {
params.name = params?.name || 'Viewer';
params.key = params?.key || 'viewer';

const [role] = await global.knex.table('roles').insert(params).returning('*');
const role = await Role.query().insert(params).returning('*');

return role;
};
3 changes: 2 additions & 1 deletion packages/backend/test/factories/step.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Step from '../../src/models/step';
import { createFlow } from './flow';

export const createStep = async (params = {}) => {
Expand All @@ -16,7 +17,7 @@ export const createStep = async (params = {}) => {
params.appKey =
params?.appKey || (params.type === 'action' ? 'deepl' : 'webhook');

const [step] = await global.knex.table('steps').insert(params).returning('*');
const step = await Step.query().insert(params).returning('*');

return step;
};
3 changes: 2 additions & 1 deletion packages/backend/test/factories/user.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { createRole } from './role';
import { faker } from '@faker-js/faker';
import User from '../../src/models/user';

export const createUser = async (params = {}) => {
params.roleId = params?.roleId || (await createRole()).id;
params.fullName = params?.fullName || faker.person.fullName();
params.email = params?.email || faker.internet.email();
params.password = params?.password || faker.internet.password();

const [user] = await global.knex.table('users').insert(params).returning('*');
const user = await User.query().insert(params).returning('*');

return user;
};
32 changes: 32 additions & 0 deletions packages/backend/test/payloads/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const userPayload = (currentUser, role) => {
return {
data: {
createdAt: currentUser.createdAt.toISOString(),
email: currentUser.email,
fullName: currentUser.fullName,
id: currentUser.id,
permissions: [],
role: {
createdAt: role.createdAt.toISOString(),
description: null,
id: role.id,
isAdmin: role.isAdmin,
key: role.key,
name: role.name,
updatedAt: role.updatedAt.toISOString(),
},
roleId: role.id,
trialExpiryDate: currentUser.trialExpiryDate.toISOString(),
updatedAt: currentUser.updatedAt.toISOString(),
},
meta: {
count: 1,
currentPage: null,
isArray: false,
totalPages: null,
type: 'User',
},
};
};

export default userPayload;