Initial commit

This commit is contained in:
Mutzi 2022-08-17 21:59:51 +02:00
commit cc6feb3171
48 changed files with 42841 additions and 0 deletions

25
.eslintrc.js Normal file
View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
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',
},
};

401
.gitignore vendored Normal file
View File

@ -0,0 +1,401 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# 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
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# 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
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_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
# 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

7
.prettierrc Normal file
View File

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

19
README.md Normal file
View File

@ -0,0 +1,19 @@
# 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
````

72
dto/index.ts Normal file
View File

@ -0,0 +1,72 @@
//
// Responses
//
export interface BaseResponse {
statusCode: number;
}
export interface ErrorResponse extends BaseResponse {
statusCode: 400 | 401 | 403;
message?: string;
}
export type RefreshResponse = LoginResponse;
export interface LoginResponse extends BaseResponse {
statusCode: 200;
jwt: string;
}
export interface GetRootResponse extends BaseResponse {
statusCode: 200;
rootId: number;
}
export interface GetNodeResponse extends BaseResponse {
statusCode: 200;
id: number;
name: string;
isFile: boolean;
parent: number | null;
children?: number[];
size?: number;
}
export interface GetPathResponse extends BaseResponse {
statusCode: 200;
path: string;
}
export type CreateFileResponse = CreateFolderResponse;
export interface CreateFolderResponse extends BaseResponse {
statusCode: 200;
id: number;
}
export type UploadFileResponse = DeleteResponse;
export interface DeleteResponse extends BaseResponse {
statusCode: 200;
}
//
// Requests
//
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface BaseRequest {}
export type AuthSignUpRequest = AuthLoginRequest;
export interface AuthLoginRequest extends BaseRequest {
username: string;
password: string;
}
export type CreateFileRequest = CreateFolderRequest;
export interface CreateFolderRequest extends BaseRequest {
parent: number;
name: string;
}
export interface DeleteRequest extends BaseRequest {
node: number;
}

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

24
frontend/README.md Normal file
View File

@ -0,0 +1,24 @@
# frontend
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Lints and fixes files
```
npm run lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

3
frontend/babel.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
presets: ['@vue/cli-plugin-babel/preset']
};

21588
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

62
frontend/package.json Normal file
View File

@ -0,0 +1,62 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service build --watch",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.27.2",
"core-js": "^3.8.3",
"filesize": "^9.0.11",
"jwt-decode": "^3.1.2",
"naive-ui": "^2.32.1",
"stream-browserify": "^3.0.0",
"util": "^0.12.4",
"vue": "^3.2.13",
"vue-router": "^4.0.3"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-typescript": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/eslint-config-typescript": "^9.1.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-vue": "^8.0.3",
"prettier": "^2.4.1",
"sass": "^1.32.7",
"sass-loader": "^12.0.0",
"typescript": "~4.5.5",
"vfonts": "^0.0.3"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 2020
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!--suppress HtmlUnknownTarget -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

66
frontend/src/App.vue Normal file
View File

@ -0,0 +1,66 @@
<script setup async lang="ts">
import { provide, ref } from 'vue';
import { useRouter } from 'vue-router';
import { refresh_token, TokenInjectType, isErrorResponse } from '@/api';
const router = useRouter();
const jwt = ref<string | null>(null);
function setToken(token: string) {
jwt.value = token;
localStorage.setItem('token', token);
}
function logout() {
jwt.value = null;
localStorage.removeItem('token');
router.push({ name: 'login' });
}
jwt.value = localStorage.getItem('token');
if (jwt.value == null) await router.push({ name: 'login' });
else {
const new_token = await refresh_token(jwt.value ?? '');
if (isErrorResponse(new_token)) logout();
else setToken(new_token.jwt);
}
provide<TokenInjectType>('jwt', {
jwt,
setToken,
logout
});
</script>
<template>
<nav>
<router-link to="/login" v-if="jwt != null" @click="logout()">
Logout
</router-link>
</nav>
<router-view />
</template>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>

View File

@ -0,0 +1,12 @@
<script setup lang="ts">
import App from './App';
</script>
<template>
<Suspense>
<App></App>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</template>

220
frontend/src/api.ts Normal file
View File

@ -0,0 +1,220 @@
import axios from 'axios';
import {
AuthLoginRequest,
AuthSignUpRequest,
BaseRequest,
BaseResponse,
CreateFileRequest,
CreateFileResponse,
CreateFolderRequest,
CreateFolderResponse,
DeleteRequest,
DeleteResponse,
ErrorResponse,
GetNodeResponse,
GetPathResponse,
GetRootResponse,
LoginResponse,
RefreshResponse,
UploadFileResponse
} from '../../dto';
import jwtDecode, { JwtPayload } from 'jwt-decode';
import { Ref, UnwrapRef } from 'vue';
export * from '../../dto';
const post = <T extends BaseRequest>(url: string, data: T) =>
axios
.post(url, data, {
headers: { 'Content-type': 'application/json' }
})
.then((res) => res.data)
.catch((err) => err.response.data);
const post_token = <T extends BaseRequest>(
url: string,
data: T,
token: string
) =>
axios
.post(url, data, {
headers: {
Authorization: 'Bearer ' + token,
'Content-type': 'application/json'
}
})
.then((res) => res.data)
.catch((err) => err.response.data);
const post_token_form = (
url: string,
data: FormData,
token: string,
onProgress: (progressEvent: ProgressEvent) => void
) =>
axios
.post(url, data, {
headers: {
Authorization: 'Bearer ' + token,
'Content-type': 'multipart/form-data'
},
onUploadProgress: onProgress
})
.then((res) => res.data)
.catch((err) => err.response.data);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const get = (url: string) =>
axios
.get(url)
.then((res) => res.data)
.catch((err) => err.response.data);
const get_token = (url: string, token: string) =>
axios
.get(url, {
headers: { Authorization: 'Bearer ' + token }
})
.then((res) => res.data)
.catch((err) => err.response.data);
//
// Api Requests
//
export const auth_login = (
username: string,
password: string
): Promise<LoginResponse | ErrorResponse> =>
post<AuthLoginRequest>('/api/auth/login', {
username: username,
password: password
});
export const auth_signup = (
username: string,
password: string
): Promise<LoginResponse | ErrorResponse> =>
post<AuthSignUpRequest>('/api/auth/signup', {
username: username,
password: password
});
export const get_root = (
token: string
): Promise<GetRootResponse | ErrorResponse> => get_token('/api/fs/root', token);
export const get_node = (
token: string,
node: number
): Promise<GetNodeResponse | ErrorResponse> =>
get_token(`/api/fs/node/${node}`, token);
export const get_path = (
token: string,
node: number
): Promise<GetPathResponse | ErrorResponse> =>
get_token(`/api/fs/path/${node}`, token);
export const create_folder = (
token: string,
parent: number,
name: string
): Promise<CreateFolderResponse | ErrorResponse> =>
post_token<CreateFolderRequest>(
'/api/fs/createFolder',
{
parent: parent,
name: name
},
token
);
export const create_file = (
token: string,
parent: number,
name: string
): Promise<CreateFileResponse | ErrorResponse> =>
post_token<CreateFileRequest>(
'/api/fs/createFile',
{
parent: parent,
name: name
},
token
);
export const delete_node = (
token: string,
node: number
): Promise<DeleteResponse | ErrorResponse> =>
post_token<DeleteRequest>(
'/api/fs/delete',
{
node: node
},
token
);
export const upload_file = async (
token: string,
parent: number,
file: File,
onProgress: (progressEvent: ProgressEvent) => void
): Promise<UploadFileResponse | ErrorResponse> => {
const node = await create_file(token, parent, file.name);
if (isErrorResponse(node)) return node;
const form = new FormData();
form.set('file', file);
return post_token_form(
`/api/fs/upload/${node.id}`,
form,
token,
onProgress
);
};
export function download_file(token: string, id: number) {
const form = document.createElement('form');
form.method = 'post';
form.target = '_blank';
form.action = '/api/fs/download';
form.innerHTML = `<input type="hidden" name="jwtToken" value="${token}"><input type="hidden" name="id" value="${id}">`;
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
export const refresh_token = (
token: string
): Promise<RefreshResponse | ErrorResponse> =>
post_token('/api/auth/refresh', '', token);
//
// Utilities
//
export async function check_token(
token: TokenInjectType
): Promise<string | void> {
if (!token.jwt.value) return token.logout();
const payload = jwtDecode<JwtPayload>(token.jwt.value);
if (!payload) return token.logout();
// Expires in more than 60 Minute
if (payload.exp && payload.exp > Math.floor(Date.now() / 1000 + 60 * 60))
return token.jwt.value;
const new_token = await refresh_token(token.jwt.value);
if (isErrorResponse(new_token)) return token.logout();
token.setToken(new_token.jwt);
return new_token.jwt;
}
export const isErrorResponse = (res: BaseResponse): res is ErrorResponse =>
res.statusCode != 200;
export type TokenInjectType = {
jwt: Ref<UnwrapRef<string | null>>;
setToken: (token: string) => void;
logout: () => void;
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@ -0,0 +1,46 @@
<script setup lang="ts">
import { defineEmits, defineProps, inject } from 'vue';
import {
check_token,
delete_node,
download_file,
GetNodeResponse,
TokenInjectType
} from '@/api';
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
const props = defineProps<{
node: GetNodeResponse;
}>();
const emit = defineEmits<{
(e: 'reloadNode'): void;
}>();
async function del() {
const token = await check_token(jwt);
if (!token) return;
await delete_node(token, props.node.id);
emit('reloadNode');
}
async function download() {
const token = await check_token(jwt);
if (!token) return;
download_file(token, props.node.id);
}
</script>
<template>
<td>
<router-link :to="'/fs/' + props.node.id">{{ node.name }}</router-link>
</td>
<td>
<a href="#" @click="download()" v-if="props.node.isFile">Download</a>
</td>
<td>
<a href="#" @click="del()" v-if="props.node.name !== '..'">delete</a>
</td>
</template>
<style scoped></style>

View File

@ -0,0 +1,111 @@
<script setup lang="ts">
import { defineEmits, defineProps, inject, reactive, ref, watch } from 'vue';
import {
GetNodeResponse,
create_folder,
get_node,
check_token,
TokenInjectType
} from '@/api';
import DirEntry from '@/components/FSView/DirEntry.vue';
import UploadFileDialog from '@/components/UploadDialog/UploadFileDialog.vue';
import { NModal } from 'naive-ui';
const props = defineProps<{
node: GetNodeResponse;
}>();
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
const emit = defineEmits<{
(e: 'reloadNode'): void;
(e: 'gotoRoot'): void;
}>();
const fileInput = ref<HTMLInputElement>();
const uploadDialog = ref();
const uploadDialogShow = ref(false);
const new_folder_name = ref('');
const files = ref<File[]>([]);
const nodes = ref<GetNodeResponse[]>([]);
const hasParent = ref(false);
const parentNode = reactive<GetNodeResponse>({
id: 0,
statusCode: 200,
isFile: false,
parent: null,
name: '..'
});
watch(
() => props.node,
async (to) => {
parentNode.id = to.parent ?? 0;
hasParent.value = to.parent != null;
nodes.value = [];
const token = await check_token(jwt);
if (!token) return;
await Promise.all(
to.children?.map(async (child) => {
nodes.value.push(
(await get_node(token, child)) as GetNodeResponse
);
}) ?? []
);
},
{ immediate: true }
);
async function newFolder() {
const token = await check_token(jwt);
if (!token) return;
await create_folder(token, props.node.id, new_folder_name.value);
emit('reloadNode');
}
async function uploadFiles() {
files.value = Array.from(fileInput.value?.files ?? []);
if (files.value.length == 0) return;
uploadDialogShow.value = true;
}
async function uploadFilesDialogOpen() {
await uploadDialog.value?.startUpload(props.node.id);
uploadDialogShow.value = false;
if (fileInput.value) fileInput.value.value = '';
emit('reloadNode');
}
</script>
<template>
<div>
<input
type="text"
placeholder="Folder name"
v-model="new_folder_name"
/>
<a href="#" @click="newFolder()">create folder</a>
</div>
<div>
<input type="file" ref="fileInput" multiple />
<a href="#" @click="uploadFiles()">upload files</a>
</div>
<table>
<tr v-if="hasParent">
<DirEntry :node="parentNode" @reloadNode="emit('reloadNode')" />
</tr>
<tr v-for="n in nodes" :key="n.id">
<DirEntry :node="n" @reloadNode="emit('reloadNode')" />
</tr>
</table>
<n-modal
v-model:show="uploadDialogShow"
:close-on-esc="false"
:mask-closable="false"
:on-after-enter="uploadFilesDialogOpen"
>
<UploadFileDialog ref="uploadDialog" :files="files" />
</n-modal>
</template>
<style scoped></style>

View File

@ -0,0 +1,44 @@
<script setup lang="ts">
import { defineProps, inject } from 'vue';
import {
check_token,
delete_node,
download_file,
GetNodeResponse,
TokenInjectType
} from '@/api';
const props = defineProps<{
node: GetNodeResponse;
}>();
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
async function del() {
const token = await check_token(jwt);
if (!token) return;
await delete_node(token, props.node.id);
}
async function download() {
const token = await check_token(jwt);
if (!token) return;
download_file(token, props.node.id);
}
</script>
<template>
<div>
<router-link :to="'/fs/' + props.node.parent ?? 0">..</router-link>
</div>
<div>
<a href="#" @click="download()" v-if="props.node.isFile">Download</a>
</div>
<div>
<router-link :to="'/fs/' + props.node.parent ?? 0" @click="del()">
delete
</router-link>
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,156 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this
project,<br />
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener"
>vue-cli documentation</a
>.
</p>
<h3>Installed CLI Plugins</h3>
<ul>
<li>
<a
href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel"
target="_blank"
rel="noopener"
>babel</a
>
</li>
<li>
<a
href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-router"
target="_blank"
rel="noopener"
>router</a
>
</li>
<li>
<a
href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-vuex"
target="_blank"
rel="noopener"
>vuex</a
>
</li>
<li>
<a
href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint"
target="_blank"
rel="noopener"
>eslint</a
>
</li>
<li>
<a
href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-typescript"
target="_blank"
rel="noopener"
>typescript</a
>
</li>
</ul>
<h3>Essential Links</h3>
<ul>
<li>
<a href="https://vuejs.org" target="_blank" rel="noopener"
>Core Docs</a
>
</li>
<li>
<a href="https://forum.vuejs.org" target="_blank" rel="noopener"
>Forum</a
>
</li>
<li>
<a href="https://chat.vuejs.org" target="_blank" rel="noopener"
>Community Chat</a
>
</li>
<li>
<a
href="https://twitter.com/vuejs"
target="_blank"
rel="noopener"
>Twitter</a
>
</li>
<li>
<a href="https://news.vuejs.org" target="_blank" rel="noopener"
>News</a
>
</li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li>
<a
href="https://router.vuejs.org"
target="_blank"
rel="noopener"
>vue-router</a
>
</li>
<li>
<a href="https://vuex.vuejs.org" target="_blank" rel="noopener"
>vuex</a
>
</li>
<li>
<a
href="https://github.com/vuejs/vue-devtools#vue-devtools"
target="_blank"
rel="noopener"
>vue-devtools</a
>
</li>
<li>
<a
href="https://vue-loader.vuejs.org"
target="_blank"
rel="noopener"
>vue-loader</a
>
</li>
<li>
<a
href="https://github.com/vuejs/awesome-vue"
target="_blank"
rel="noopener"
>awesome-vue</a
>
</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String
}
});
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

View File

@ -0,0 +1,51 @@
<script setup lang="ts">
import { defineProps, defineExpose, ref } from 'vue';
import { isErrorResponse, upload_file } from '@/api';
import { NProgress } from 'naive-ui';
import filesize from 'filesize';
const props = defineProps<{
file: File;
}>();
const progress = ref(0);
const percentage = ref(0);
const err = ref('');
const status = ref('info');
async function startUpload(parent: number, token: string) {
const resp = await upload_file(token, parent, props.file, (e) => {
progress.value = e.loaded;
percentage.value = (e.loaded / e.total) * 100;
});
percentage.value = 100;
if (isErrorResponse(resp)) {
err.value = resp.message ?? 'Error';
status.value = 'error';
} else status.value = 'success';
}
defineExpose({
startUpload
});
</script>
<template>
<div v-if="percentage < 100">
{{ file.name }} - {{ filesize(progress) }} / {{ filesize(file.size) }} -
{{ Math.floor(percentage * 1000) / 1000 }}%
</div>
<div v-else-if="err !== ''">{{ file.name }} - Error: {{ err }}</div>
<div v-else>{{ file.name }} - Completed</div>
<n-progress
type="line"
:percentage="percentage"
:height="20"
:status="status"
border-radius="10px 0"
fill-border-radius="10px 0"
:show-indicator="false"
/>
</template>
<style scoped></style>

View File

@ -0,0 +1,48 @@
<script setup lang="ts">
import { defineProps, defineExpose, ref, inject } from 'vue';
import { check_token, TokenInjectType } from '@/api';
import UploadEntry from '@/components/UploadDialog/UploadEntry.vue';
import { NCard } from 'naive-ui';
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
const entries = ref<typeof UploadEntry[]>([]);
const done = ref(false);
let canCloseResolve = null;
const canClose = new Promise((r) => (canCloseResolve = r));
async function startUpload(parent: number) {
const token = await check_token(jwt);
if (!token) return;
await Promise.all(
entries.value.map((entry) => entry.startUpload(parent, token))
);
done.value = true;
await canClose;
}
defineExpose({
startUpload
});
defineProps<{
files: File[];
}>();
</script>
<template>
<n-card title="Upload Files">
<div>
<UploadEntry
v-for="f in files"
:key="f.name"
ref="entries"
:file="f"
/>
</div>
<div>
<button v-if="done" @click="canCloseResolve()">Close</button>
</div>
</n-card>
</template>
<style scoped></style>

8
frontend/src/main.ts Normal file
View File

@ -0,0 +1,8 @@
import { createApp } from 'vue';
import router from './router';
import AppAsyncWrapper from './AppAsyncWrapper.vue';
const app = createApp(AppAsyncWrapper);
app.use(router);
app.config.unwrapInjectedRef = true;
app.mount('#app');

View File

@ -0,0 +1,34 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import LoginView from '@/views/LoginView.vue';
import HomeView from '@/views/HomeView.vue';
import AboutView from '@/views/AboutView.vue';
import FSView from '@/views/FSView.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
},
{
path: '/login',
name: 'login',
component: LoginView
},
{
path: '/fs/:node_id',
name: 'fs',
component: FSView
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;

6
frontend/src/shims-vue.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
/* eslint-disable */
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

View File

@ -0,0 +1,5 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>

View File

@ -0,0 +1,72 @@
<script setup lang="ts">
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router';
import { inject, onBeforeMount, ref } from 'vue';
import {
check_token,
get_node,
get_path,
get_root,
GetNodeResponse,
isErrorResponse,
TokenInjectType
} from '@/api';
import DirViewer from '@/components/FSView/DirViewer.vue';
import FileViewer from '@/components/FSView/FileViewer.vue';
const router = useRouter();
const route = useRoute();
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
const path = ref('');
const node = ref<GetNodeResponse | null>(null);
async function fetch_node(node_id: number) {
const token = await check_token(jwt);
if (!token) return;
let [p, n] = [
await get_path(token, node_id),
await get_node(token, node_id)
];
if (isErrorResponse(p)) return gotoRoot();
if (isErrorResponse(n)) return gotoRoot();
[path.value, node.value] = [p.path, n];
}
onBeforeRouteUpdate(async (to) => {
await fetch_node(Number(to.params.node_id));
});
async function reloadNode() {
await fetch_node(Number(route.params.node_id));
}
onBeforeMount(async () => {
await reloadNode();
});
async function gotoRoot() {
const token = await check_token(jwt);
if (!token) return;
const rootRes = await get_root(token);
if (isErrorResponse(rootRes)) return jwt.logout();
const root = rootRes.rootId;
await router.replace({
name: 'fs',
params: { node_id: root }
});
}
</script>
<template>
<div v-if="node">
<div>Path: {{ path }}</div>
<DirViewer
v-if="!node.isFile"
:node="node"
@reloadNode="reloadNode"
@gotoRoot="gotoRoot"
/>
<FileViewer v-else :node="node" />
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,28 @@
<template><p></p></template>
<script setup lang="ts">
import { onBeforeRouteUpdate, useRouter } from 'vue-router';
import { inject, onBeforeMount } from 'vue';
import { check_token, get_root, isErrorResponse, TokenInjectType } from '@/api';
const router = useRouter();
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
async function start_redirect() {
const token = await check_token(jwt);
if (!token) return;
const root = await get_root(token);
if (isErrorResponse(root)) return jwt.logout();
await router.push({
name: 'fs',
params: { node_id: root.rootId }
});
}
onBeforeRouteUpdate(async () => {
await start_redirect();
});
onBeforeMount(async () => {
await start_redirect();
});
</script>

View File

@ -0,0 +1,43 @@
<script setup lang="ts">
import { ref, inject } from 'vue';
import { auth_login, get_root, isErrorResponse, TokenInjectType } from '@/api';
import { useRouter } from 'vue-router';
const router = useRouter();
let username = ref('');
let password = ref('');
const error = ref('');
const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;
async function login() {
if (username.value === '' || password.value === '') {
error.value = 'Username and/or Password missing';
return;
}
const res = await auth_login(username.value, password.value);
if (isErrorResponse(res)) error.value = 'Login failed: ' + res.message;
else {
const root = await get_root(res.jwt);
if (isErrorResponse(root)) {
error.value = 'Get root failed: ' + root.message;
return;
}
jwt.setToken(res.jwt);
await router.push({
name: 'fs',
params: { node_id: root.rootId }
});
}
}
</script>
<template>
<div v-if="error !== ''" v-text="error"></div>
<input type="email" placeholder="Email" v-model="username" />
<input type="password" placeholder="Password" v-model="password" />
<button @click="login()">Login</button>
</template>
<style scoped></style>

40
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,40 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}

12
frontend/vue.config.js Normal file
View File

@ -0,0 +1,12 @@
const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
resolve: {
fallback: {
crypto: false,
stream: require.resolve('stream-browserify')
}
}
}
});

5
nest-cli.json Normal file
View File

@ -0,0 +1,5 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

18695
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

88
package.json Normal file
View File

@ -0,0 +1,88 @@
{
"name": "nest-typescript-starter",
"private": true,
"version": "1.0.0",
"description": "Nest TypeScript starter repository",
"license": "MIT",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.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"
},
"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",
"@typescript-eslint/typescript-estree": "^5.33.0",
"argon2": "^0.28.7",
"jsonwebtoken": "^8.5.1",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.6",
"sqlite3": "^5.0.11",
"typeorm": "^0.3.7"
},
"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/passport-jwt": "^3.0.6",
"@types/passport-local": "^1.0.34",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.33.0",
"@typescript-eslint/parser": "^5.33.0",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^28.1.3",
"prettier": "^2.7.1",
"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",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

28
requests.http Normal file
View File

@ -0,0 +1,28 @@
### 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}}

52
src/app.module.ts Normal file
View File

@ -0,0 +1,52 @@
import { Controller, Get, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { INode, JWTToken, User, UserRole } 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';
@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: join(__dirname, '..', '..', 'frontend', 'dist'),
exclude: ['/api*']
}),
FileSystemModule,
AuthModule
],
controllers: [TestController],
providers: [
{
provide: 'APP_GUARD',
useClass: JWTAuthGuard
},
{
provide: 'APP_GUARD',
useClass: RoleGuard
}
]
})
export class AppModule {}

46
src/authguards.ts Normal file
View File

@ -0,0 +1,46 @@
import {
CanActivate,
ExecutionContext,
Injectable,
SetMetadata
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { User, UserRole } from './entities';
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;
}
}

58
src/controller/auth.ts Normal file
View File

@ -0,0 +1,58 @@
import {
BadRequestException,
Body,
Controller,
HttpCode,
Post,
Request,
UseGuards
} from '@nestjs/common';
import { AuthService } from '../services/auth';
import { AuthGuard } from '@nestjs/passport';
import { Public } from '../authguards';
import {
BaseResponse,
ErrorResponse,
LoginResponse,
RefreshResponse
} from 'dto';
@Controller('api/auth')
export default class AuthController {
constructor(private authService: AuthService) {}
@Public()
@UseGuards(AuthGuard('local'))
@Post('login')
@HttpCode(200)
async login(@Request() req): Promise<LoginResponse> {
return {
statusCode: 200,
jwt: await this.authService.login(req.user)
};
}
@Public()
@Post('signup')
async signup(
@Body('username') username,
@Body('password') password
): Promise<BaseResponse | ErrorResponse> {
if ((await this.authService.findUser(username)) != null)
throw new BadRequestException('Username already taken');
await this.authService.signup(username, password);
return {
statusCode: 200
};
}
@Post('refresh')
async refresh(@Request() req): Promise<RefreshResponse | ErrorResponse> {
const token = await this.authService.login(req.user);
await this.authService.revoke(req.token);
return {
statusCode: 200,
jwt: token
};
}
}

View File

@ -0,0 +1,141 @@
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Post,
Request,
StreamableFile
} from '@nestjs/common';
import {
CreateFileResponse,
CreateFolderResponse,
DeleteResponse,
GetNodeResponse,
GetPathResponse,
GetRootResponse,
UploadFileResponse
} from 'dto/index';
import FileSystemService from '../services/filesystem';
import { UserRole } from '../entities';
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<GetRootResponse> {
return {
statusCode: 200,
rootId: req.user.rootId
};
}
@Get('node/:node')
@Role(UserRole.USER)
async getNode(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<GetNodeResponse> {
const node = await this.fsService.getNodeAndValidate(nodeId, req.user);
const data: GetNodeResponse = {
id: nodeId,
statusCode: 200,
name: node.name,
parent: node.parentId,
isFile: node.isFile
};
if (data.isFile) {
data.size = node.size;
} else {
data.children = (await node.children).map((child) => child.id);
}
return data;
}
@Get('path/:node')
@Role(UserRole.USER)
async getPath(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<GetPathResponse> {
return {
statusCode: 200,
path: await this.fsService.generatePath(
await this.fsService.getNodeAndValidate(nodeId, req.user)
)
};
}
@Post('createFolder')
@Role(UserRole.USER)
async createFolder(
@Request() req,
@Body('parent', ParseIntPipe) parent,
@Body('name') name
): Promise<CreateFolderResponse> {
const newChild = await this.fsService.create(
await this.fsService.getNodeAndValidate(parent, req.user),
name,
req.user,
false
);
return {
statusCode: 200,
id: newChild.id
};
}
@Post('createFile')
@Role(UserRole.USER)
async createFile(
@Request() req,
@Body('parent', ParseIntPipe) parent,
@Body('name') name
): Promise<CreateFileResponse> {
const newChild = await this.fsService.create(
await this.fsService.getNodeAndValidate(parent, req.user),
name,
req.user,
true
);
return {
statusCode: 200,
id: newChild.id
};
}
@Post('delete')
@Role(UserRole.USER)
async delete(
@Request() req,
@Body('node', ParseIntPipe) node_id
): Promise<DeleteResponse> {
await this.fsService.delete(
await this.fsService.getNodeAndValidate(node_id, req.user)
);
return { statusCode: 200 };
}
@Post('upload/:node')
@Role(UserRole.USER)
async upload(
@Request() req,
@Param('node', ParseIntPipe) nodeId
): Promise<UploadFileResponse> {
await this.fsService.uploadFile(await req.file(), nodeId, req.user);
return { statusCode: 200 };
}
@Post('download')
@Role(UserRole.USER)
async download(
@Request() req,
@Body('id', ParseIntPipe) id
): Promise<StreamableFile> {
return this.fsService.downloadFile(id, req.user);
}
}

74
src/entities/index.ts Normal file
View File

@ -0,0 +1,74 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
OneToMany,
OneToOne
} from 'typeorm';
export enum UserRole {
ADMIN = 2,
USER = 1,
DISABLED = 0
}
@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()
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>;
}
@Entity()
export class JWTToken {
@PrimaryGeneratedColumn()
id: number;
@Column()
ownerId: number;
@Column({ nullable: true })
exp: number;
}

20
src/main.ts Normal file
View File

@ -0,0 +1,20 @@
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();

22
src/modules/auth.ts Normal file
View File

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

12
src/modules/filesystem.ts Normal file
View File

@ -0,0 +1,12 @@
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 {}

145
src/services/auth.ts Normal file
View File

@ -0,0 +1,145 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { JWTToken, User, UserRole } from '../entities';
import { Repository, LessThanOrEqual } from 'typeorm';
import * as argon2 from 'argon2';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { ExtractJwt, Strategy as JWTStrategy } from 'passport-jwt';
import FileSystemService from './filesystem';
import * as jwt from 'jsonwebtoken';
const jwtSecret = 'CUM';
interface jwtPayload {
sub: number;
jti: number;
exp?: number;
iat?: number;
}
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private userRepo: Repository<User>,
@InjectRepository(JWTToken)
private tokenRepo: Repository<JWTToken>,
private fsService: FileSystemService
) {}
async getUser(userId: number): Promise<User | null> {
return this.userRepo.findOneBy({
id: userId
});
}
async findUser(username: string): Promise<User | null> {
return this.userRepo.findOneBy({
name: username
});
}
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);
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(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 signup(username: string, password: string) {
const user = new User();
user.name = username;
user.password = await argon2.hash(password);
const dbUser = await this.userRepo.save(user);
const root = await this.fsService.generateRoot(dbUser);
dbUser.rootId = root.id;
await this.userRepo.save(dbUser);
}
async revoke(token: JWTToken) {
await this.tokenRepo.delete({
id: token.id
});
}
}
@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'
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
req.token = token;
return user;
}
}

129
src/services/filesystem.ts Normal file
View File

@ -0,0 +1,129 @@
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): Promise<void> {
if (node.parentId == null)
throw new BadRequestException("Can't delete root");
if (!node.isFile)
await Promise.all(
(await node.children).map((child) => this.delete(child))
);
else
unlink(`files/${node.id}`, (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
});
}
}

62
tools/apigen.ts Normal file
View File

@ -0,0 +1,62 @@
import {
AST_NODE_TYPES,
createProgram,
parse
} from '@typescript-eslint/typescript-estree';
import * as fs from 'fs';
import {
Decorator,
ExportDefaultDeclaration,
FunctionExpression,
Literal
} from '@typescript-eslint/types/dist/generated/ast-spec';
const program = createProgram('tsconfig.json');
const ast = parse(fs.readFileSync('src/controller/filesystem.ts').toString(), {
programs: [program]
});
function parseDecorators(decs: Decorator[]): object[] | null {
try {
return decs.map((dec) => {
if (dec.expression.type !== AST_NODE_TYPES.CallExpression)
throw null;
if (dec.expression.callee.type != AST_NODE_TYPES.Identifier)
throw null;
const name = dec.expression.callee.name;
if (name === 'Request') throw null;
const prop = (
dec.expression.arguments
.filter((arg) => arg.type === AST_NODE_TYPES.Literal)
.pop() as Literal
).value;
return { name: name, prop: prop };
});
} catch (e) {
return null;
}
}
function parseFunction(name: string, func: FunctionExpression) {
const decs = func.params
.map((p) => p.decorators)
.map(parseDecorators)
.filter((d) => d !== null);
console.log(name, decs);
}
ast.body
.filter((body) => body.type == AST_NODE_TYPES.ExportDefaultDeclaration)
.forEach((body: ExportDefaultDeclaration) => {
if (body.declaration.type !== AST_NODE_TYPES.ClassDeclaration) return;
if (body.declaration.body.type !== AST_NODE_TYPES.ClassBody) return;
body.declaration.body.body.forEach((def) => {
if (
def.type === AST_NODE_TYPES.MethodDefinition &&
'name' in def.key &&
def.key.name !== 'constructor' &&
def.value.type === AST_NODE_TYPES.FunctionExpression
)
parseFunction(def.key.name, def.value);
});
});

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "test", "**/*spec.ts", "frontend"]
}

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true
}
}