1
0
mirror of https://github.com/stonith404/pingvin-share.git synced 2024-07-04 08:20:13 +02:00

Merge remote-tracking branch 'stonith404/main' into main

This commit is contained in:
Elias Schneider 2022-10-16 00:08:37 +02:00
commit 9d17377bbc
47 changed files with 6692 additions and 881 deletions

View File

@ -1,8 +1,8 @@
backend/dist/ backend/dist/
backend/node_modules/ backend/node_modules/
backend/data
frontend/node_modules/ frontend/node_modules/
frontend/.next/ frontend/.next/
frontend/dist/
**/.git/ **/.git/

View File

@ -0,0 +1,22 @@
name: Backend system tests
on:
pull_request:
branches:
- main
jobs:
system-tests:
runs-on: ubuntu-latest
container: node:18
steps:
- uses: actions/checkout@v2
- name: Install Dependencies
working-directory: ./backend
run: npm install
- name: Create .env file
working-directory: ./backend
run: mv .env.example .env
- name: Run Server and Test with Newman
working-directory: ./backend
run: npm run test:system

View File

@ -4,8 +4,8 @@ on:
push: push:
branches: main branches: main
paths: paths:
- 'frontend/**' - "frontend/**"
- 'backend/**' - "backend/**"
jobs: jobs:
build: build:

View File

@ -37,7 +37,7 @@ The website is now listening available on `http://localhost:3000`, have fun with
### Upgrade to a new version ### Upgrade to a new version
Just updated the docker container by running `docker-compose pull && docker-compose up -d` Just update the docker container by running `docker compose pull && docker compose up -d`
> Note: If you installed Pingvin Share before it used Sqlite, you unfortunately have to set up the project from scratch again, sorry for that. > Note: If you installed Pingvin Share before it used Sqlite, you unfortunately have to set up the project from scratch again, sorry for that.
@ -65,3 +65,7 @@ Contact me, create an issue or directly create a pull request.
5. Start the frontend with `npm run dev` 5. Start the frontend with `npm run dev`
You're all set! You're all set!
### Testing
At the moment we only have system tests for the backend. To run these tests, run `npm run test:system` in the backend folder.

View File

@ -1,18 +1,6 @@
{ {
"env": { "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"browser": true, "parser": "@typescript-eslint/parser",
"es2021": true "plugins": ["@typescript-eslint"],
}, "root": true
"overrides": [
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
}
} }

4331
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,8 @@
"dev": "dotenv -- nest start --watch", "dev": "dotenv -- nest start --watch",
"prod": "npx prisma migrate deploy && dotenv node dist/main", "prod": "npx prisma migrate deploy && dotenv node dist/main",
"lint": "eslint 'src/**/*.ts'", "lint": "eslint 'src/**/*.ts'",
"format": "prettier --write 'src/**/*.ts'" "format": "prettier --write 'src/**/*.ts'",
"test:system": "npx prisma migrate reset -f && nest start & sleep 10 && newman run ./test/system/newman-system-tests.json"
}, },
"dependencies": { "dependencies": {
"@nestjs/common": "^9.1.2", "@nestjs/common": "^9.1.2",
@ -21,6 +22,7 @@
"argon2": "^0.29.1", "argon2": "^0.29.1",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.13.2", "class-validator": "^0.13.2",
"content-disposition": "^0.5.4",
"mime-types": "^2.1.35", "mime-types": "^2.1.35",
"moment": "^2.29.4", "moment": "^2.29.4",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
@ -44,19 +46,20 @@
"@types/node": "^18.7.23", "@types/node": "^18.7.23",
"@types/passport-jwt": "^3.0.7", "@types/passport-jwt": "^3.0.7",
"@types/supertest": "^2.0.12", "@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.39.0", "@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.39.0", "@typescript-eslint/parser": "^5.40.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"dotenv-cli": "^6.0.0", "dotenv-cli": "^6.0.0",
"eslint": "^8.0.1", "eslint": "^8.25.0",
"eslint-config-prettier": "^8.3.0", "eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "^4.0.0",
"newman": "^5.3.2",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"prisma": "^4.4.0", "prisma": "^4.4.0",
"source-map-support": "^0.5.21", "source-map-support": "^0.5.21",
"ts-loader": "^9.4.1", "ts-loader": "^9.4.1",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tsconfig-paths": "4.1.0", "tsconfig-paths": "4.1.0",
"typescript": "^4.3.5" "typescript": "^4.8.4"
} }
} }

View File

@ -0,0 +1,14 @@
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_RefreshToken" (
"token" TEXT NOT NULL PRIMARY KEY,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" DATETIME NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "RefreshToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_RefreshToken" ("createdAt", "expiresAt", "token", "userId") SELECT "createdAt", "expiresAt", "token", "userId" FROM "RefreshToken";
DROP TABLE "RefreshToken";
ALTER TABLE "new_RefreshToken" RENAME TO "RefreshToken";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;

View File

@ -28,7 +28,7 @@ model RefreshToken {
expiresAt DateTime expiresAt DateTime
userId String userId String
user User @relation(fields: [userId], references: [id]) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
} }
model Share { model Share {

View File

@ -27,6 +27,7 @@ export class AuthController {
} }
@Post("signIn") @Post("signIn")
@HttpCode(200)
signIn(@Body() dto: AuthSignInDTO) { signIn(@Body() dto: AuthSignInDTO) {
return this.authService.signIn(dto); return this.authService.signIn(dto);
} }

View File

@ -1,4 +1,3 @@
import { PickType } from "@nestjs/swagger";
import { UserDTO } from "src/user/dto/user.dto"; import { UserDTO } from "src/user/dto/user.dto";
export class AuthRegisterDTO extends UserDTO {} export class AuthRegisterDTO extends UserDTO {}

View File

@ -1,4 +1,4 @@
import { IsNotEmpty, IsString } from "class-validator"; import { IsNotEmpty } from "class-validator";
export class RefreshAccessTokenDTO { export class RefreshAccessTokenDTO {
@IsNotEmpty() @IsNotEmpty()

View File

@ -14,7 +14,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}); });
} }
async validate(payload: any) { async validate(payload: { sub: string }) {
const user: User = await this.prisma.user.findUnique({ const user: User = await this.prisma.user.findUnique({
where: { id: payload.sub }, where: { id: payload.sub },
}); });

View File

@ -11,9 +11,6 @@ export class FileDTO {
@Expose() @Expose()
size: string; size: string;
@Expose()
url: boolean;
share: ShareDTO; share: ShareDTO;
from(partial: Partial<FileDTO>) { from(partial: Partial<FileDTO>) {

View File

@ -11,6 +11,7 @@ import {
UseInterceptors, UseInterceptors,
} from "@nestjs/common"; } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express"; import { FileInterceptor } from "@nestjs/platform-express";
import * as contentDisposition from "content-disposition";
import { Response } from "express"; import { Response } from "express";
import { JwtGuard } from "src/auth/guard/jwt.guard"; import { JwtGuard } from "src/auth/guard/jwt.guard";
import { FileDownloadGuard } from "src/file/guard/fileDownload.guard"; import { FileDownloadGuard } from "src/file/guard/fileDownload.guard";
@ -41,6 +42,10 @@ export class FileController {
file: Express.Multer.File, file: Express.Multer.File,
@Param("shareId") shareId: string @Param("shareId") shareId: string
) { ) {
// Fixes file names with special characters
file.originalname = Buffer.from(file.originalname, "latin1").toString(
"utf8"
);
return new ShareDTO().from(await this.fileService.create(file, shareId)); return new ShareDTO().from(await this.fileService.create(file, shareId));
} }
@ -98,7 +103,7 @@ export class FileController {
res.set({ res.set({
"Content-Type": file.metaData.mimeType, "Content-Type": file.metaData.mimeType,
"Content-Length": file.metaData.size, "Content-Length": file.metaData.size,
"Content-Disposition": `attachment ; filename="${file.metaData.name}"`, "Content-Disposition": contentDisposition(file.metaData.name),
}); });
return new StreamableFile(file.file); return new StreamableFile(file.file);

View File

@ -1,7 +1,6 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt"; import { JwtModule } from "@nestjs/jwt";
import { ShareModule } from "src/share/share.module"; import { ShareModule } from "src/share/share.module";
import { ShareService } from "src/share/share.service";
import { FileController } from "./file.controller"; import { FileController } from "./file.controller";
import { FileService } from "./file.service"; import { FileService } from "./file.service";

View File

@ -100,12 +100,12 @@ export class FileService {
); );
} }
verifyFileDownloadToken(shareId: string, fileId: string, token: string) { verifyFileDownloadToken(shareId: string, token: string) {
try { try {
const claims = this.jwtService.verify(token, { const claims = this.jwtService.verify(token, {
secret: this.config.get("JWT_SECRET"), secret: this.config.get("JWT_SECRET"),
}); });
return claims.shareId == shareId && claims.fileId == fileId; return claims.shareId == shareId;
} catch { } catch {
return false; return false;
} }

View File

@ -1,23 +1,17 @@
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common"; import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express"; import { Request } from "express";
import { FileService } from "src/file/file.service"; import { FileService } from "src/file/file.service";
import { PrismaService } from "src/prisma/prisma.service";
@Injectable() @Injectable()
export class FileDownloadGuard implements CanActivate { export class FileDownloadGuard implements CanActivate {
constructor( constructor(private fileService: FileService) {}
private reflector: Reflector,
private fileService: FileService,
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const token = request.query.token as string; const token = request.query.token as string;
const { shareId, fileId } = request.params; const { shareId } = request.params;
return this.fileService.verifyFileDownloadToken(shareId, fileId, token); return this.fileService.verifyFileDownloadToken(shareId, token);
} }
} }

View File

@ -1,5 +1,5 @@
import { Type } from "class-transformer"; import { Type } from "class-transformer";
import { IsString, Matches, ValidateNested } from "class-validator"; import { IsString, Length, Matches, ValidateNested } from "class-validator";
import { ShareSecurityDTO } from "./shareSecurity.dto"; import { ShareSecurityDTO } from "./shareSecurity.dto";
export class CreateShareDTO { export class CreateShareDTO {
@ -7,6 +7,7 @@ export class CreateShareDTO {
@Matches("^[a-zA-Z0-9_-]*$", undefined, { @Matches("^[a-zA-Z0-9_-]*$", undefined, {
message: "ID only can contain letters, numbers, underscores and hyphens", message: "ID only can contain letters, numbers, underscores and hyphens",
}) })
@Length(3, 50)
id: string; id: string;
@IsString() @IsString()

View File

@ -1,6 +1,3 @@
import { IsNotEmpty } from "class-validator";
export class SharePasswordDto { export class SharePasswordDto {
@IsNotEmpty()
password: string; password: string;
} }

View File

@ -1,16 +1,16 @@
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common"; import {
import { Reflector } from "@nestjs/core"; CanActivate,
ExecutionContext,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { User } from "@prisma/client"; import { User } from "@prisma/client";
import { Request } from "express"; import { Request } from "express";
import { ExtractJwt } from "passport-jwt";
import { PrismaService } from "src/prisma/prisma.service"; import { PrismaService } from "src/prisma/prisma.service";
import { ShareService } from "src/share/share.service";
@Injectable() @Injectable()
export class ShareOwnerGuard implements CanActivate { export class ShareOwnerGuard implements CanActivate {
constructor( constructor(private prisma: PrismaService) {}
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
@ -26,7 +26,7 @@ export class ShareOwnerGuard implements CanActivate {
include: { security: true }, include: { security: true },
}); });
if (!share) throw new NotFoundException("Share not found");
return share.creatorId == (request.user as User).id; return share.creatorId == (request.user as User).id;
} }

View File

@ -21,6 +21,7 @@ export class ShareSecurityGuard implements CanActivate {
async canActivate(context: ExecutionContext) { async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest(); const request: Request = context.switchToHttp().getRequest();
const shareToken = request.get("X-Share-Token");
const shareId = Object.prototype.hasOwnProperty.call( const shareId = Object.prototype.hasOwnProperty.call(
request.params, request.params,
"shareId" "shareId"
@ -36,19 +37,15 @@ export class ShareSecurityGuard implements CanActivate {
if (!share || (moment().isAfter(share.expiration) && moment(share.expiration).unix() !== 0)) if (!share || (moment().isAfter(share.expiration) && moment(share.expiration).unix() !== 0))
throw new NotFoundException("Share not found"); throw new NotFoundException("Share not found");
if (!share.security) return true; if (share.security?.password && !shareToken)
if (share.security.maxViews && share.security.maxViews <= share.views)
throw new ForbiddenException(
"Maximum views exceeded",
"share_max_views_exceeded"
);
if (
!this.shareService.verifyShareToken(shareId, request.get("X-Share-Token"))
)
throw new ForbiddenException( throw new ForbiddenException(
"This share is password protected", "This share is password protected",
"share_password_required"
);
if (!this.shareService.verifyShareToken(shareId, shareToken))
throw new ForbiddenException(
"Share token required",
"share_token_required" "share_token_required"
); );

View File

@ -0,0 +1,47 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";
import * as moment from "moment";
import { PrismaService } from "src/prisma/prisma.service";
import { ShareService } from "src/share/share.service";
@Injectable()
export class ShareTokenSecurity implements CanActivate {
constructor(
private reflector: Reflector,
private shareService: ShareService,
private prisma: PrismaService
) {}
async canActivate(context: ExecutionContext) {
const request: Request = context.switchToHttp().getRequest();
const shareId = Object.prototype.hasOwnProperty.call(
request.params,
"shareId"
)
? request.params.shareId
: request.params.id;
const share = await this.prisma.share.findUnique({
where: { id: shareId },
include: { security: true },
});
if (!share || moment().isAfter(share.expiration))
throw new NotFoundException("Share not found");
if (share.security?.maxViews && share.security.maxViews <= share.views)
throw new ForbiddenException(
"Maximum views exceeded",
"share_max_views_exceeded"
);
return true;
}
}

View File

@ -18,6 +18,7 @@ import { ShareMetaDataDTO } from "./dto/shareMetaData.dto";
import { SharePasswordDto } from "./dto/sharePassword.dto"; import { SharePasswordDto } from "./dto/sharePassword.dto";
import { ShareOwnerGuard } from "./guard/shareOwner.guard"; import { ShareOwnerGuard } from "./guard/shareOwner.guard";
import { ShareSecurityGuard } from "./guard/shareSecurity.guard"; import { ShareSecurityGuard } from "./guard/shareSecurity.guard";
import { ShareTokenSecurity } from "./guard/shareTokenSecurity.guard";
import { ShareService } from "./share.service"; import { ShareService } from "./share.service";
@Controller("shares") @Controller("shares")
@ -68,11 +69,10 @@ export class ShareController {
return this.shareService.isShareIdAvailable(id); return this.shareService.isShareIdAvailable(id);
} }
@Post(":id/password") @HttpCode(200)
async exchangeSharePasswordWithToken( @UseGuards(ShareTokenSecurity)
@Param("id") id: string, @Post(":id/token")
@Body() body: SharePasswordDto async getShareToken(@Param("id") id: string, @Body() body: SharePasswordDto) {
) { return this.shareService.getShareToken(id, body.password);
return this.shareService.exchangeSharePasswordWithToken(id, body.password);
} }
} }

View File

@ -1,8 +1,8 @@
import { import {
BadRequestException, BadRequestException,
ForbiddenException, ForbiddenException,
Injectable, Injectable,
NotFoundException, NotFoundException,
} from "@nestjs/common"; } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { JwtService } from "@nestjs/jwt"; import { JwtService } from "@nestjs/jwt";
@ -17,195 +17,213 @@ import { CreateShareDTO } from "./dto/createShare.dto";
@Injectable() @Injectable()
export class ShareService { export class ShareService {
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private fileService: FileService, private fileService: FileService,
private config: ConfigService, private config: ConfigService,
private jwtService: JwtService private jwtService: JwtService
) { ) {}
async create(share: CreateShareDTO, user: User) {
if (!(await this.isShareIdAvailable(share.id)).isAvailable)
throw new BadRequestException("Share id already in use");
if (!share.security || Object.keys(share.security).length == 0)
share.security = undefined;
if (share.security?.password) {
share.security.password = await argon.hash(share.security.password);
} }
async create(share: CreateShareDTO, user: User) { // We have to add an exception for "never" (since moment won't like that)
if (!(await this.isShareIdAvailable(share.id)).isAvailable) let expirationDate;
throw new BadRequestException("Share id already in use"); if (share.expiration !== "never") {
expirationDate = moment()
.add(
share.expiration.split("-")[0],
share.expiration.split(
"-"
)[1] as moment.unitOfTime.DurationConstructor
)
.toDate();
if (!share.security || Object.keys(share.security).length == 0) // Throw error if expiration date is now
share.security = undefined; if (expirationDate.setMilliseconds(0) == new Date().setMilliseconds(0))
throw new BadRequestException("Invalid expiration date");
if (share.security?.password) { } else {
share.security.password = await argon.hash(share.security.password); expirationDate = moment(0).toDate();
}
// We have to add an exception for "never" (since moment won't like that)
let expirationDate;
if (share.expiration !== "never") {
expirationDate = moment()
.add(
share.expiration.split("-")[0],
share.expiration.split("-")[1] as moment.unitOfTime.DurationConstructor
)
.toDate();
// Throw error if expiration date is now
if (expirationDate.setMilliseconds(0) == new Date().setMilliseconds(0))
throw new BadRequestException("Invalid expiration date");
} else {
expirationDate = moment(0).toDate();
}
return await this.prisma.share.create({
data: {
...share,
expiration: expirationDate,
creator: {connect: {id: user.id}},
security: {create: share.security},
},
});
} }
async createZip(shareId: string) { return await this.prisma.share.create({
const path = `./data/uploads/shares/${shareId}`; data: {
...share,
expiration: expirationDate,
creator: { connect: { id: user.id } },
security: { create: share.security },
},
});
}
const files = await this.prisma.file.findMany({where: {shareId}}); async createZip(shareId: string) {
const archive = archiver("zip", { const path = `./data/uploads/shares/${shareId}`;
zlib: {level: 9},
});
const writeStream = fs.createWriteStream(`${path}/archive.zip`);
for (const file of files) { const files = await this.prisma.file.findMany({ where: { shareId } });
archive.append(fs.createReadStream(`${path}/${file.id}`), { const archive = archiver("zip", {
name: file.name, zlib: { level: 9 },
}); });
} const writeStream = fs.createWriteStream(`${path}/archive.zip`);
archive.pipe(writeStream); for (const file of files) {
await archive.finalize(); archive.append(fs.createReadStream(`${path}/${file.id}`), {
name: file.name,
});
} }
async complete(id: string) { archive.pipe(writeStream);
const moreThanOneFileInShare = await archive.finalize();
(await this.prisma.file.findMany({where: {shareId: id}})).length != 0; }
if (!moreThanOneFileInShare) async complete(id: string) {
throw new BadRequestException( if (await this.isShareCompleted(id))
"You need at least on file in your share to complete it." throw new BadRequestException("Share already completed");
);
this.createZip(id).then(() => const moreThanOneFileInShare =
this.prisma.share.update({where: {id}, data: {isZipReady: true}}) (await this.prisma.file.findMany({ where: { shareId: id } })).length != 0;
);
return await this.prisma.share.update({ if (!moreThanOneFileInShare)
where: {id}, throw new BadRequestException(
data: {uploadLocked: true}, "You need at least on file in your share to complete it."
}); );
}
this.createZip(id).then(() =>
async getSharesByUser(userId: string) { this.prisma.share.update({ where: { id }, data: { isZipReady: true } })
return await this.prisma.share.findMany({ );
where: {
creator: {id: userId}, return await this.prisma.share.update({
// We want to grab any shares that are not expired or have their expiration date set to "never" (unix 0) where: { id },
OR: [{expiration: {gt: new Date()}}, {expiration: {equals: moment(0).toDate()}}] data: { uploadLocked: true },
}, });
}); }
}
async getSharesByUser(userId: string) {
async get(id: string) { return await this.prisma.share.findMany({
let share: any = await this.prisma.share.findUnique({ where: {
where: {id}, creator: { id: userId },
include: { uploadLocked: true,
files: true, // We want to grab any shares that are not expired or have their expiration date set to "never" (unix 0)
creator: true, OR: [
}, { expiration: { gt: new Date() } },
}); { expiration: { equals: moment(0).toDate() } },
],
if (!share || !share.uploadLocked) },
throw new NotFoundException("Share not found"); orderBy: {
expiration: "desc",
share.files = share.files.map((file) => { },
file["url"] = `http://localhost:8080/file/${file.id}`; });
return file; }
});
async get(id: string) {
await this.increaseViewCount(share); const share: any = await this.prisma.share.findUnique({
where: { id },
return share; include: {
} files: true,
creator: true,
async getMetaData(id: string) { },
const share = await this.prisma.share.findUnique({ });
where: {id},
}); if (!share || !share.uploadLocked)
throw new NotFoundException("Share not found");
if (!share || !share.uploadLocked)
throw new NotFoundException("Share not found"); return share;
}
return share;
} async getMetaData(id: string) {
const share = await this.prisma.share.findUnique({
async remove(shareId: string) { where: { id },
const share = await this.prisma.share.findUnique({ });
where: {id: shareId},
}); if (!share || !share.uploadLocked)
throw new NotFoundException("Share not found");
if (!share) throw new NotFoundException("Share not found");
return share;
await this.fileService.deleteAllFiles(shareId); }
await this.prisma.share.delete({where: {id: shareId}});
} async remove(shareId: string) {
const share = await this.prisma.share.findUnique({
async isShareCompleted(id: string) { where: { id: shareId },
return (await this.prisma.share.findUnique({where: {id}})).uploadLocked; });
}
if (!share) throw new NotFoundException("Share not found");
async isShareIdAvailable(id: string) {
const share = await this.prisma.share.findUnique({where: {id}}); await this.fileService.deleteAllFiles(shareId);
return {isAvailable: !share}; await this.prisma.share.delete({ where: { id: shareId } });
} }
async increaseViewCount(share: Share) { async isShareCompleted(id: string) {
await this.prisma.share.update({ return (await this.prisma.share.findUnique({ where: { id } })).uploadLocked;
where: {id: share.id}, }
data: {views: share.views + 1},
}); async isShareIdAvailable(id: string) {
} const share = await this.prisma.share.findUnique({ where: { id } });
return { isAvailable: !share };
async exchangeSharePasswordWithToken(shareId: string, password: string) { }
const sharePassword = (
await this.prisma.shareSecurity.findFirst({ async increaseViewCount(share: Share) {
where: {share: {id: shareId}}, await this.prisma.share.update({
}) where: { id: share.id },
).password; data: { views: share.views + 1 },
});
if (!(await argon.verify(sharePassword, password))) }
throw new ForbiddenException("Wrong password");
async getShareToken(shareId: string, password: string) {
const token = this.generateShareToken(shareId); const share = await this.prisma.share.findFirst({
return {token}; where: { id: shareId },
} include: {
security: true,
generateShareToken(shareId: string) { },
return this.jwtService.sign( });
{
shareId, if (
}, share?.security?.password &&
{ !(await argon.verify(share.security.password, password))
expiresIn: "1h", )
secret: this.config.get("JWT_SECRET"), throw new ForbiddenException("Wrong password");
}
); const token = await this.generateShareToken(shareId);
} await this.increaseViewCount(share);
return { token };
verifyShareToken(shareId: string, token: string) { }
try {
const claims = this.jwtService.verify(token, { async generateShareToken(shareId: string) {
secret: this.config.get("JWT_SECRET"), const { expiration } = await this.prisma.share.findUnique({
}); where: { id: shareId },
});
return claims.shareId == shareId; return this.jwtService.sign(
} catch { {
return false; shareId,
} },
{
expiresIn: moment(expiration).diff(new Date(), "seconds") + "s",
secret: this.config.get("JWT_SECRET"),
}
);
}
async verifyShareToken(shareId: string, token: string) {
const { expiration } = await this.prisma.share.findUnique({
where: { id: shareId },
});
try {
const claims = this.jwtService.verify(token, {
secret: this.config.get("JWT_SECRET"),
// Ignore expiration if expiration is 0
ignoreExpiration: moment(expiration).isSame(0),
});
return claims.shareId == shareId;
} catch {
return false;
} }
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
This is a test filed used for uploading in the system test.

View File

@ -26,7 +26,7 @@
"next-pwa": "^5.6.0", "next-pwa": "^5.6.0",
"react": "18.0.0", "react": "18.0.0",
"react-dom": "18.0.0", "react-dom": "18.0.0",
"tabler-icons-react": "^1.44.0", "react-icons": "^4.4.0",
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {
@ -6381,6 +6381,14 @@
"react": ">= 16.8 || 18.0.0" "react": ">= 16.8 || 18.0.0"
} }
}, },
"node_modules/react-icons": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/react-icons/-/react-icons-4.4.0.tgz",
"integrity": "sha512-fSbvHeVYo/B5/L4VhB7sBA1i2tS8MkT0Hb9t2H1AVPkwGfVHLJCqyr2Py9dKMxsyM63Eng1GkdZfbWj+Fmv8Rg==",
"peerDependencies": {
"react": "*"
}
},
"node_modules/react-is": { "node_modules/react-is": {
"version": "16.13.1", "version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
@ -6971,14 +6979,6 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/tabler-icons-react": {
"version": "1.44.0",
"resolved": "https://registry.npmjs.org/tabler-icons-react/-/tabler-icons-react-1.44.0.tgz",
"integrity": "sha512-AYQQGl55yVe1KHZl+zyDAAwDOcPknKZNC7vgwmjyvpmz4P5Gjb7DtpsOPa1nB0qMYW5Orsrt+1e4qnRoCKgo6A==",
"peerDependencies": {
"react": ">= 16.8.0"
}
},
"node_modules/tapable": { "node_modules/tapable": {
"version": "2.2.1", "version": "2.2.1",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz",
@ -12479,6 +12479,12 @@
"prop-types": "^15.8.1" "prop-types": "^15.8.1"
} }
}, },
"react-icons": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/react-icons/-/react-icons-4.4.0.tgz",
"integrity": "sha512-fSbvHeVYo/B5/L4VhB7sBA1i2tS8MkT0Hb9t2H1AVPkwGfVHLJCqyr2Py9dKMxsyM63Eng1GkdZfbWj+Fmv8Rg==",
"requires": {}
},
"react-is": { "react-is": {
"version": "16.13.1", "version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
@ -12910,12 +12916,6 @@
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="
}, },
"tabler-icons-react": {
"version": "1.44.0",
"resolved": "https://registry.npmjs.org/tabler-icons-react/-/tabler-icons-react-1.44.0.tgz",
"integrity": "sha512-AYQQGl55yVe1KHZl+zyDAAwDOcPknKZNC7vgwmjyvpmz4P5Gjb7DtpsOPa1nB0qMYW5Orsrt+1e4qnRoCKgo6A==",
"requires": {}
},
"tapable": { "tapable": {
"version": "2.2.1", "version": "2.2.1",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz",

View File

@ -29,7 +29,7 @@
"next-pwa": "^5.6.0", "next-pwa": "^5.6.0",
"react": "18.0.0", "react": "18.0.0",
"react-dom": "18.0.0", "react-dom": "18.0.0",
"tabler-icons-react": "^1.44.0", "react-icons": "^4.4.0",
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {

View File

@ -0,0 +1,34 @@
const Logo = ({ height, width }: { height: number; width: number }) => {
return (
<svg
id="Layer_1"
data-name="Layer 1"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 943.11 911.62"
height={height}
width={width}
>
<ellipse cx="471.56" cy="454.28" rx="471.56" ry="454.28" fill="#46509e" />
<ellipse cx="471.56" cy="390.28" rx="233.66" ry="207" fill="#37474f" />
<path
d="M705.22,849c-36.69,21.14-123.09,64.32-240.64,62.57A469.81,469.81,0,0,1,237.89,849V394.76H705.22Z"
fill="#37474f"
/>
<path
d="M658.81,397.7V873.49a478.12,478.12,0,0,1-374.19,0V397.7c0-95.55,83.78-173,187.1-173S658.81,302.15,658.81,397.7Z"
fill="#fff"
/>
<polygon
points="565.02 431.68 471.56 514.49 378.09 431.68 565.02 431.68"
fill="#46509e"
/>
<ellipse cx="378.09" cy="369.58" rx="23.37" ry="20.7" fill="#37474f" />
<ellipse cx="565.02" cy="369.58" rx="23.37" ry="20.7" fill="#37474f" />
<path
d="M658.49,400.63c0-40-36.6-72.45-81.79-72.45s-81.78,32.41-81.78,72.45a64.79,64.79,0,0,0,7.9,31.05H440.29a64.79,64.79,0,0,0,7.9-31.05c0-40-36.59-72.45-81.78-72.45s-81.79,32.41-81.79,72.45l-46.73-10.35c0-114.31,104.64-207,233.67-207s233.66,92.69,233.66,207Z"
fill="#37474f"
/>
</svg>
);
};
export default Logo;

View File

@ -1,6 +1,6 @@
import { ActionIcon, Avatar, Menu } from "@mantine/core"; import { ActionIcon, Avatar, Menu } from "@mantine/core";
import { NextLink } from "@mantine/next"; import { NextLink } from "@mantine/next";
import { DoorExit, Link } from "tabler-icons-react"; import { TbDoorExit, TbLink } from "react-icons/tb";;
import authService from "../../services/auth.service"; import authService from "../../services/auth.service";
const ActionAvatar = () => { const ActionAvatar = () => {
@ -15,7 +15,7 @@ const ActionAvatar = () => {
<Menu.Item <Menu.Item
component={NextLink} component={NextLink}
href="/account/shares" href="/account/shares"
icon={<Link size={14} />} icon={<TbLink size={14} />}
> >
My shares My shares
</Menu.Item> </Menu.Item>
@ -23,7 +23,7 @@ const ActionAvatar = () => {
onClick={async () => { onClick={async () => {
authService.signOut(); authService.signOut();
}} }}
icon={<DoorExit size={14} />} icon={<TbDoorExit size={14} />}
> >
Sign out Sign out
</Menu.Item> </Menu.Item>

View File

@ -5,7 +5,6 @@ import {
createStyles, createStyles,
Group, Group,
Header, Header,
Image,
Paper, Paper,
Stack, Stack,
Text, Text,
@ -16,6 +15,7 @@ import { NextLink } from "@mantine/next";
import getConfig from "next/config"; import getConfig from "next/config";
import { ReactNode, useEffect, useState } from "react"; import { ReactNode, useEffect, useState } from "react";
import useUser from "../../hooks/user.hook"; import useUser from "../../hooks/user.hook";
import Logo from "../Logo";
import ActionAvatar from "./ActionAvatar"; import ActionAvatar from "./ActionAvatar";
const { publicRuntimeConfig } = getConfig(); const { publicRuntimeConfig } = getConfig();
@ -152,14 +152,12 @@ const NavBar = () => {
const { classes, cx } = useStyles(); const { classes, cx } = useStyles();
const items = ( const items = (
<> <>
{(user ? authenticatedLinks : unauthenticatedLinks).map((link) => { {(user ? authenticatedLinks : unauthenticatedLinks).map((link, i) => {
if (link.component) { if (link.component) {
return ( return (
<> <Box pl={5} py={15} key={i}>
<Box pl={5} py={15}> {link.component}
{link.component} </Box>
</Box>
</>
); );
} }
return ( return (
@ -182,12 +180,7 @@ const NavBar = () => {
<Container className={classes.header}> <Container className={classes.header}>
<NextLink href="/"> <NextLink href="/">
<Group> <Group>
<Image <Logo height={35} width={35} />
src="/img/logo.svg"
alt="Pinvgin Share Logo"
height={35}
width={35}
/>
<Text weight={600}>Pingvin Share</Text> <Text weight={600}>Pingvin Share</Text>
</Group> </Group>
</NextLink> </NextLink>

View File

@ -1,197 +1,229 @@
import { import {
Accordion, Accordion,
Button, Button,
Col, Col,
Checkbox, Checkbox,
Grid, Grid,
NumberInput, NumberInput,
PasswordInput, PasswordInput,
Select, Select,
Stack, Stack,
Text, Text,
TextInput, TextInput,
} from "@mantine/core"; } from "@mantine/core";
import {useForm, yupResolver} from "@mantine/form"; import { useForm, yupResolver } from "@mantine/form";
import {useModals} from "@mantine/modals"; import { useModals } from "@mantine/modals";
import * as yup from "yup"; import * as yup from "yup";
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
import {ShareSecurity} from "../../types/share.type"; import { ShareSecurity } from "../../types/share.type";
import moment from "moment"; import moment from "moment";
import getConfig from "next/config"; import getConfig from "next/config";
const {publicRuntimeConfig} = getConfig(); const { publicRuntimeConfig } = getConfig();
const PreviewExpiration = ({form}: { form: any }) => { const PreviewExpiration = ({ form }: { form: any }) => {
const value = form.values.never_expires ? "never" : form.values.expiration_num + form.values.expiration_unit; const value = form.values.never_expires
if (value === "never") return "This share will never expire."; ? "never"
: form.values.expiration_num + form.values.expiration_unit;
if (value === "never") return "This share will never expire.";
const expirationDate = moment() const expirationDate = moment()
.add( .add(
value.split("-")[0], value.split("-")[0],
value.split("-")[1] as moment.unitOfTime.DurationConstructor value.split("-")[1] as moment.unitOfTime.DurationConstructor
) )
.toDate(); .toDate();
if (publicRuntimeConfig.TWELVE_HOUR_TIME === "true") if (publicRuntimeConfig.TWELVE_HOUR_TIME === "true")
return `This share will expire on ${moment(expirationDate).format("MMMM Do YYYY, h:mm a")}`; return `This share will expire on ${moment(expirationDate).format(
else "MMMM Do YYYY, h:mm a"
return `This share will expire on ${moment(expirationDate).format("MMMM DD YYYY, HH:mm")}`; )}`;
} else
return `This share will expire on ${moment(expirationDate).format(
"MMMM DD YYYY, HH:mm"
)}`;
};
const CreateUploadModalBody = ({ const CreateUploadModalBody = ({
uploadCallback, uploadCallback,
}: { }: {
uploadCallback: ( uploadCallback: (
id: string, id: string,
expiration: string, expiration: string,
security: ShareSecurity security: ShareSecurity
) => void; ) => void;
}) => { }) => {
const modals = useModals(); const modals = useModals();
const validationSchema = yup.object().shape({ const validationSchema = yup.object().shape({
link: yup link: yup
.string() .string()
.required() .required()
.min(3) .min(3)
.max(100) .max(50)
.matches(new RegExp("^[a-zA-Z0-9_-]*$"), { .matches(new RegExp("^[a-zA-Z0-9_-]*$"), {
message: "Can only contain letters, numbers, underscores and hyphens", message: "Can only contain letters, numbers, underscores and hyphens",
}), }),
password: yup.string().min(3).max(30), password: yup.string().min(3).max(30),
maxViews: yup.number().min(1), maxViews: yup.number().min(1),
}); });
const form = useForm({ const form = useForm({
initialValues: { initialValues: {
link: "", link: "",
password: undefined, password: undefined,
maxViews: undefined, maxViews: undefined,
expiration_num: 1, expiration_num: 1,
expiration_unit: "-days", expiration_unit: "-days",
never_expires: false never_expires: false,
}, },
validate: yupResolver(validationSchema), validate: yupResolver(validationSchema),
}); });
return ( return (
<form <form
onSubmit={form.onSubmit(async (values) => { onSubmit={form.onSubmit(async (values) => {
if (!(await shareService.isShareIdAvailable(values.link))) { if (!(await shareService.isShareIdAvailable(values.link))) {
form.setFieldError("link", "This link is already in use"); form.setFieldError("link", "This link is already in use");
} else { } else {
const expiration = form.values.never_expires ? "never" : form.values.expiration_num + form.values.expiration_unit; const expiration = form.values.never_expires
uploadCallback(values.link, expiration, { ? "never"
password: values.password, : form.values.expiration_num + form.values.expiration_unit;
maxViews: values.maxViews, uploadCallback(values.link, expiration, {
}); password: values.password,
modals.closeAll(); maxViews: values.maxViews,
} });
})} modals.closeAll();
}
})}
>
<Stack align="stretch">
<Grid align={form.errors.link ? "center" : "flex-end"}>
<Col xs={9}>
<TextInput
variant="filled"
label="Link"
placeholder="myAwesomeShare"
{...form.getInputProps("link")}
/>
</Col>
<Col xs={3}>
<Button
variant="outline"
onClick={() =>
form.setFieldValue(
"link",
Buffer.from(Math.random().toString(), "utf8")
.toString("base64")
.substr(10, 7)
)
}
>
Generate
</Button>
</Col>
</Grid>
<Text
italic
size="xs"
sx={(theme) => ({
color: theme.colors.gray[6],
})}
> >
<Stack align="stretch"> {window.location.origin}/share/
<Grid align={form.errors.link ? "center" : "flex-end"}> {form.values.link == "" ? "myAwesomeShare" : form.values.link}
<Col xs={9}> </Text>
<TextInput <Grid align={form.errors.link ? "center" : "flex-end"}>
variant="filled" <Col xs={6}>
label="Link" <NumberInput
placeholder="myAwesomeShare" min={1}
{...form.getInputProps("link")} max={99999}
/> precision={0}
</Col> variant="filled"
<Col xs={3}> label="Expiration"
<Button placeholder="n"
variant="outline" disabled={form.values.never_expires}
onClick={() => {...form.getInputProps("expiration_num")}
form.setFieldValue( />
"link", </Col>
Buffer.from(Math.random().toString(), "utf8") <Col xs={6}>
.toString("base64") <Select
.substr(10, 7) disabled={form.values.never_expires}
) {...form.getInputProps("expiration_unit")}
} data={[
> // Set the label to singular if the number is 1, else plural
Generate {
</Button> value: "-minutes",
</Col> label:
</Grid> "Minute" + (form.values.expiration_num == 1 ? "" : "s"),
},
{
value: "-hours",
label: "Hour" + (form.values.expiration_num == 1 ? "" : "s"),
},
{
value: "-days",
label: "Day" + (form.values.expiration_num == 1 ? "" : "s"),
},
{
value: "-weeks",
label: "Week" + (form.values.expiration_num == 1 ? "" : "s"),
},
{
value: "-months",
label: "Month" + (form.values.expiration_num == 1 ? "" : "s"),
},
{
value: "-years",
label: "Year" + (form.values.expiration_num == 1 ? "" : "s"),
},
]}
/>
</Col>
</Grid>
<Checkbox
label="Never Expires"
{...form.getInputProps("never_expires")}
/>
<Text italic {/* Preview expiration date text */}
size="xs" <Text
sx={(theme) => ({ italic
color: theme.colors.gray[6], size="xs"
})} sx={(theme) => ({
> color: theme.colors.gray[6],
{window.location.origin}/share/ })}
{form.values.link == "" ? "myAwesomeShare" : form.values.link} >
</Text> {PreviewExpiration({ form })}
<Grid align={form.errors.link ? "center" : "flex-end"}> </Text>
<Col xs={6}>
<NumberInput
min={1}
max={99999}
precision={0}
variant="filled"
label="Expiration"
placeholder="n"
disabled={form.values.never_expires}
{...form.getInputProps("expiration_num")}
/>
</Col>
<Col xs={6}>
<Select
disabled={form.values.never_expires}
{...form.getInputProps("expiration_unit")}
data={[
// Set the label to singular if the number is 1, else plural
{value: "-minutes", label: "Minute" + (form.values.expiration_num == 1 ? "" : "s")},
{value: "-hours", label: "Hour" + (form.values.expiration_num == 1 ? "" : "s")},
{value: "-days", label: "Day" + (form.values.expiration_num == 1 ? "" : "s")},
{value: "-weeks", label: "Week" + (form.values.expiration_num == 1 ? "" : "s")},
{value: "-months", label: "Month" + (form.values.expiration_num == 1 ? "" : "s")},
{value: "-years", label: "Year" + (form.values.expiration_num == 1 ? "" : "s")}
]}
/>
</Col>
</Grid>
<Checkbox label="Never Expires" {...form.getInputProps("never_expires")} />
{/* Preview expiration date text */} <Accordion>
<Text italic <Accordion.Item value="security" sx={{ borderBottom: "none" }}>
size="xs" <Accordion.Control>Security options</Accordion.Control>
sx={(theme) => ({ <Accordion.Panel>
color: theme.colors.gray[6], <Stack align="stretch">
})} <PasswordInput
> variant="filled"
{PreviewExpiration({form})} placeholder="No password"
</Text> label="Password protection"
{...form.getInputProps("password")}
<Accordion> />
<Accordion.Item value="security" sx={{borderBottom: "none"}}> <NumberInput
<Accordion.Control>Security options</Accordion.Control> min={1}
<Accordion.Panel> type="number"
<Stack align="stretch"> variant="filled"
<PasswordInput placeholder="No limit"
variant="filled" label="Maximal views"
placeholder="No password" {...form.getInputProps("maxViews")}
label="Password protection" />
{...form.getInputProps("password")} </Stack>
/> </Accordion.Panel>
<NumberInput </Accordion.Item>
min={1} </Accordion>
type="number" <Button type="submit">Share</Button>
variant="filled" </Stack>
placeholder="No limit" </form>
label="Maximal views" );
{...form.getInputProps("maxViews")}
/>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
<Button type="submit">Share</Button>
</Stack>
</form>
);
}; };
export default CreateUploadModalBody; export default CreateUploadModalBody;

View File

@ -1,6 +1,7 @@
import { Button, Tooltip } from "@mantine/core"; import { Button } from "@mantine/core";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
import toast from "../../utils/toast.util";
const DownloadAllButton = ({ shareId }: { shareId: string }) => { const DownloadAllButton = ({ shareId }: { shareId: string }) => {
const [isZipReady, setIsZipReady] = useState(false); const [isZipReady, setIsZipReady] = useState(false);
@ -25,28 +26,25 @@ const DownloadAllButton = ({ shareId }: { shareId: string }) => {
setIsZipReady(share.isZipReady); setIsZipReady(share.isZipReady);
if (share.isZipReady) clearInterval(timer); if (share.isZipReady) clearInterval(timer);
}) })
.catch(() => {}); .catch(() => clearInterval(timer));
}, 5000); }, 5000);
return () => { return () => {
clearInterval(timer); clearInterval(timer);
}; };
}, []); }, []);
if (!isZipReady)
return (
<Tooltip
position="bottom"
width={220}
withArrow
label="The share is preparing. This can take a few minutes."
>
<Button variant="outline" onClick={downloadAll} disabled>
Download all
</Button>
</Tooltip>
);
return ( return (
<Button variant="outline" loading={isLoading} onClick={downloadAll}> <Button
variant="outline"
loading={isLoading}
onClick={() => {
if (!isZipReady) {
toast.error("The share is preparing. Try again in a few minutes.");
} else {
downloadAll();
}
}}
>
Download all Download all
</Button> </Button>
); );

View File

@ -1,5 +1,5 @@
import { ActionIcon, Loader, Skeleton, Table } from "@mantine/core"; import { ActionIcon, Loader, Skeleton, Table } from "@mantine/core";
import { CircleCheck, Download } from "tabler-icons-react"; import { TbCircleCheck, TbDownload } from "react-icons/tb";;
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util"; import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
@ -39,7 +39,7 @@ const FileList = ({
file.uploadingState != "finished" ? ( file.uploadingState != "finished" ? (
<Loader size={22} /> <Loader size={22} />
) : ( ) : (
<CircleCheck color="green" size={22} /> <TbCircleCheck color="green" size={22} />
) )
) : ( ) : (
<ActionIcon <ActionIcon
@ -48,7 +48,7 @@ const FileList = ({
await shareService.downloadFile(shareId, file.id); await shareService.downloadFile(shareId, file.id);
}} }}
> >
<Download /> <TbDownload />
</ActionIcon> </ActionIcon>
)} )}
</td> </td>

View File

@ -1,14 +1,9 @@
import { import { Button, Center, createStyles, Group, Text } from "@mantine/core";
Button,
Center,
createStyles,
Group,
Text,
} from "@mantine/core";
import { Dropzone as MantineDropzone } from "@mantine/dropzone"; import { Dropzone as MantineDropzone } from "@mantine/dropzone";
import getConfig from "next/config"; import getConfig from "next/config";
import { Dispatch, ForwardedRef, SetStateAction, useRef } from "react"; import { Dispatch, ForwardedRef, SetStateAction, useRef } from "react";
import { CloudUpload, Upload } from "tabler-icons-react"; import { TbCloudUpload, TbUpload } from "react-icons/tb";
import { FileUpload } from "../../types/File.type";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util"; import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
import toast from "../../utils/toast.util"; import toast from "../../utils/toast.util";
@ -43,7 +38,7 @@ const Dropzone = ({
setFiles, setFiles,
}: { }: {
isUploading: boolean; isUploading: boolean;
setFiles: Dispatch<SetStateAction<File[]>>; setFiles: Dispatch<SetStateAction<FileUpload[]>>;
}) => { }) => {
const { classes } = useStyles(); const { classes } = useStyles();
const openRef = useRef<() => void>(); const openRef = useRef<() => void>();
@ -60,7 +55,11 @@ const Dropzone = ({
if (files.length > 100) { if (files.length > 100) {
toast.error("You can't upload more than 100 files per share."); toast.error("You can't upload more than 100 files per share.");
} else { } else {
setFiles(files); const newFiles = files.map((file) => {
(file as FileUpload).uploadingProgress = 0;
return file as FileUpload;
});
setFiles(newFiles);
} }
}} }}
className={classes.dropzone} className={classes.dropzone}
@ -68,7 +67,7 @@ const Dropzone = ({
> >
<div style={{ pointerEvents: "none" }}> <div style={{ pointerEvents: "none" }}>
<Group position="center"> <Group position="center">
<CloudUpload size={50} /> <TbCloudUpload size={50} />
</Group> </Group>
<Text align="center" weight={700} size="lg" mt="xl"> <Text align="center" weight={700} size="lg" mt="xl">
Upload files Upload files
@ -90,7 +89,7 @@ const Dropzone = ({
disabled={isUploading} disabled={isUploading}
onClick={() => openRef.current && openRef.current()} onClick={() => openRef.current && openRef.current()}
> >
{<Upload />} {<TbUpload />}
</Button> </Button>
</Center> </Center>
</div> </div>

View File

@ -1,8 +1,9 @@
import { ActionIcon, Loader, Table } from "@mantine/core"; import { ActionIcon, Table } from "@mantine/core";
import { Dispatch, SetStateAction } from "react"; import { Dispatch, SetStateAction } from "react";
import { CircleCheck, Trash } from "tabler-icons-react"; import { TbTrash } from "react-icons/tb";;
import { FileUpload } from "../../types/File.type"; import { FileUpload } from "../../types/File.type";
import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util"; import { byteStringToHumanSizeString } from "../../utils/math/byteStringToHumanSizeString.util";
import UploadProgressIndicator from "./UploadProgressIndicator";
const FileList = ({ const FileList = ({
files, files,
@ -15,27 +16,22 @@ const FileList = ({
files.splice(index, 1); files.splice(index, 1);
setFiles([...files]); setFiles([...files]);
}; };
const rows = files.map((file, i) => ( const rows = files.map((file, i) => (
<tr key={i}> <tr key={i}>
<td>{file.name}</td> <td>{file.name}</td>
<td>{byteStringToHumanSizeString(file.size.toString())}</td> <td>{byteStringToHumanSizeString(file.size.toString())}</td>
<td> <td>
{file.uploadingState ? ( {file.uploadingProgress == 0 ? (
file.uploadingState != "finished" ? (
<Loader size={22} />
) : (
<CircleCheck color="green" size={22} />
)
) : (
<ActionIcon <ActionIcon
color="red" color="red"
variant="light" variant="light"
size={25} size={25}
onClick={() => remove(i)} onClick={() => remove(i)}
> >
<Trash /> <TbTrash />
</ActionIcon> </ActionIcon>
) : (
<UploadProgressIndicator progress={file.uploadingProgress} />
)} )}
</td> </td>
</tr> </tr>

View File

@ -0,0 +1,19 @@
import { RingProgress } from "@mantine/core";
import { TbCircleCheck, TbCircleX } from "react-icons/tb";
const UploadProgressIndicator = ({ progress }: { progress: number }) => {
if (progress > 0 && progress < 100) {
return (
<RingProgress
sections={[{ value: progress, color: "victoria" }]}
thickness={3}
size={25}
/>
);
} else if (progress >= 100) {
return <TbCircleCheck color="green" size={22} />;
} else {
return <TbCircleX color="red" size={22} />;
}
};
export default UploadProgressIndicator;

View File

@ -1,86 +1,84 @@
import { import {
ActionIcon, ActionIcon,
Button, Button,
Stack, Stack,
Text, Text,
TextInput, TextInput,
Title Title,
} from "@mantine/core"; } from "@mantine/core";
import { useClipboard } from "@mantine/hooks"; import { useClipboard } from "@mantine/hooks";
import { useModals } from "@mantine/modals"; import { useModals } from "@mantine/modals";
import { ModalsContextProps } from "@mantine/modals/lib/context"; import { ModalsContextProps } from "@mantine/modals/lib/context";
import moment from "moment"; import moment from "moment";
import getConfig from "next/config";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { Copy } from "tabler-icons-react"; import { TbCopy } from "react-icons/tb";
import { Share } from "../../types/share.type"; import { Share } from "../../types/share.type";
import toast from "../../utils/toast.util"; import toast from "../../utils/toast.util";
import getConfig from "next/config";
const {publicRuntimeConfig} = getConfig(); const { publicRuntimeConfig } = getConfig();
const showCompletedUploadModal = ( const showCompletedUploadModal = (modals: ModalsContextProps, share: Share) => {
modals: ModalsContextProps, return modals.openModal({
share: Share, closeOnClickOutside: false,
) => { withCloseButton: false,
return modals.openModal({ closeOnEscape: false,
closeOnClickOutside: false, title: (
withCloseButton: false, <Stack align="stretch" spacing={0}>
closeOnEscape: false, <Title order={4}>Share ready</Title>
title: ( </Stack>
<Stack align="stretch" spacing={0}> ),
<Title order={4}>Share ready</Title> children: <Body share={share} />,
</Stack> });
),
children: <Body share={share}/>,
});
}; };
const Body = ({share}: { share: Share }) => { const Body = ({ share }: { share: Share }) => {
const clipboard = useClipboard({timeout: 500}); const clipboard = useClipboard({ timeout: 500 });
const modals = useModals(); const modals = useModals();
const router = useRouter(); const router = useRouter();
const link = `${window.location.origin}/share/${share.id}`; const link = `${window.location.origin}/share/${share.id}`;
return ( return (
<Stack align="stretch"> <Stack align="stretch">
<TextInput <TextInput
variant="filled" variant="filled"
value={link} value={link}
rightSection={ rightSection={
<ActionIcon <ActionIcon
onClick={() => { onClick={() => {
clipboard.copy(link); clipboard.copy(link);
toast.success("Your link was copied to the keyboard."); toast.success("Your link was copied to the keyboard.");
}} }}
> >
<Copy/> <TbCopy />
</ActionIcon> </ActionIcon>
} }
/> />
<Text <Text
size="xs" size="xs"
sx={(theme) => ({ sx={(theme) => ({
color: theme.colors.gray[6], color: theme.colors.gray[6],
})} })}
> >
{/* If our share.expiration is timestamp 0, show a different message */} {/* If our share.expiration is timestamp 0, show a different message */}
{moment(share.expiration).unix() === 0 {moment(share.expiration).unix() === 0
? "This share will never expire." ? "This share will never expire."
: `This share will expire on ${ : `This share will expire on ${
(publicRuntimeConfig.TWELVE_HOUR_TIME === "true") publicRuntimeConfig.TWELVE_HOUR_TIME === "true"
? moment(share.expiration).format("MMMM Do YYYY, h:mm a") ? moment(share.expiration).format("MMMM Do YYYY, h:mm a")
: moment(share.expiration).format("MMMM DD YYYY, HH:mm")}`} : moment(share.expiration).format("MMMM DD YYYY, HH:mm")
</Text> }`}
</Text>
<Button <Button
onClick={() => { onClick={() => {
modals.closeAll(); modals.closeAll();
router.push("/upload"); router.push("/upload");
}} }}
> >
Done Done
</Button> </Button>
</Stack> </Stack>
); );
}; };
export default showCompletedUploadModal; export default showCompletedUploadModal;

View File

@ -8,9 +8,6 @@ import {
import { useColorScheme } from "@mantine/hooks"; import { useColorScheme } from "@mantine/hooks";
import { ModalsProvider } from "@mantine/modals"; import { ModalsProvider } from "@mantine/modals";
import { NotificationsProvider } from "@mantine/notifications"; import { NotificationsProvider } from "@mantine/notifications";
import { setCookies } from "cookies-next";
import { GetServerSidePropsContext } from "next";
import cookies from "next-cookies";
import type { AppProps } from "next/app"; import type { AppProps } from "next/app";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Footer from "../components/Footer"; import Footer from "../components/Footer";
@ -23,14 +20,10 @@ import globalStyle from "../styles/mantine.style";
import { CurrentUser } from "../types/user.type"; import { CurrentUser } from "../types/user.type";
import { GlobalLoadingContext } from "../utils/loading.util"; import { GlobalLoadingContext } from "../utils/loading.util";
function App(props: AppProps & { colorScheme: ColorScheme }) { function App({ Component, pageProps }: AppProps) {
const { Component, pageProps } = props;
const systemTheme = useColorScheme(); const systemTheme = useColorScheme();
const [colorScheme, setColorScheme] = useState<ColorScheme>( const [colorScheme, setColorScheme] = useState<ColorScheme>();
props.colorScheme
);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<CurrentUser | null>(null); const [user, setUser] = useState<CurrentUser | null>(null);
@ -47,9 +40,6 @@ function App(props: AppProps & { colorScheme: ColorScheme }) {
}, []); }, []);
useEffect(() => { useEffect(() => {
setCookies("color-schema", systemTheme, {
maxAge: 60 * 60 * 24 * 30,
});
setColorScheme(systemTheme); setColorScheme(systemTheme);
}, [systemTheme]); }, [systemTheme]);
@ -87,9 +77,3 @@ function App(props: AppProps & { colorScheme: ColorScheme }) {
} }
export default App; export default App;
App.getInitialProps = ({ ctx }: { ctx: GetServerSidePropsContext }) => {
return {
colorScheme: cookies(ctx)["color-schema"] || "light",
};
};

View File

@ -1,131 +1,140 @@
import { import {
ActionIcon, ActionIcon,
Button, Button,
Center, Center,
Group, Group,
LoadingOverlay, LoadingOverlay,
Space, Space,
Stack, Stack,
Table, Table,
Text, Text,
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import {useClipboard} from "@mantine/hooks"; import { useClipboard } from "@mantine/hooks";
import {useModals} from "@mantine/modals"; import { useModals } from "@mantine/modals";
import {NextLink} from "@mantine/next"; import { NextLink } from "@mantine/next";
import moment from "moment"; import moment from "moment";
import {useEffect, useState} from "react"; import { useRouter } from "next/router";
import {Link, Trash} from "tabler-icons-react"; import { useEffect, useState } from "react";
import { TbLink, TbTrash } from "react-icons/tb";
import Meta from "../../components/Meta"; import Meta from "../../components/Meta";
import useUser from "../../hooks/user.hook";
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
import {MyShare} from "../../types/share.type"; import { MyShare } from "../../types/share.type";
import toast from "../../utils/toast.util"; import toast from "../../utils/toast.util";
import getConfig from "next/config"; import getConfig from "next/config";
const {publicRuntimeConfig} = getConfig(); const { publicRuntimeConfig } = getConfig();
const MyShares = () => { const MyShares = () => {
const modals = useModals(); const modals = useModals();
const clipboard = useClipboard(); const clipboard = useClipboard();
const router = useRouter();
const user = useUser();
const [shares, setShares] = useState<MyShare[]>(); const [shares, setShares] = useState<MyShare[]>();
useEffect(() => { useEffect(() => {
shareService.getMyShares().then((shares) => setShares(shares)); shareService.getMyShares().then((shares) => setShares(shares));
}, []); }, []);
if (!shares) return <LoadingOverlay visible/>; if (!user) {
router.replace("/");
} else {
if (!shares) return <LoadingOverlay visible />;
return ( return (
<> <>
<Meta title="My shares"/> <Meta title="My shares" />
<Title mb={30} order={3}> <Title mb={30} order={3}>
My shares My shares
</Title> </Title>
{shares.length == 0 ? ( {shares.length == 0 ? (
<Center style={{height: "70vh"}}> <Center style={{ height: "70vh" }}>
<Stack align="center" spacing={10}> <Stack align="center" spacing={10}>
<Title order={3}>It's empty here 👀</Title> <Title order={3}>It's empty here 👀</Title>
<Text>You don't have any shares.</Text> <Text>You don't have any shares.</Text>
<Space h={5}/> <Space h={5} />
<Button component={NextLink} href="/upload" variant="light"> <Button component={NextLink} href="/upload" variant="light">
Create one Create one
</Button> </Button>
</Stack> </Stack>
</Center> </Center>
) : ( ) : (
<Table> <Table>
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Visitors</th> <th>Visitors</th>
<th>Expires at</th> <th>Expires at</th>
<th></th> <th></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{shares.map((share) => ( {shares.map((share) => (
<tr key={share.id}> <tr key={share.id}>
<td>{share.id}</td> <td>{share.id}</td>
<td>{share.views}</td> <td>{share.views}</td>
<td> <td>
{moment(share.expiration).unix() === 0 {moment(share.expiration).unix() === 0
? "Never" ? "Never"
: (publicRuntimeConfig.TWELVE_HOUR_TIME === "true") : publicRuntimeConfig.TWELVE_HOUR_TIME === "true"
? moment(share.expiration).format("MMMM Do YYYY, h:mm a") ? moment(share.expiration).format("MMMM Do YYYY, h:mm a")
: moment(share.expiration).format("MMMM DD YYYY, HH:mm") : moment(share.expiration).format("MMMM DD YYYY, HH:mm")}
} </td>
</td> <td>
<td> <Group position="right">
<Group position="right"> <ActionIcon
<ActionIcon color="victoria"
color="victoria" variant="light"
variant="light" size={25}
size={25} onClick={() => {
onClick={() => { clipboard.copy(
clipboard.copy( `${window.location.origin}/share/${share.id}`
`${window.location.origin}/share/${share.id}` );
); toast.success(
toast.success("Your link was copied to the keyboard."); "Your link was copied to the keyboard."
}} );
> }}
<Link/> >
</ActionIcon> <TbLink />
<ActionIcon </ActionIcon>
color="red" <ActionIcon
variant="light" color="red"
size={25} variant="light"
onClick={() => { size={25}
modals.openConfirmModal({ onClick={() => {
title: `Delete share ${share.id}`, modals.openConfirmModal({
children: ( title: `Delete share ${share.id}`,
<Text size="sm"> children: (
Do you really want to delete this share? <Text size="sm">
</Text> Do you really want to delete this share?
), </Text>
confirmProps: { ),
color: "red", confirmProps: {
}, color: "red",
labels: {confirm: "Confirm", cancel: "Cancel"}, },
onConfirm: () => { labels: { confirm: "Confirm", cancel: "Cancel" },
shareService.remove(share.id); onConfirm: () => {
setShares( shareService.remove(share.id);
shares.filter((item) => item.id !== share.id) setShares(
); shares.filter((item) => item.id !== share.id)
}, );
}); },
}} });
> }}
<Trash/> >
</ActionIcon> <TbTrash />
</Group> </ActionIcon>
</td> </Group>
</tr> </td>
))} </tr>
</tbody> ))}
</Table> </tbody>
)} </Table>
</> )}
</>
); );
}
}; };
export default MyShares; export default MyShares;

View File

@ -12,10 +12,9 @@ import { NextLink } from "@mantine/next";
import getConfig from "next/config"; import getConfig from "next/config";
import Image from "next/image"; import Image from "next/image";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { Check } from "tabler-icons-react"; import { TbCheck } from "react-icons/tb";
import Meta from "../components/Meta"; import Meta from "../components/Meta";
import useUser from "../hooks/user.hook"; import useUser from "../hooks/user.hook";
const { publicRuntimeConfig } = getConfig(); const { publicRuntimeConfig } = getConfig();
const useStyles = createStyles((theme) => ({ const useStyles = createStyles((theme) => ({
@ -101,7 +100,7 @@ export default function Home() {
size="sm" size="sm"
icon={ icon={
<ThemeIcon size={20} radius="xl"> <ThemeIcon size={20} radius="xl">
<Check size={12} /> <TbCheck size={12} />
</ThemeIcon> </ThemeIcon>
} }
> >

View File

@ -1,6 +1,6 @@
import { Group } from "@mantine/core"; import { Group } from "@mantine/core";
import { useModals } from "@mantine/modals"; import { useModals } from "@mantine/modals";
import { useRouter } from "next/router"; import { GetServerSidePropsContext } from "next";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Meta from "../../components/Meta"; import Meta from "../../components/Meta";
import DownloadAllButton from "../../components/share/DownloadAllButton"; import DownloadAllButton from "../../components/share/DownloadAllButton";
@ -9,18 +9,31 @@ import showEnterPasswordModal from "../../components/share/showEnterPasswordModa
import showErrorModal from "../../components/share/showErrorModal"; import showErrorModal from "../../components/share/showErrorModal";
import shareService from "../../services/share.service"; import shareService from "../../services/share.service";
const Share = () => { export function getServerSideProps(context: GetServerSidePropsContext) {
const router = useRouter(); return {
props: { shareId: context.params!.shareId },
};
}
const Share = ({ shareId }: { shareId: string }) => {
const modals = useModals(); const modals = useModals();
const shareId = router.query.shareId as string;
const [fileList, setFileList] = useState<any[]>([]); const [fileList, setFileList] = useState<any[]>([]);
const submitPassword = async (password: string) => { const getShareToken = async (password?: string) => {
await shareService await shareService
.exchangeSharePasswordWithToken(shareId, password) .getShareToken(shareId, password)
.then(() => { .then(() => {
modals.closeAll(); modals.closeAll();
getFiles(); getFiles();
})
.catch((e) => {
if (e.response.data.error == "share_max_views_exceeded") {
showErrorModal(
modals,
"Visitor limit exceeded",
"The visitor limit from this share has been exceeded."
);
}
}); });
}; };
@ -38,14 +51,10 @@ const Share = () => {
"Not found", "Not found",
"This share can't be found. Please check your link." "This share can't be found. Please check your link."
); );
} else if (error == "share_password_required") {
showEnterPasswordModal(modals, getShareToken);
} else if (error == "share_token_required") { } else if (error == "share_token_required") {
showEnterPasswordModal(modals, submitPassword); getShareToken();
} else if (error == "share_max_views_exceeded") {
showErrorModal(
modals,
"Visitor limit exceeded",
"The visitor limit from this share has been exceeded."
);
} else if (error == "forbidden") { } else if (error == "forbidden") {
showErrorModal( showErrorModal(
modals, modals,
@ -69,9 +78,7 @@ const Share = () => {
description="Look what I've shared with you." description="Look what I've shared with you."
/> />
<Group position="right" mb="lg"> <Group position="right" mb="lg">
<DownloadAllButton <DownloadAllButton shareId={shareId} />
shareId={shareId}
/>
</Group> </Group>
<FileList <FileList
files={fileList} files={fileList}

View File

@ -28,39 +28,61 @@ const Upload = () => {
security: ShareSecurity security: ShareSecurity
) => { ) => {
setisUploading(true); setisUploading(true);
try { try {
files.forEach((file) => { setFiles((files) =>
file.uploadingState = "inProgress"; files.map((file) => {
}); file.uploadingProgress = 1;
setFiles([...files]); return file;
})
);
const share = await shareService.create(id, expiration, security); const share = await shareService.create(id, expiration, security);
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
await shareService.uploadFile(share.id, files[i]); const progressCallBack = (bytesProgress: number) => {
setFiles((files) => {
return files.map((file, callbackIndex) => {
if (i == callbackIndex) {
file.uploadingProgress = Math.round(
(100 * bytesProgress) / files[i].size
);
}
return file;
});
});
};
files[i].uploadingState = "finished"; try {
setFiles([...files]); await shareService.uploadFile(share.id, files[i], progressCallBack);
if (!files.some((f) => f.uploadingState == "inProgress")) { } catch {
await shareService.completeShare(share.id); files[i].uploadingProgress = -1;
}
if (
files.every(
(file) =>
file.uploadingProgress >= 100 || file.uploadingProgress == -1
)
) {
const fileErrorCount = files.filter(
(file) => file.uploadingProgress == -1
).length;
setisUploading(false); setisUploading(false);
showCompletedUploadModal( if (fileErrorCount > 0) {
modals, toast.error(
`${fileErrorCount} file(s) failed to upload. Try again.`
share );
); } else {
setFiles([]); await shareService.completeShare(share.id);
showCompletedUploadModal(modals, share);
setFiles([]);
}
} }
} }
} catch (e) { } catch (e) {
files.forEach((file) => {
file.uploadingState = undefined;
});
if (axios.isAxiosError(e)) { if (axios.isAxiosError(e)) {
toast.error(e.response?.data?.message ?? "An unkown error occured."); toast.error(e.response?.data?.message ?? "An unkown error occured.");
} else { } else {
toast.error("An unkown error occured."); toast.error("An unkown error occured.");
} }
setFiles([...files]);
setisUploading(false); setisUploading(false);
} }
}; };

View File

@ -44,9 +44,8 @@ const getMyShares = async (): Promise<MyShare[]> => {
return (await api.get("shares")).data; return (await api.get("shares")).data;
}; };
const exchangeSharePasswordWithToken = async (id: string, password: string) => { const getShareToken = async (id: string, password?: string) => {
const { token } = (await api.post(`/shares/${id}/password`, { password })) const { token } = (await api.post(`/shares/${id}/token`, { password })).data;
.data;
localStorage.setItem(`share_${id}_token`, token); localStorage.setItem(`share_${id}_token`, token);
}; };
@ -68,16 +67,26 @@ const downloadFile = async (shareId: string, fileId: string) => {
window.location.href = await getFileDownloadUrl(shareId, fileId); window.location.href = await getFileDownloadUrl(shareId, fileId);
}; };
const uploadFile = async (shareId: string, file: File) => { const uploadFile = async (
var formData = new FormData(); shareId: string,
file: File,
progressCallBack: (uploadingProgress: number) => void
) => {
let formData = new FormData();
formData.append("file", file); formData.append("file", file);
return (await api.post(`shares/${shareId}/files`, formData)).data;
return (
await api.post(`shares/${shareId}/files`, formData, {
onUploadProgress: (progressEvent) =>
progressCallBack(progressEvent.loaded),
})
).data;
}; };
export default { export default {
create, create,
completeShare, completeShare,
exchangeSharePasswordWithToken, getShareToken,
get, get,
remove, remove,
getMetaData, getMetaData,

View File

@ -1,2 +1 @@
export type FileUpload = File & { uploadingState?: UploadState }; export type FileUpload = File & { uploadingProgress: number };
export type UploadState = "finished" | "inProgress" | undefined;

View File

@ -1,19 +1,18 @@
import { showNotification } from "@mantine/notifications"; import { showNotification } from "@mantine/notifications";
import { Check, X } from "tabler-icons-react"; import { TbCheck, TbX } from "react-icons/tb";
const error = (message: string) => const error = (message: string) =>
showNotification({ showNotification({
icon: <X />, icon: <TbX />,
color: "red", color: "red",
radius: "md", radius: "md",
title: "Error", title: "Error",
message: message, message: message,
}); });
const success = (message: string) => const success = (message: string) =>
showNotification({ showNotification({
icon: <Check />, icon: <TbCheck />,
color: "green", color: "green",
radius: "md", radius: "md",
title: "Success", title: "Success",