Change semi rule to enforce semicolons

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/3/head
trivernis 4 years ago
parent 910e120baf
commit 49e29259bd
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -24,8 +24,9 @@
"max-classes-per-file": 0, "max-classes-per-file": 0,
"no-var-requires": 0, "no-var-requires": 0,
"array-type": 0, "array-type": 0,
"semi": 1, "semi": ["error", "always"],
"semi-style": ["error", "last"] "semi-style": ["error", "last"],
"no-extra-semi": "off"
} }
} }

@ -1,14 +1,14 @@
import { DataSource } from 'apollo-datasource' import { DataSource } from 'apollo-datasource';
import { getConnection, Connection } from 'typeorm' import { getConnection, Connection } from 'typeorm';
import { CargoBike } from '../../model/CargoBike' import { CargoBike } from '../../model/CargoBike';
/** /**
* extended datasource to feed resolvers with data about cargoBikes * extended datasource to feed resolvers with data about cargoBikes
*/ */
export class CargoBikeAPI extends DataSource { export class CargoBikeAPI extends DataSource {
connection : Connection connection : Connection
constructor () { constructor () {
super() super();
this.connection = getConnection() this.connection = getConnection();
} }
/** /**
@ -18,15 +18,15 @@ export class CargoBikeAPI extends DataSource {
return { return {
id, id,
name: token name: token
} };
} }
async updateBike ({ id, token, name }:{id:any, token: string, name: string }) { async updateBike ({ id, token, name }:{id:any, token: string, name: string }) {
const bike = new CargoBike() const bike = new CargoBike();
bike.id = id bike.id = id;
bike.description = token bike.description = token;
bike.name = name bike.name = name;
await this.connection.manager.save(bike) await this.connection.manager.save(bike);
return { return {
success: true, success: true,
message: token, message: token,
@ -34,6 +34,6 @@ export class CargoBikeAPI extends DataSource {
id, id,
name name
} }
} };
} }
} }

@ -1,43 +1,43 @@
import { encode, decode } from 'messagepack' import { encode, decode } from 'messagepack';
import { Method } from './method' import { Method } from './method';
import { crc32 } from 'crc' import { crc32 } from 'crc';
export class RPCMessage<T> { export class RPCMessage<T> {
private readonly method: Method private readonly method: Method
readonly data: T readonly data: T
constructor (method: Method, data: any) { constructor (method: Method, data: any) {
this.method = method this.method = method;
this.data = data this.data = data;
} }
static fromBuffer<T> (raw: Buffer): RPCMessage<T> { static fromBuffer<T> (raw: Buffer): RPCMessage<T> {
const length = raw.readUInt32BE() const length = raw.readUInt32BE();
if (raw.length !== length) { if (raw.length !== length) {
throw new Error('Invalid Buffer length') throw new Error('Invalid Buffer length');
} }
const crcNum = raw.readUInt32BE(length - 4) const crcNum = raw.readUInt32BE(length - 4);
if (crc32(raw.slice(0, length - 4)) !== crcNum) { if (crc32(raw.slice(0, length - 4)) !== crcNum) {
throw new Error('Validation check failed') throw new Error('Validation check failed');
} }
const method = raw.readUInt32BE(4) const method = raw.readUInt32BE(4);
const msgData = decode(raw.slice(8, length)) const msgData = decode(raw.slice(8, length));
return new RPCMessage(method, msgData) return new RPCMessage(method, msgData);
} }
public toBuffer (): Buffer { public toBuffer (): Buffer {
const msgData = encode(this.data) const msgData = encode(this.data);
const length = msgData.length + 12 const length = msgData.length + 12;
const buffer = Buffer.alloc(length - 4) const buffer = Buffer.alloc(length - 4);
buffer.writeUInt32BE(length) buffer.writeUInt32BE(length);
buffer.writeUInt32BE(this.method, 4) buffer.writeUInt32BE(this.method, 4);
buffer.fill(msgData, 8) buffer.fill(msgData, 8);
const crcNum = crc32(buffer) const crcNum = crc32(buffer);
const resultBuffer = Buffer.alloc(length, buffer) const resultBuffer = Buffer.alloc(length, buffer);
resultBuffer.writeUInt32BE(crcNum, length - 4) resultBuffer.writeUInt32BE(crcNum, length - 4);
return resultBuffer return resultBuffer;
} }
} }

@ -14,4 +14,4 @@ export const requiredPermissions = [
name: Permission.WriteBike, name: Permission.WriteBike,
description: 'Allows the modification of bike information' description: 'Allows the modification of bike information'
} }
] ];

@ -1,16 +1,16 @@
import { DataSource } from 'apollo-datasource' import { DataSource } from 'apollo-datasource';
import { Socket } from 'net' import { Socket } from 'net';
import { PromiseSocket } from 'promise-socket' import { PromiseSocket } from 'promise-socket';
import { RPCMessage } from './message' import { RPCMessage } from './message';
import { Method } from './method' import { Method } from './method';
import { import {
CreateRoleResponse, CreateRoleResponse,
GetInfoResponse, GetInfoResponse,
GetRolesPermissionsResponse, GetRolesPermissionsResponse,
GetRolesResponse, GetRolesResponse,
ValidateTokenResponse ValidateTokenResponse
} from './responses' } from './responses';
import { Permission, requiredPermissions } from './permission' import { Permission, requiredPermissions } from './permission';
/** /**
* fetches datafrom user server, especially validates user tokens * fetches datafrom user server, especially validates user tokens
@ -20,13 +20,13 @@ export class UserServerAPI extends DataSource {
host: string host: string
constructor (address: string) { constructor (address: string) {
super() super();
const parts = address.split(':') const parts = address.split(':');
this.host = parts[0] this.host = parts[0];
if (parts.length === 2) { if (parts.length === 2) {
this.port = Number(parts[1]) this.port = Number(parts[1]);
} else { } else {
this.port = 5000 this.port = 5000;
} }
} }
@ -34,16 +34,16 @@ export class UserServerAPI extends DataSource {
* Returns the information about all available rpc methods * Returns the information about all available rpc methods
*/ */
async getInfo (): Promise<GetInfoResponse> { async getInfo (): Promise<GetInfoResponse> {
const response = await this.send<GetInfoResponse>(new RPCMessage(Method.Info, null)) const response = await this.send<GetInfoResponse>(new RPCMessage(Method.Info, null));
return response.data return response.data;
} }
/** /**
* Creates required API permissions * Creates required API permissions
*/ */
async createDefinedPermissions () { async createDefinedPermissions () {
await this.send<any>(new RPCMessage(Method.CreatePermissions, { permissions: requiredPermissions })) await this.send<any>(new RPCMessage(Method.CreatePermissions, { permissions: requiredPermissions }));
} }
/** /**
@ -57,20 +57,20 @@ export class UserServerAPI extends DataSource {
name, name,
description, description,
permissions: permissionIDs permissions: permissionIDs
})) }));
return response.data return response.data;
} }
/** /**
* validates user token * validates user token
*/ */
async validateToken (token:string): Promise<boolean> { async validateToken (token:string): Promise<boolean> {
const response = await this.send<ValidateTokenResponse>(new RPCMessage(Method.ValidateToken, { token })) const response = await this.send<ValidateTokenResponse>(new RPCMessage(Method.ValidateToken, { token }));
if (response) { if (response) {
return response.data[0] return response.data[0];
} else { } else {
return false return false;
} }
} }
@ -79,8 +79,8 @@ export class UserServerAPI extends DataSource {
* @param token * @param token
*/ */
async getUserRoles (token: String): Promise<GetRolesResponse> { async getUserRoles (token: String): Promise<GetRolesResponse> {
const response = await this.send<any>(new RPCMessage(Method.GetRoles, { token })) const response = await this.send<any>(new RPCMessage(Method.GetRoles, { token }));
return response.data return response.data;
} }
/** /**
@ -88,27 +88,27 @@ export class UserServerAPI extends DataSource {
* @param token * @param token
*/ */
async getUserPermissions (token: String): Promise<string[]> { async getUserPermissions (token: String): Promise<string[]> {
const roles = await this.getUserRoles(token) const roles = await this.getUserRoles(token);
const roleIds = roles.map(role => role[0]) const roleIds = roles.map(role => role[0]);
const permissionsResponse = await this.send<GetRolesPermissionsResponse>(new RPCMessage(Method.GetRolePermissions, { roles: roleIds })) const permissionsResponse = await this.send<GetRolesPermissionsResponse>(new RPCMessage(Method.GetRolePermissions, { roles: roleIds }));
const permissions: string[] = [] const permissions: string[] = [];
for (const id of roleIds) { for (const id of roleIds) {
permissions.push(...permissionsResponse.data[id].map(entry => entry[1])) permissions.push(...permissionsResponse.data[id].map(entry => entry[1]));
} }
return permissions return permissions;
} }
/** /**
* Connects to the socket and returns the client * Connects to the socket and returns the client
*/ */
async getSocket (): Promise<PromiseSocket<Socket>> { async getSocket (): Promise<PromiseSocket<Socket>> {
const socket = new Socket() const socket = new Socket();
const promiseSocket = new PromiseSocket(socket) const promiseSocket = new PromiseSocket(socket);
await promiseSocket.connect(this.port, this.host) await promiseSocket.connect(this.port, this.host);
return promiseSocket return promiseSocket;
} }
/** /**
@ -116,12 +116,12 @@ export class UserServerAPI extends DataSource {
* @param message * @param message
*/ */
async send<T> (message: RPCMessage<any>): Promise<RPCMessage<T>> { async send<T> (message: RPCMessage<any>): Promise<RPCMessage<T>> {
const socket = await this.getSocket() const socket = await this.getSocket();
await socket.writeAll(message.toBuffer()) await socket.writeAll(message.toBuffer());
const response = await socket.readAll() as Buffer const response = await socket.readAll() as Buffer;
if (response?.length > 0) { if (response?.length > 0) {
return RPCMessage.fromBuffer<T>(response) return RPCMessage.fromBuffer<T>(response);
} }
} }
} }

@ -1,14 +1,14 @@
import { ApolloServer } from 'apollo-server-express' import { ApolloServer } from 'apollo-server-express';
import bikeresolver from './resolvers/cargobikeResolver' import bikeresolver from './resolvers/cargobikeResolver';
import { CargoBikeAPI } from './datasources/db/cargobikeAPI' import { CargoBikeAPI } from './datasources/db/cargobikeAPI';
import typeDefs from './schema/type-defs' import typeDefs from './schema/type-defs';
import 'reflect-metadata' import 'reflect-metadata';
import { createConnection } from 'typeorm' import { createConnection } from 'typeorm';
import { UserServerAPI } from './datasources/userserver/userserviceAPI' import { UserServerAPI } from './datasources/userserver/userserviceAPI';
import express from 'express' import express from 'express';
import { requiredPermissions } from './datasources/userserver/permission' import { requiredPermissions } from './datasources/userserver/permission';
require('dotenv').config() require('dotenv').config();
/** /**
* Function that is called to authenticate a user by using the user rpc server * Function that is called to authenticate a user by using the user rpc server
@ -18,30 +18,30 @@ require('dotenv').config()
*/ */
async function authenticate (req: any, res: any, next: any) { async function authenticate (req: any, res: any, next: any) {
if (process.env.NODE_ENV === 'develop') { if (process.env.NODE_ENV === 'develop') {
req.permissions = requiredPermissions.map((e) => e.name) req.permissions = requiredPermissions.map((e) => e.name);
next() next();
} else { } else {
const token = req.headers.authorization?.replace('Bearer ', '') const token = req.headers.authorization?.replace('Bearer ', '');
if (token) { if (token) {
if (await userAPI.validateToken(token)) { if (await userAPI.validateToken(token)) {
req.permissions = await userAPI.getUserPermissions(token) req.permissions = await userAPI.getUserPermissions(token);
next() next();
} else { } else {
res.status(401) res.status(401);
res.send('Unauthorized') res.send('Unauthorized');
} }
} else { } else {
res.status(401) res.status(401);
res.send('Unauthorized') res.send('Unauthorized');
} }
} }
} }
createConnection().then(async () => { createConnection().then(async () => {
console.log('connected to db') console.log('connected to db');
}).catch(error => console.log(error)) }).catch(error => console.log(error));
const userAPI = new UserServerAPI(process.env.RPC_HOST) const userAPI = new UserServerAPI(process.env.RPC_HOST);
const server = new ApolloServer({ const server = new ApolloServer({
resolvers: [bikeresolver], resolvers: [bikeresolver],
@ -51,18 +51,18 @@ const server = new ApolloServer({
userAPI userAPI
}), }),
context: (req: any) => { context: (req: any) => {
return req return req;
} }
}) });
const app = express() const app = express();
app.post('/graphql', authenticate) app.post('/graphql', authenticate);
app.get(/\/graphql?&.*query=/, authenticate) app.get(/\/graphql?&.*query=/, authenticate);
server.applyMiddleware({ app }) server.applyMiddleware({ app });
console.log(__dirname) console.log(__dirname);
app.listen(4000, async () => { app.listen(4000, async () => {
console.log('Server listening on port 4000') console.log('Server listening on port 4000');
await userAPI.createDefinedPermissions() await userAPI.createDefinedPermissions();
}) });

@ -1,4 +1,4 @@
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm' import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity() @Entity()
export class CargoBike { export class CargoBike {

@ -1,23 +1,23 @@
import { Permission } from '../datasources/userserver/permission' import { Permission } from '../datasources/userserver/permission';
import { GraphQLError } from 'graphql' import { GraphQLError } from 'graphql';
export default { export default {
Query: { Query: {
CargobikeById: (_: any, { id, token }:{id: any, token: string}, { dataSources, req }:{dataSources: any, req: any }) => { CargobikeById: (_: any, { id, token }:{id: any, token: string}, { dataSources, req }:{dataSources: any, req: any }) => {
if (req.permissions.includes(Permission.ReadBike)) { if (req.permissions.includes(Permission.ReadBike)) {
return dataSources.cargoBikeAPI.findCargoBikeById({ id, token }) return dataSources.cargoBikeAPI.findCargoBikeById({ id, token });
} else { } else {
throw new GraphQLError('Insufficient Permissions') throw new GraphQLError('Insufficient Permissions');
} }
} }
}, },
Mutation: { Mutation: {
addBike: (_: any, { id, token, name }:{id: any, token: string, name:string}, { dataSources, req }:{dataSources: any, req: any }) => { addBike: (_: any, { id, token, name }:{id: any, token: string, name:string}, { dataSources, req }:{dataSources: any, req: any }) => {
if (req.permissions.includes(Permission.WriteBike)) { if (req.permissions.includes(Permission.WriteBike)) {
return dataSources.cargoBikeAPI.updateBike({ id, token, name }) return dataSources.cargoBikeAPI.updateBike({ id, token, name });
} else { } else {
throw new GraphQLError('Insufficient Permissions') throw new GraphQLError('Insufficient Permissions');
} }
} }
} }
} };

@ -1,4 +1,4 @@
import { gql } from 'apollo-server' import { gql } from 'apollo-server';
export default gql` export default gql`
@ -355,4 +355,4 @@ type Mutation {
cargoBike(token:String!,cargoBike: CargoBikeInput): UpdateBikeResponse! cargoBike(token:String!,cargoBike: CargoBikeInput): UpdateBikeResponse!
} }
` `;

Loading…
Cancel
Save