Passed
Push — master ( e6aee2...1ab6c1 )
by Leandro
01:23
created

app.ts ➔ createApp   A

Complexity

Conditions 1

Size

Total Lines 32
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 32
rs 9.232
c 0
b 0
f 0
cc 1
1
// eslint-disable-next-line import/no-unassigned-import
2
import "reflect-metadata";
3
import { Action, createExpressServer, UnauthorizedError, useContainer } from "routing-controllers";
4
import { getCustomRepository } from "typeorm";
5
import { AuthController } from "./controllers/AuthController";
6
import { isProduction, loadEnv } from "./utils/global";
7
import { CompressionMiddleware } from "./middlewares/CompressionMiddleware";
8
import { DatabaseMiddleware } from "./middlewares/DatabaseMiddleware";
9
import { SecurityHstsMiddleware } from "./middlewares/SecurityHstsMiddleware";
10
import { SecurityMiddleware } from "./middlewares/SecurityMiddleware";
11
import { SecurityNoCacheMiddleware } from "./middlewares/SecurityNoCacheMiddleware";
12
import { UserRepository } from "./repositories/UserRepository";
13
import { checkJwt, createJwt } from "./utils/jwt";
14
import { User } from "./entities/User";
15
16
async function findUser(action: Action): Promise<User | false> {
17
  const request = action.request;
18
  const response = action.response;
19
20
  const authorization = request.headers["authorization"];
21
  const apiKey = request.query.key || request.headers["x-api-key"];
22
23
  const repository = getCustomRepository(UserRepository);
24
25
  if (authorization) {
26
    try {
27
      const payload = checkJwt(authorization);
28
      const token = createJwt(payload);
29
      response.setHeader("token", `Bearer ${token}`);
30
      return await repository.findOne({ username: payload.username });
31
    } catch  {
32
      return false;
33
    }
34
  }
35
36
  if (apiKey) {
37
    return await repository.findOneByApiKey(apiKey);
38
  }
39
40
  return false;
41
}
42
43
export function createApp() {
44
  loadEnv();
45
46
  return createExpressServer({
47
    development: !isProduction(),
48
    validation: false,
49
    cors: {
50
      origin: true,
51
      allowedHeaders: [
52
        "accept",
53
        "content-type",
54
        "x-requested-with",
55
        "x-api-key",
56
      ],
57
    },
58
    controllers: [
59
      AuthController,
60
    ],
61
    middlewares: [
62
      CompressionMiddleware,
63
      DatabaseMiddleware,
64
      SecurityHstsMiddleware,
65
      SecurityMiddleware,
66
      SecurityNoCacheMiddleware,
67
    ],
68
    currentUserChecker: async (action: Action) => {
69
      return await findUser(action);
70
    },
71
    authorizationChecker: async (action: Action, roles: string[]) => {
72
      const user = await findUser(action);
73
      return user && !roles.length;
74
    },
75
  });
76
}
77