Passed
Push — master ( 0a16e3...f6f176 )
by Leandro
01:24
created

app.ts ➔ findUser   B

Complexity

Conditions 5

Size

Total Lines 30
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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