Skip to content

Commit 12485b4

Browse files
GufCabAugust AndersenAramAlsabtinlgbkd231
authored
Merge stage prior to release v1.1.0 (#145)
* Feature/IOT_16_MulticastBackend (#132) * Made CRUD operationer for multicast. Tested with frontend. * Made CRUD for multicast in backend plus connection to chirpStack. * Changed chirpstack applicationID since there will always only be one. * Split multicast in two entities so it's easier to expand later. Made a new entity called lorawanMulticastDefinition which will contain the informations about a lorawan multicast * made functionality so devices now will be added to chirpstack if they are a lorawan device. Also made the update functionality, so a device will be removed if it's not a part of the new multicast * Send message. Possible to get current message queue and to overwrite it * Made validation for service profile. Devices should only be added to multicast if they alle have same service profile. * PR changes * PR changes - fixed pagination for multicast * PR Changes * PR Changes * Pr changes Co-authored-by: August Andersen <[email protected]> * Db migrations (#133) * Made migrations. Now it's nessesary to add migrations when changes are made in db. The command - npm run typeorm migration:generate -- -n <migrationName> - will generate a migration file if changes are made compared to the db. When you launch the app, a migration:run command will be called. This will apply the newly migration. If you want to revert a migration, npm run typeorm migration:revert can be called. It will revert the latest migration. If you are in doubt which migrations has been called or not, you can write npm run typeorm migration:show. This will show you the pending/fulfilled migrations. * Since migrations are made in prestart, no need to check on dist. * PR Changes * PR changes Co-authored-by: August Andersen <[email protected]> * Migrations changes in ormconfig file to make migrations possible in test environment * Initial migration (#134) * Initial migration * Fix proper linting ignore of migrations * Changed ormconfig.ts to .js so dist folder is created correctly. Minor changes in package.json. Removed multicast from initialmigration and made a seperate migration with multicast. Co-authored-by: augusthjerrild <[email protected]> * Feature/1220 api key (#136) * Init api key auth with hardcoded keys * Added TODOs. Throw 401 if api key is invalid * Fix roles metadata not set on class controller * Fetch api keys and sort. Prepare for create and update * Api key fetch and create done * Cleanup api key flow. Remove update flow for now * Validate api key access * Works - typeerror when building * Fixed circular dependency error * Added API guard to relevant controllers * Fix indentation. Delete unused auth api key request Co-authored-by: Aram Al-Sabti <[email protected]> Co-authored-by: nlg <[email protected]> * Fix roles in controllers where it was set on the whole class (#139) * Edit API keys (#138) * Add option for editing API key * Fix API keys with admin not having write access * Edit API key PR * Clean up API key * CVE-2019-18413. Patch for potential SQL injections (#137) * CVE-2019-18413. Patch for potential SQL injections * Fix request 400 on get applications by permission * Spell organization with British English ("z") * Simplified migration names * Optimize chirpstack calls when fetching devices (#143) * FIWARE datatarget (#141) * Fiware DataTarget Support * Migration for Fiware Datatarget * Fixing incorrect log message * PR Fixes * Optimize bulk import and the load on chirpstack (#140) * Adjust eslint * Modify bulk import create to take batches. Update missing * Remove restriction on devices belonging to the same application * Optimize chirpstack calls. Init updatemany endpoint. * Implement updateMany and cleanup * Fix device model not set. Cleanup code. Add comments * Refactor iot device helpers * Make device model error code more specific * Added comment every time invalid devices are filtered * Fixed issue when creating new IoT device with no device model * Fixed Fiware datatarget headers declarations and corresponding unit tests (#144) Co-authored-by: August Andersen <[email protected]> Co-authored-by: Aram Al-Sabti <[email protected]> Co-authored-by: nlg <[email protected]> Co-authored-by: Bartek <[email protected]>
1 parent ba70c7f commit 12485b4

File tree

122 files changed

+3506
-389
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

122 files changed

+3506
-389
lines changed

.eslintignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ node_modules
44
dist
55
# don't lint nyc coverage output
66
coverage
7+
src/migration/
8+
.eslintrc.js

.eslintrc.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ module.exports = {
2323
"@typescript-eslint/no-unused-vars": "off",
2424
"@typescript-eslint/no-floating-promises": "warn",
2525
"max-lines-per-function": ["error", 80],
26-
"max-lines-per-function": ["warn", 40],
26+
"max-lines-per-function": ["warn", 55],
2727
},
2828
overrides: [
2929
{

ormconfig.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
module.exports = {
2+
"type": "postgres",
3+
"host": process.env.DATABASE_HOSTNAME || "host.docker.internal",
4+
"port": parseInt(process.env.DATABASE_PORT, 10) || 5433,
5+
"username": process.env.DATABASE_USERNAME || "os2iot",
6+
"password": process.env.DATABASE_PASSWORD || "toi2so",
7+
"database": "os2iot",
8+
"synchronize": false,
9+
"logging": false,
10+
"entities": ["src/entities/*.ts"],
11+
"migrations": ["src/migration/*.ts"],
12+
"cli": {
13+
"migrationsDir": "src/migration"
14+
}
15+
}

ormconfig.json

Lines changed: 0 additions & 11 deletions
This file was deleted.

package-lock.json

Lines changed: 44 additions & 34 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,13 @@
88
"scripts": {
99
"prebuild": "rimraf dist",
1010
"build": "nest build",
11+
"generate-migration": "npm run typeorm migration:generate -- -n",
1112
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
13+
"prestart": "npm run run-migrations",
14+
"prestart:debug": "npm run run-migrations",
15+
"prestart:dev": "npm run run-migrations",
16+
"prestart:prod": "npm run run-migrations",
17+
"run-migrations": "npm run typeorm migration:run",
1218
"start": "nest start",
1319
"start:dev": "nest start --watch",
1420
"start:debug": "nest start --debug --watch",
@@ -19,7 +25,7 @@
1925
"test:cov": "jest --coverage",
2026
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
2127
"test:e2e": "jest --config ./jest-e2e.js --detectOpenHandles --colors",
22-
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.json",
28+
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.js",
2329
"typeorm-e2e": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig-e2e.json"
2430
},
2531
"dependencies": {
@@ -30,7 +36,7 @@
3036
"@nestjs/passport": "^7.1.5",
3137
"@nestjs/platform-express": "^7.6.1",
3238
"@nestjs/schedule": "^0.4.1",
33-
"@nestjs/swagger": "^4.7.6",
39+
"@nestjs/swagger": "^4.8.2",
3440
"@nestjs/typeorm": "^7.1.5",
3541
"@types/bcryptjs": "^2.4.2",
3642
"@types/geojson": "^7946.0.7",
@@ -42,8 +48,8 @@
4248
"axios-cache-adapter": "^2.5.0",
4349
"bcryptjs": "^2.4.3",
4450
"bluebird": "^3.7.2",
45-
"class-transformer": "^0.3.1",
46-
"class-validator": "^0.12.2",
51+
"class-transformer": "^0.5.1",
52+
"class-validator": "^0.13.2",
4753
"compression": "^1.7.4",
4854
"cookie-parser": "^1.4.5",
4955
"kafkajs": "^1.15.0",
@@ -52,6 +58,7 @@
5258
"nestjs-pino": "^1.3.0",
5359
"njwt": "^1.0.0",
5460
"passport": "^0.4.1",
61+
"passport-headerapikey": "^1.2.2",
5562
"passport-jwt": "^4.0.0",
5663
"passport-local": "^1.0.0",
5764
"passport-saml": "^1.3.5",
@@ -78,6 +85,7 @@
7885
"@types/passport-jwt": "^3.0.3",
7986
"@types/passport-local": "^1.0.33",
8087
"@types/supertest": "^2.0.10",
88+
"@types/validator": "^13.7.1",
8189
"@typescript-eslint/eslint-plugin": "^4.10.0",
8290
"@typescript-eslint/parser": "^4.10.0",
8391
"eslint": "^7.15.0",

src/auth/api-key-auth.guard.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { Injectable } from "@nestjs/common";
2+
import { AuthGuard } from "@nestjs/passport";
3+
import { ApiKeyStrategyName } from "./constants";
4+
5+
@Injectable()
6+
export class ApiKeyAuthGuard extends AuthGuard(ApiKeyStrategyName) {}

src/auth/api-key.strategy.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { AuthenticatedUser } from "@dto/internal/authenticated-user";
2+
import { ErrorCodes } from "@enum/error-codes.enum";
3+
import { Injectable, UnauthorizedException } from "@nestjs/common";
4+
import { PassportStrategy } from "@nestjs/passport";
5+
import { AuthService } from "@services/user-management/auth.service";
6+
import { PermissionService } from "@services/user-management/permission.service";
7+
import { HeaderAPIKeyStrategy } from "passport-headerapikey";
8+
import { ApiKeyHeader, ApiKeyStrategyName, HeaderApiVerifiedCallback } from "./constants";
9+
10+
const passReqToCallback = false;
11+
12+
@Injectable()
13+
export class ApiKeyStrategy extends PassportStrategy(
14+
HeaderAPIKeyStrategy,
15+
ApiKeyStrategyName
16+
) {
17+
constructor(
18+
private authService: AuthService,
19+
private permissionService: PermissionService
20+
) {
21+
super(
22+
{
23+
header: ApiKeyHeader,
24+
prefix: "",
25+
},
26+
passReqToCallback
27+
);
28+
}
29+
30+
async validate(
31+
apiKey: string,
32+
_done: HeaderApiVerifiedCallback
33+
): Promise<AuthenticatedUser> {
34+
const apiKeyDb = await this.authService.validateApiKey(apiKey);
35+
if (!apiKeyDb) {
36+
throw new UnauthorizedException(ErrorCodes.ApiKeyAuthFailed);
37+
}
38+
39+
// Get the permissions and the UserID from the API Key instead of the user
40+
const permissions = await this.permissionService.findPermissionGroupedByLevelForApiKey(
41+
apiKeyDb.id
42+
);
43+
44+
// const permissions = dbApiKey.permissions as Permission[];
45+
const userId = apiKeyDb.systemUser.id;
46+
47+
// Set the permissions and the userId on the returned user
48+
const user: AuthenticatedUser = {
49+
userId,
50+
username: apiKeyDb.systemUser.name,
51+
permissions,
52+
};
53+
54+
return user;
55+
}
56+
}

src/auth/compose-auth.guard.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Injectable } from "@nestjs/common";
2+
import { AuthGuard } from "@nestjs/passport";
3+
import { ApiKeyStrategyName, JwtStrategyName } from "./constants";
4+
5+
@Injectable()
6+
/**
7+
* Let authentication go through a chain of strategies. The first to succeed, redirect, or error will halt the chain
8+
* If a strategy fails (not errors! Ex. JWT token wasn't valid), then authentication proceeds to the next strategy.
9+
* Source: https://docs.nestjs.com/security/authentication#extending-guards
10+
*/
11+
export class ComposeAuthGuard extends AuthGuard([JwtStrategyName, ApiKeyStrategyName]) {}

src/auth/constants.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { AuthenticatedUser } from "@dto/internal/authenticated-user";
2+
3+
export type HeaderApiVerifiedCallback = (
4+
err: Error | null,
5+
user?: AuthenticatedUser,
6+
info?: Record<string, unknown>
7+
) => void;
8+
9+
export const ApiKeyStrategyName = "api-key";
10+
export const ApiKeyHeader = "X-API-KEY";
11+
export const LocalStrategyName = "local";
12+
export const JwtStrategyName = "jwt";
13+
export const RolesMetaData = "roles";

src/auth/jwt-auth.guard.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Injectable } from "@nestjs/common";
22
import { AuthGuard } from "@nestjs/passport";
3+
import { JwtStrategyName } from "./constants";
34

45
@Injectable()
5-
export class JwtAuthGuard extends AuthGuard("jwt") {}
6+
export class JwtAuthGuard extends AuthGuard(JwtStrategyName) {}

src/auth/jwt.strategy.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
1+
import { AuthenticatedUser } from "@dto/internal/authenticated-user";
2+
import { JwtPayloadDto } from "@entities/dto/internal/jwt-payload.dto";
13
import { Injectable, Logger, UnauthorizedException } from "@nestjs/common";
24
import { ConfigService } from "@nestjs/config";
35
import { PassportStrategy } from "@nestjs/passport";
4-
import { ExtractJwt, Strategy } from "passport-jwt";
5-
6-
import { AuthenticatedUser } from "@dto/internal/authenticated-user";
7-
import { JwtPayloadDto } from "@entities/dto/internal/jwt-payload.dto";
86
import { PermissionService } from "@services/user-management/permission.service";
97
import { UserService } from "@services/user-management/user.service";
8+
import { ExtractJwt, Strategy } from "passport-jwt";
9+
import { JwtStrategyName } from "./constants";
1010

1111
@Injectable()
12-
export class JwtStrategy extends PassportStrategy(Strategy) {
12+
export class JwtStrategy extends PassportStrategy(Strategy, JwtStrategyName) {
1313
constructor(
1414
private permissionService: PermissionService,
1515
private userService: UserService,
1616
private configService: ConfigService
1717
) {
1818
super({
19+
// Configure the strategy to look for the JWT token in the Authorization header
1920
jwtFromRequest: ExtractJwt.fromExtractors([
2021
ExtractJwt.fromAuthHeaderAsBearerToken(),
2122
ExtractJwt.fromUrlQueryParameter("secret_token"),

src/auth/local-auth.guard.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Injectable } from "@nestjs/common";
22
import { AuthGuard } from "@nestjs/passport";
3+
import { LocalStrategyName } from "./constants";
34

45
@Injectable()
5-
export class LocalAuthGuard extends AuthGuard("local") {}
6+
export class LocalAuthGuard extends AuthGuard(LocalStrategyName) {}

0 commit comments

Comments
 (0)