Moved typescript backend into old_backend

This commit is contained in:
Mutzi 2022-08-26 09:42:33 +02:00
parent 520aeecb4e
commit d199ecae87
26 changed files with 69 additions and 7894 deletions

View File

@ -1,29 +0,0 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin', 'no-relative-import-paths'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'no-relative-import-paths/no-relative-import-paths': [
'error',
{ 'allowSameFolder': true, 'rootDir': 'src' }
]
},
};

422
.gitignore vendored
View File

@ -1,37 +1,58 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Created by https://www.toptal.com/developers/gitignore/api/clion
# Edit at https://www.toptal.com/developers/gitignore?templates=clion
### CLion ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Sensitive or high-churn files:
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle:
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# Mongo Explorer plugin:
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
## File-based project format:
# File-based project format
*.iws
## Plugin-specific files:
# IntelliJ
out/
@ -44,358 +65,53 @@ atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### VisualStudio template
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# Editor-based Rest Client
.idea/httpRequests
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
### CLion Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# NUNIT
*.VisualState.xml
TestResult.xml
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Benchmark Results
BenchmarkDotNet.Artifacts/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
coverage/
### macOS template
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
=======
# Local
.env
dist
files
sqlite.db
# End of https://www.toptal.com/developers/gitignore/api/clion

View File

@ -1,114 +0,0 @@
image: node:latest
stages:
- setup
- test
- build
- package
cache: &global_cache
paths:
- .yarn
- node_modules
- frontend/.yarn
- frontend/node_modules
policy: pull
before_script:
- yarn install --cache-folder .yarn --frozen-lockfile
- cd frontend
- yarn install --cache-folder .yarn --frozen-lockfile
- cd ..
.dto_artifacts_need: &dto_artifacts_need
job: test_build_dto
artifacts: true
test_build_dto:
stage: setup
cache:
<<: *global_cache
policy: pull-push
before_script: []
script:
- cd dto
- yarn install --frozen-lockfile
- yarn lint
- yarn build
- cd ..
- yarn install --cache-folder .yarn --frozen-lockfile
- yarn add ./dto
- cd frontend
- yarn install --cache-folder .yarn --frozen-lockfile
- yarn add ../dto
artifacts:
paths:
- dto/lib/
test_backend:
needs:
- *dto_artifacts_need
stage: test
script:
- yarn lint
test_frontend:
needs:
- *dto_artifacts_need
stage: test
script:
- cd frontend
- yarn lint
build_backend:
stage: build
needs:
- *dto_artifacts_need
- job: test_backend
artifacts: false
script:
- echo This has to work till I rewrite the backend
- false && echo
- yarn webpack
artifacts:
paths:
- dist/
expire_in: 1h
build_frontend:
stage: build
needs:
- *dto_artifacts_need
- job: test_frontend
artifacts: false
script:
- cd frontend
- yarn build
artifacts:
paths:
- frontend/dist/
expire_in: 1h
package_server:
stage: package
cache: []
before_script: []
needs:
- job: build_backend
artifacts: true
- job: build_frontend
artifacts: true
script:
- TMP=$(mktemp -d)
- mv dist/* "$TMP"
- mkdir "$TMP/frontend"
- mv frontend/dist/* "$TMP/frontend"
- rm -r *
- rm -r .* || true
- mv "$TMP/"* .
artifacts:
paths:
- package.json
- server.js
- frontend/

View File

@ -1,7 +0,0 @@
{
"tabWidth": 4,
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"endOfLine": "lf"
}

View File

@ -1,19 +0,0 @@
# Mutzi's fileserver
## Description
The most crackhead fileserver you will find on the market
## Installation
```bash
npm install
cd frontend && npm install
```
## Running the app
```bash
npm run start:dev
```
Run in parallel for building the frontend:
````bash
cd frontend && npm run serve
````

View File

@ -1,9 +0,0 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"monorepo": true,
"sourceRoot": "src",
"compilerOptions": {
"tsConfigPath": "tsconfig.json"
}
}

View File

@ -1,122 +0,0 @@
{
"name": "fileserver",
"private": true,
"version": "1.0.0",
"description": "Crackhead fileserver",
"license": "MIT",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"lint": "eslint \"src/**/*.ts\"",
"lint-fix": "eslint \"src/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"genapi": "ts-node tools/apigen.ts",
"updateDto": "cd dto && yarn build && cd .. && yarn add ./dto && cd frontend && yarn add ../dto",
"lint-fix-all": "yarn lint-fix && cd dto && yarn lint-fix && cd ../frontend && yarn lint --fix"
},
"dependencies": {
"@fastify/multipart": "^7.1.0",
"@fastify/static": "^6.5.0",
"@nestjs/common": "^9.0.8",
"@nestjs/core": "^9.0.8",
"@nestjs/jwt": "^9.0.0",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-fastify": "^9.0.8",
"@nestjs/serve-static": "^3.0.0",
"@nestjs/typeorm": "^9.0.0",
"argon2": "^0.28.7",
"axios": "^0.27.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"jsonwebtoken": "^8.5.1",
"nodemailer": "^6.7.8",
"notp": "^2.0.3",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"qrcode": "^1.5.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.5.6",
"sqlite3": "^5.0.11",
"thirty-two": "^1.0.2",
"typeorm": "^0.3.7"
},
"runtimeDependencies": [
"@fastify/multipart",
"@fastify/static",
"@nestjs/common",
"@nestjs/core",
"@nestjs/platform-fastify",
"@nestjs/serve-static",
"argon2",
"class-transformer",
"class-validator",
"reflect-metadata",
"rxjs",
"sqlite3",
"typeorm"
],
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.1",
"@nestjs/testing": "^9.0.8",
"@types/express": "^4.17.13",
"@types/jest": "^28.1.6",
"@types/jsonwebtoken": "^8.5.8",
"@types/node": "^18.6.5",
"@types/nodemailer": "^6.4.5",
"@types/notp": "^2.0.2",
"@types/passport-jwt": "^3.0.6",
"@types/passport-local": "^1.0.34",
"@types/qrcode": "^1.5.0",
"@types/supertest": "^2.0.12",
"@types/webpack": "^5.28.0",
"@types/webpack-node-externals": "^2.5.3",
"@typescript-eslint/eslint-plugin": "^5.33.0",
"@typescript-eslint/parser": "^5.33.0",
"@typescript-eslint/typescript-estree": "^5.33.0",
"copy-webpack-plugin": "^11.0.0",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-no-relative-import-paths": "^1.4.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^28.1.3",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"source-map-support": "^0.5.21",
"supertest": "^6.2.4",
"ts-jest": "^28.0.7",
"ts-loader": "^9.3.1",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.1.0",
"tsconfig-paths-webpack-plugin": "^4.0.0",
"typescript": "^4.7.4",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-node-externals": "^3.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -1,28 +0,0 @@
### Create account
POST http://127.0.0.1:8080/api/auth/signup
Content-Type: application/json
{"username": "root@mattv.de", "password": "123"}
### Wrong authenctication
POST http://127.0.0.1:8080/api/auth/login
Content-Type: application/json
{"username": "root@mattv.de", "password": "this is not correct"}
### Correct authentication
POST http://127.0.0.1:8080/api/auth/login
Content-Type: application/json
{"username": "root@mattv.de", "password": "123"}
> {% client.global.set("auth_token", response.body.jwt); %}
### Check if authenticated with admin perms
GET http://127.0.0.1:8080/test/hello2
Authorization: Bearer {{auth_token}}
### Refresh token
POST http://127.0.0.1:8080/api/auth/refresh
Authorization: Bearer {{auth_token}}

View File

@ -1,59 +0,0 @@
import { Controller, Get, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { INode, JWTToken, User } from './entities';
import FileSystemModule from './modules/filesystem';
import { JWTAuthGuard, Role, RoleGuard } from './authguards';
import AuthModule from './modules/auth';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { cwd } from 'process';
import { UserRole } from '../dto/';
declare const PROD: boolean | undefined;
@Controller('test')
class TestController {
@Role(UserRole.USER)
@Get('hello')
getHello(): string {
return 'UwU';
}
@Role(UserRole.ADMIN)
@Get('hello2')
getHelloAdmin(): string {
return 'UwU Admin';
}
}
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'sqlite.db',
synchronize: true,
entities: [User, INode, JWTToken]
}),
ServeStaticModule.forRoot({
rootPath:
typeof PROD !== 'undefined' && PROD
? join(cwd(), 'frontend')
: join(__dirname, '..', '..', 'frontend', 'dist'),
exclude: ['/api*']
}),
FileSystemModule,
AuthModule
],
controllers: [TestController],
providers: [
{
provide: 'APP_GUARD',
useClass: JWTAuthGuard
},
{
provide: 'APP_GUARD',
useClass: RoleGuard
}
]
})
export class AppModule {}

View File

@ -1,47 +0,0 @@
import {
CanActivate,
ExecutionContext,
Injectable,
SetMetadata
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { User } from './entities';
import { UserRole } from '../dto';
const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
@Injectable()
export class JWTAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(
IS_PUBLIC_KEY,
[context.getHandler(), context.getClass()]
);
if (isPublic) return true;
return super.canActivate(context);
}
}
const ROLE_KEY = 'role';
export const Role = (role: UserRole) => SetMetadata(ROLE_KEY, role);
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext) {
const requiredRole = this.reflector.getAllAndOverride<UserRole>(
ROLE_KEY,
[context.getHandler(), context.getClass()]
);
if (!requiredRole) return true;
const user: User = context.switchToHttp().getRequest().user;
return user.role >= requiredRole;
}
}

View File

@ -1,83 +0,0 @@
import {
BadRequestException,
Body,
Controller,
Get,
Post,
Request,
ValidationPipe
} from '@nestjs/common';
import { AuthService } from 'services/auth';
import { Requests, Responses, UserRole } from '../../dto';
import { Role } from 'authguards';
import { tfaTypes } from 'entities';
@Controller('api/admin')
export default class AdminController {
constructor(private authService: AuthService) {}
@Role(UserRole.ADMIN)
@Get('users')
async getUsers(): Promise<Responses.Admin.GetUsers> {
const users = await this.authService.getUsers();
const entries = users.map(
(user) =>
new Responses.Admin.GetUsersEntry(
user.id,
user.isGitlabUser,
user.name,
user.role,
this.authService.requiresTfa(user)
)
);
return new Responses.Admin.GetUsers(entries);
}
@Role(UserRole.ADMIN)
@Post('set_role')
async setRole(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.SetUserRole
): Promise<Responses.Admin.SetUserRole> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.setUserRole(user, data.role);
return new Responses.Admin.SetUserRole();
}
@Role(UserRole.ADMIN)
@Post('logout')
async logout(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.LogoutAll
): Promise<Responses.Admin.LogoutAllUser> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.revokeAll(user);
return new Responses.Admin.LogoutAllUser();
}
@Role(UserRole.ADMIN)
@Post('delete')
async delete(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.DeleteUser
): Promise<Responses.Admin.DeleteUser> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.deleteUser(user);
return new Responses.Admin.DeleteUser();
}
@Role(UserRole.ADMIN)
@Post('disable_2fa')
async disableTfa(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Admin.DisableTfa
): Promise<Responses.Admin.DisableTfa> {
const user = await this.authService.getUser(data.user);
if (!user) throw new BadRequestException('Invalid user');
await this.authService.setTfaType(user, tfaTypes.NONE);
return new Responses.Admin.DisableTfa();
}
}

View File

@ -1,150 +0,0 @@
import {
BadRequestException,
Body,
Controller,
Get,
HttpCode,
Post,
Query,
Redirect,
Request,
UnauthorizedException,
UseGuards,
ValidationPipe
} from '@nestjs/common';
import { AuthService } from 'services/auth';
import { AuthGuard } from '@nestjs/passport';
import { Public } from 'authguards';
import { Requests, Responses } from '../../dto';
import { tfaTypes } from 'entities';
import { toDataURL } from 'qrcode';
import * as base32 from 'thirty-two';
@Controller('api/auth')
export default class AuthController {
constructor(private authService: AuthService) {}
@Public()
@UseGuards(AuthGuard('local'))
@Post('login')
@HttpCode(200)
async login(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Auth.LoginRequest
): Promise<
Responses.Auth.LoginResponse | Responses.Auth.TfaRequiredResponse
> {
if (this.authService.requiresTfa(req.user)) {
if (!data.otp) {
if (req.user.tfaType == tfaTypes.EMAIL)
await this.authService.sendTfaMail(req.user);
return new Responses.Auth.TfaRequiredResponse();
}
if (!(await this.authService.verifyTfa(req.user, data.otp)))
throw new UnauthorizedException('Incorrect 2fa');
}
return new Responses.Auth.LoginResponse(
await this.authService.login(req, req.user)
);
}
@Post('2fa/disable')
async tfaDisable(
@Request() req
): Promise<Responses.Auth.RemoveTfaResponse> {
await this.authService.setTfaType(req.user, tfaTypes.NONE);
await this.authService.revokeAll(req.user);
return new Responses.Auth.RemoveTfaResponse();
}
@Post('2fa/complete')
async tfaMail(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Auth.TfaComplete
): Promise<Responses.Auth.TfaCompletedResponse> {
const type = data.mail ? tfaTypes.EMAIL : tfaTypes.TOTP;
if (!(await this.authService.verifyTfa(req.user, data.code, type))) {
throw new UnauthorizedException('Incorrect 2fa');
}
await this.authService.setTfaType(req.user, type);
await this.authService.revokeAll(req.user);
return new Responses.Auth.TfaCompletedResponse();
}
@Post('2fa/setup')
async setupTotp(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Auth.TfaSetup
): Promise<
| Responses.Auth.RequestTotpTfaResponse
| Responses.Auth.RequestEmailTfaResponse
> {
const secret = await this.authService.setupTfa(req.user);
if (data.mail) return new Responses.Auth.RequestEmailTfaResponse();
return new Responses.Auth.RequestTotpTfaResponse(
await toDataURL(
`otpauth://totp/MFileserver:${req.user.name}?secret=${base32
.encode(secret)
.toString()}&issuer=MFileserver`
),
base32.encode(secret).toString()
);
}
@Public()
@Post('signup')
async signup(
@Body(new ValidationPipe()) data: Requests.Auth.SignUpRequest
): Promise<Responses.Auth.SignupResponse> {
if ((await this.authService.findUser(data.username, false)) != null)
throw new BadRequestException('Username already taken');
await this.authService.signup(data.username, data.password);
return new Responses.Auth.SignupResponse();
}
@Post('refresh')
async refresh(@Request() req): Promise<Responses.Auth.RefreshResponse> {
const token = await this.authService.login(req, req.user);
await this.authService.revoke(req.token);
return await new Responses.Auth.RefreshResponse(token);
}
@Public()
@Redirect()
@Get('gitlab')
async gitlab(@Request() req) {
return {
url: this.authService.getGitlabAuthUrl(req)
};
}
@Public()
@Redirect()
@Get('gitlab_callback')
async gitlabCallback(@Request() req, @Query('code') code) {
const user = await this.authService.getGitlabUserFromCode(req, code);
const token = await this.authService.login(req, user);
return {
url: `/set_token?token=${token}`
};
}
@Post('change_password')
async changePassword(
@Request() req,
@Body(new ValidationPipe()) data: Requests.Auth.ChangePasswordRequest
): Promise<Responses.Auth.ChangePasswordResponse> {
await this.authService.changePassword(
req.user,
data.oldPassword,
data.newPassword
);
return new Responses.Auth.ChangePasswordResponse();
}
@Post('logout_all')
async logoutAll(@Request() req): Promise<Responses.Auth.LogoutAllResponse> {
await this.authService.revokeAll(req.user);
return new Responses.Auth.LogoutAllResponse();
}
}

View File

@ -1,121 +0,0 @@
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Post,
Request,
StreamableFile,
ValidationPipe
} from '@nestjs/common';
import { Responses, Requests, validateAsyncInline, UserRole } from '../../dto';
import FileSystemService from 'services/filesystem';
import { Role } from 'authguards';
@Controller('api/fs')
export default class FileSystemController {
constructor(private fsService: FileSystemService) {}
@Get('root')
@Role(UserRole.USER)
async getRoot(@Request() req): Promise<Responses.FS.GetRootResponse> {
return new Responses.FS.GetRootResponse(req.user.rootId);
}
@Get('node/:node')
@Role(UserRole.USER)
async getNode(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<Responses.FS.GetNodeResponse> {
const node = await this.fsService.getNodeAndValidate(nodeId, req.user);
const data = new Responses.FS.GetNodeResponse(
nodeId,
node.name,
node.isFile,
node.parentId
);
if (data.isFile) {
data.size = node.size;
} else {
data.children = (await node.children).map((child) => child.id);
}
return validateAsyncInline(data);
}
@Get('path/:node')
@Role(UserRole.USER)
async getPath(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<Responses.FS.GetPathResponse> {
return new Responses.FS.GetPathResponse(
await this.fsService.generatePath(
await this.fsService.getNodeAndValidate(nodeId, req.user)
)
);
}
@Post('createFolder')
@Role(UserRole.USER)
async createFolder(
@Request() req,
@Body(new ValidationPipe()) data: Requests.FS.CreateFolderRequest
): Promise<Responses.FS.CreateFolderResponse> {
const newChild = await this.fsService.create(
await this.fsService.getNodeAndValidate(data.parent, req.user),
data.name,
req.user,
false
);
return new Responses.FS.CreateFolderResponse(newChild.id);
}
@Post('createFile')
@Role(UserRole.USER)
async createFile(
@Request() req,
@Body(new ValidationPipe()) data: Requests.FS.CreateFileRequest
): Promise<Responses.FS.CreateFileResponse> {
const newChild = await this.fsService.create(
await this.fsService.getNodeAndValidate(data.parent, req.user),
data.name,
req.user,
true
);
return new Responses.FS.CreateFileResponse(newChild.id);
}
@Post('delete')
@Role(UserRole.USER)
async delete(
@Request() req,
@Body(new ValidationPipe()) data: Requests.FS.DeleteRequest
): Promise<Responses.FS.DeleteResponse> {
await this.fsService.delete(
await this.fsService.getNodeAndValidate(data.node, req.user)
);
return new Responses.FS.DeleteResponse();
}
@Post('upload/:node')
@Role(UserRole.USER)
async upload(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<Responses.FS.UploadFileResponse> {
await this.fsService.uploadFile(await req.file(), nodeId, req.user);
return new Responses.FS.UploadFileResponse();
}
@Post('download')
@Role(UserRole.USER)
async download(
@Request() req,
@Body('id', ParseIntPipe) id
): Promise<StreamableFile> {
return this.fsService.downloadFile(id, req.user);
}
}

View File

@ -1,27 +0,0 @@
import { Controller, Get, Post, Request } from '@nestjs/common';
import { AuthService } from 'services/auth';
import { Responses } from '../../dto';
@Controller('api/user')
export default class UserController {
constructor(private authService: AuthService) {}
@Get('info')
async getUserInfo(
@Request() req
): Promise<Responses.User.UserInfoResponse> {
return new Responses.User.UserInfoResponse(
req.user.name,
req.user.isGitlabUser,
this.authService.requiresTfa(req.user)
);
}
@Post('delete')
async deleteUser(
@Request() req
): Promise<Responses.User.DeleteUserResponse> {
await this.authService.deleteUser(req.user);
return new Responses.User.DeleteUserResponse();
}
}

View File

@ -1,95 +0,0 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
OneToMany,
OneToOne
} from 'typeorm';
import { UserRole } from '../dto';
export enum tfaTypes {
NONE = 0,
EMAIL = 1,
TOTP = 2
}
@Entity()
export class INode {
@PrimaryGeneratedColumn()
id: number;
@Column()
isFile: boolean;
@Column()
name: string;
@Column({ nullable: true })
size: number;
@Column({ nullable: true })
parentId: number;
@ManyToOne(() => INode, (node) => node.children)
parent: Promise<INode>;
@OneToMany(() => INode, (node) => node.parent)
children: Promise<INode[]>;
@Column({ nullable: true })
ownerId: number;
@ManyToOne(() => User)
owner: Promise<User>;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ default: false })
isGitlabUser: boolean;
@Column()
name: string;
@Column()
password: string;
@Column({
type: 'int',
default: UserRole.DISABLED,
transformer: {
from: (db: number): UserRole => db,
to: (role: UserRole): number => role
}
})
role: UserRole;
@Column({ nullable: true })
rootId: number;
@OneToOne(() => INode)
root: Promise<INode>;
@Column({
type: 'int',
default: tfaTypes.NONE,
transformer: {
from: (db: number): tfaTypes => db,
to: (type: tfaTypes): number => type
}
})
tfaType: tfaTypes;
@Column({ nullable: true })
tfaSecret: string;
@Column({ nullable: true })
gitlabAT: string;
@Column({ nullable: true })
gitlabRT: string;
}
@Entity()
export class JWTToken {
@PrimaryGeneratedColumn()
id: number;
@Column()
ownerId: number;
@Column({ nullable: true })
exp: number;
}

View File

@ -1,20 +0,0 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
FastifyAdapter,
NestFastifyApplication
} from '@nestjs/platform-fastify';
import fastifyMultipart from '@fastify/multipart';
import { existsSync, mkdirSync } from 'fs';
async function bootstrap() {
if (!existsSync('files')) mkdirSync('files');
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true })
);
await app.register(fastifyMultipart);
await app.listen(8080, '0.0.0.0');
}
bootstrap();

View File

@ -1,20 +0,0 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { INode, JWTToken, User } from 'entities';
import { AuthService, AuthLocalService, AuthJwtService } from 'services/auth';
import FileSystemService from 'services/filesystem';
import AuthController from 'controller/auth';
import UserController from 'controller/user';
import AdminController from 'controller/admin';
@Module({
imports: [TypeOrmModule.forFeature([User, INode, JWTToken])],
providers: [
AuthService,
AuthLocalService,
AuthJwtService,
FileSystemService
],
controllers: [AuthController, UserController, AdminController]
})
export default class AuthModule {}

View File

@ -1,12 +0,0 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { INode } from 'entities';
import FileSystemService from 'services/filesystem';
import FileSystemController from 'controller/filesystem';
@Module({
imports: [TypeOrmModule.forFeature([INode])],
providers: [FileSystemService],
controllers: [FileSystemController]
})
export default class FileSystemModule {}

View File

@ -1,121 +0,0 @@
import {
BadRequestException,
Injectable,
UnauthorizedException
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { JWTToken, User } from 'entities';
import { LessThanOrEqual, Repository } from 'typeorm';
import * as argon2 from 'argon2';
import FileSystemService from 'services/filesystem';
import * as jwt from 'jsonwebtoken';
import { UserRole } from '../../../dto';
export const jwtSecret = 'CUM';
export interface jwtPayload {
sub: number;
jti: number;
exp?: number;
iat?: number;
}
@Injectable()
export default class BaseAuthService {
constructor(
@InjectRepository(User)
protected userRepo: Repository<User>,
@InjectRepository(JWTToken)
protected tokenRepo: Repository<JWTToken>,
protected fsService: FileSystemService
) {}
getUsers(): Promise<User[]> {
return this.userRepo.find();
}
async getUser(userId: number): Promise<User | null> {
return this.userRepo.findOneBy({
id: userId
});
}
async findUser(username: string, gitlab: boolean): Promise<User | null> {
return this.userRepo.findOneBy({
name: username,
isGitlabUser: gitlab
});
}
async getToken(tokenId: number): Promise<JWTToken | null> {
return this.tokenRepo.findOneBy({
id: tokenId
});
}
async validateUser(username: string, pass: string): Promise<User | null> {
const user = await this.findUser(username, false);
if (!user)
throw new UnauthorizedException('Invalid username or password');
if (!(await argon2.verify(user.password, pass)))
throw new UnauthorizedException('Invalid username or password');
if (user.role == UserRole.DISABLED)
throw new UnauthorizedException('Account is disabled');
return user;
}
async cleanupTokens(): Promise<void> {
await this.tokenRepo.delete({
exp: LessThanOrEqual(Math.floor(Date.now() / 1000))
});
}
async login(req: Request, user: User) {
const token = new JWTToken();
token.ownerId = user.id;
const db_token = await this.tokenRepo.save(token);
const payload: jwtPayload = {
sub: user.id,
jti: db_token.id
};
const jwtToken = jwt.sign(payload, jwtSecret, {
mutatePayload: true,
expiresIn: '1d'
});
db_token.exp = payload.exp;
await this.tokenRepo.save(db_token);
return jwtToken;
}
async singupInternal(user: User): Promise<User> {
const root = await this.fsService.generateRoot(user);
user.rootId = root.id;
return this.userRepo.save(user);
}
async signup(username: string, password: string) {
if (await this.findUser(username, false))
throw new BadRequestException('User already exists');
const user = new User();
user.name = username;
user.password = await argon2.hash(password);
await this.singupInternal(await this.userRepo.save(user));
}
async revoke(token: JWTToken) {
await this.tokenRepo.delete({
id: token.id
});
}
async revokeAll(user: User) {
await this.tokenRepo.delete({
ownerId: user.id
});
}
async setUserRole(user: User, role: UserRole) {
user.role = role;
await this.userRepo.save(user);
}
}

View File

@ -1,160 +0,0 @@
import { User } from 'entities';
import { FastifyRequest } from 'fastify';
import axios from 'axios';
import * as argon2 from 'argon2';
import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
import TfaAuthService from './tfa';
import { UserRole } from '../../../dto';
const GITLAB_ID =
'98bcbad78cb1f880d1d1de62291d70a791251a7bea077bfe7df111ef3c115760';
const GITLAB_SECRET =
'7ee01d2b204aff3a05f9d028f004d169b6d381ec873e195f314b3935fa150959';
const GITLAB_URL = 'https://gitlab.mattv.de';
const GITLAB_API_URL = 'https://ssh.gitlab.mattv.de';
interface GitlabTokenResponse {
access_token: string;
token_type: string;
expires_in: number;
refresh_token: string;
created_at: number;
}
interface GitlabUserResponse {
username: string;
is_admin?: boolean;
}
export default class GitlabAuthService extends TfaAuthService {
async login(req: Request, user: User) {
if (user.isGitlabUser && !(await this.verifyGitlabUser(req, user))) {
await this.revokeAll(user);
throw new UnauthorizedException('Invalid gitlab token');
}
return super.login(req, user);
}
async singupGitlab(
info: GitlabUserResponse,
data: GitlabTokenResponse
): Promise<User> {
const user = new User();
user.name = info.username;
user.password = '';
user.isGitlabUser = true;
user.role = info.is_admin ? UserRole.ADMIN : UserRole.DISABLED;
return this.singupInternal(await this.setGitlabTokens(user, data));
}
async setGitlabTokens(
user: User,
data: GitlabTokenResponse
): Promise<User> {
user.gitlabAT = data.access_token;
user.gitlabRT = data.refresh_token;
return this.userRepo.save(user);
}
getGitlabRedirectUrl(req: Request): string {
const _req = req as unknown as FastifyRequest;
return `${_req.protocol}://${_req.hostname}/api/auth/gitlab_callback`;
}
getGitlabAuthUrl(req: Request): string {
const params = new URLSearchParams();
params.append('redirect_uri', this.getGitlabRedirectUrl(req));
params.append('response_type', 'code');
params.append('scope', 'read_user');
params.append('client_id', GITLAB_ID);
return `${GITLAB_URL}/oauth/authorize?${params.toString()}`;
}
async getGitlabUserFromCode(req: Request, code: string): Promise<User> {
const params = new URLSearchParams();
params.append('redirect_uri', this.getGitlabRedirectUrl(req));
params.append('client_id', GITLAB_ID);
params.append('client_secret', GITLAB_SECRET);
params.append('code', code);
params.append('grant_type', 'authorization_code');
const resp = await axios.post(
`${GITLAB_API_URL}/oauth/token?${params.toString()}`,
{}
);
const data: GitlabTokenResponse = resp.data;
const userInfoResp = await axios.get(`${GITLAB_API_URL}/api/v4/user`, {
headers: { Authorization: `Bearer ${data.access_token}` }
});
const userInfo: GitlabUserResponse = userInfoResp.data;
let user = await this.findUser(userInfo.username, true);
if (!user) user = await this.singupGitlab(userInfo, data);
else user = await this.setGitlabTokens(user, data);
return user;
}
async getGitlabUserInfo(
req: Request,
user: User
): Promise<GitlabUserResponse | null> {
try {
const userInfoResp = await axios.get(
`${GITLAB_API_URL}/api/v4/user`,
{
headers: { Authorization: `Bearer ${user.gitlabAT}` }
}
);
return userInfoResp.data;
} catch (e) {
return null;
}
}
async tryRefreshGitlabTokens(
req: Request,
user: User
): Promise<User | null> {
const params = new URLSearchParams();
params.append('redirect_uri', this.getGitlabRedirectUrl(req));
params.append('client_id', GITLAB_ID);
params.append('client_secret', GITLAB_SECRET);
params.append('refresh_token', user.gitlabRT);
params.append('grant_type', 'refresh_token');
try {
const resp = await axios.post(
`${GITLAB_API_URL}/oauth/token?${params.toString()}`,
{}
);
const data: GitlabTokenResponse = resp.data;
return this.setGitlabTokens(user, data);
} catch (e) {
return null;
}
}
async verifyGitlabUser(req: Request, user: User): Promise<boolean> {
let info = await this.getGitlabUserInfo(req, user);
if (!info) {
user = await this.tryRefreshGitlabTokens(req, user);
if (!user) return false;
info = await this.getGitlabUserInfo(req, user);
}
return info && info.username == user.name;
}
async deleteUser(user: User): Promise<void> {
await this.revokeAll(user);
await this.fsService.delete(await user.root, true);
await this.userRepo.remove(user);
}
async changePassword(
user: User,
oldPW: string,
newPw: string
): Promise<void> {
if (!(await argon2.verify(user.password, oldPW)))
throw new ForbiddenException('Old password is wrong');
user.password = await argon2.hash(newPw);
await this.revokeAll(await this.userRepo.save(user));
}
}

View File

@ -1,2 +0,0 @@
export { default as AuthService } from './gitlab';
export * from './strategies';

View File

@ -1,60 +0,0 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { ExtractJwt, Strategy as JWTStrategy } from 'passport-jwt';
import AuthService from './gitlab';
import { jwtPayload, jwtSecret } from './base';
@Injectable()
export class AuthLocalService extends PassportStrategy(LocalStrategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, pass: string) {
const user = await this.authService.validateUser(username, pass);
if (!user)
throw new UnauthorizedException('Invalid username or password');
return user;
}
}
@Injectable()
export class AuthJwtService extends PassportStrategy(JWTStrategy) {
constructor(private authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
ExtractJwt.fromBodyField('jwtToken')
]),
ignoreExpiration: false,
passReqToCallback: true,
secretOrKey: jwtSecret
});
}
async validate(req: Request, payload: jwtPayload) {
await this.authService.cleanupTokens();
const token = await this.authService.getToken(payload.jti);
if (!token)
throw new UnauthorizedException(
'Invalid token, please log in again'
);
const user = await this.authService.getUser(token.ownerId);
if (!user || user.id != payload.sub)
throw new UnauthorizedException(
'Invalid token, please log in again'
);
if (
user.isGitlabUser &&
!(await this.authService.verifyGitlabUser(req, user))
) {
await this.authService.revokeAll(user);
throw new UnauthorizedException('Invalid gitlab token');
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
req.token = token;
return user;
}
}

View File

@ -1,74 +0,0 @@
import { tfaTypes, User } from 'entities';
import { BadRequestException } from '@nestjs/common';
import BaseAuthService from './base';
import { randomBytes } from 'crypto';
import * as notp from 'notp';
import { createTransport } from 'nodemailer';
const mailAccount = createTransport({
host: 'mail.mattv.de',
port: 587,
secure: false,
auth: {
user: 'no-reply@mattv.de',
pass: 'noreplyLONGPASS123'
}
});
export default class TfaAuthService extends BaseAuthService {
generateTfaSecret(): string {
const set =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!@#$%^&*()<>?/[]{},.:;';
return randomBytes(32)
.map((b) =>
set.charCodeAt(Math.floor((b / 255.0) * (set.length - 1)))
)
.toString();
}
requiresTfa(user: User): boolean {
return user.tfaType != tfaTypes.NONE;
}
async verifyTfa(
user: User,
token: string,
type?: tfaTypes
): Promise<boolean> {
if (!type) type = user.tfaType;
const delta = notp.totp.verify(token, user.tfaSecret, {
window: 10
});
return (
delta &&
(type == tfaTypes.EMAIL ? delta.delta <= 0 : delta.delta == 0)
);
}
async sendTfaMail(user: User) {
await mailAccount.sendMail({
from: 'fileserver@mattv.de',
to: user.name,
subject: 'Fileserver - EMail 2fa code',
text: `Your code is: ${notp.totp.gen(
user.tfaSecret
)}\nIt is valid for 5 Minutes`
});
}
async setupTfa(user: User): Promise<string> {
if (user.tfaType != tfaTypes.NONE)
throw new BadRequestException(
'2 Factor authentication is already setup'
);
const secret = this.generateTfaSecret();
user.tfaSecret = secret;
await this.userRepo.save(user);
return secret;
}
async setTfaType(user: User, type: tfaTypes) {
user.tfaType = type;
await this.userRepo.save(user);
}
}

View File

@ -1,129 +0,0 @@
import {
BadRequestException,
Injectable,
NotImplementedException,
StreamableFile,
UnauthorizedException
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { INode, User } from 'entities';
import { Repository } from 'typeorm';
import { Multipart } from '@fastify/multipart';
import { pipeline } from 'stream/promises';
import { createReadStream, createWriteStream, statSync, unlink } from 'fs';
import { Writable } from 'stream';
@Injectable()
export default class FileSystemService {
constructor(
@InjectRepository(INode)
private inodeRepo: Repository<INode>
) {}
async generateRoot(user: User): Promise<INode> {
const node = new INode();
node.isFile = false;
node.name = '';
node.owner = Promise.resolve(user);
return await this.inodeRepo.save(node);
}
async getNode(nodeId: number): Promise<INode> {
return await this.inodeRepo.findOneBy({
id: nodeId
});
}
async getNodeAndValidate(node_id: number, user: User): Promise<INode> {
const node = await this.getNode(node_id);
if (node == null) throw new BadRequestException();
if (node.ownerId != user.id) throw new UnauthorizedException();
return node;
}
async generatePath(node: INode): Promise<string> {
if (node.parentId == null) return '/';
return (
(await this.generatePath(await node.parent)).slice(0, -1) +
'/' +
node.name +
(node.isFile ? '' : '/')
);
}
async delete(node: INode, force = false): Promise<void> {
if (node.parentId == null || force)
throw new BadRequestException("Can't delete root");
if (!node.isFile)
await Promise.all(
(await node.children).map((child) => this.delete(child, force))
);
else
unlink(`files/${node.id}`, (err) => {
if (err) console.error(`Error while deleting ${node.id}`, err);
});
await this.inodeRepo.remove(node);
}
async create(
parent: INode,
full_name: string,
owner: User,
file: boolean
): Promise<INode> {
const name = full_name.trim();
if (name == '') throw new BadRequestException("Name can't be empty");
if (name == '.' || name == '..')
throw new BadRequestException('Invalid name');
if (parent.isFile)
throw new BadRequestException("Can't create file/folder in file");
if (
await this.inodeRepo.findOneBy({
parentId: parent.id,
name: name
})
)
throw new BadRequestException('File/Folder already exists');
const node = new INode();
node.isFile = file;
node.name = name;
node.owner = Promise.resolve(owner);
node.parent = Promise.resolve(parent);
return await this.inodeRepo.save(node);
}
async uploadFile(file: Multipart, nodeId: number, user: User) {
try {
const node = await this.getNodeAndValidate(nodeId, user);
await pipeline(file.file, createWriteStream(`files/${node.id}`));
const stats = statSync(`files/${node.id}`);
node.size = stats.size;
await this.inodeRepo.save(node);
} catch (e) {
await pipeline(
file.file,
new Writable({
write(
chunk: any,
encoding: BufferEncoding,
callback: (error?: Error | null) => void
) {
setImmediate(callback);
}
})
);
}
}
async downloadFile(id: number, user: User): Promise<StreamableFile> {
const node = await this.getNodeAndValidate(id, user);
if (!node.isFile) throw new NotImplementedException();
const stats = statSync(`files/${node.id}`);
return new StreamableFile(createReadStream(`files/${node.id}`), {
disposition: `attachment; filename="${node.name}"`,
length: stats.size
});
}
}

View File

@ -1,19 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./src",
"incremental": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"strictPropertyInitialization": false
},
"exclude": ["node_modules", "dist", "test", "**/*spec.ts", "frontend"]
}

6014
yarn.lock

File diff suppressed because it is too large Load Diff