server: add and run prettier
This commit is contained in:
parent
056a2bd3ce
commit
2823c217ea
19 changed files with 668 additions and 553 deletions
7
server/.prettierrc
Normal file
7
server/.prettierrc
Normal file
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"semi": false,
|
||||
"trailingComma": "none",
|
||||
"singleQuote": false,
|
||||
"printWidth": 80,
|
||||
"useTabs": true
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
import * as dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
import * as dotenv from "dotenv"
|
||||
dotenv.config()
|
||||
|
||||
import './src/server';
|
||||
import "./src/server"
|
||||
|
|
|
@ -7,7 +7,8 @@
|
|||
"start": "ts-node index.ts",
|
||||
"dev": "nodemon index.ts",
|
||||
"build": "tsc -p .",
|
||||
"migrate": "sequelize db:migrate"
|
||||
"migrate": "sequelize db:migrate",
|
||||
"lint": "prettier --config .prettierrc 'src/**/*.ts' 'index.ts' --write"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
|
@ -40,6 +41,7 @@
|
|||
"@types/marked": "^4.0.3",
|
||||
"@types/node": "^17.0.21",
|
||||
"@types/react-dom": "^17.0.14",
|
||||
"prettier": "^2.6.0",
|
||||
"ts-node": "^10.6.0",
|
||||
"tsconfig-paths": "^3.14.1",
|
||||
"tslint": "^6.1.3",
|
||||
|
|
|
@ -1,29 +1,30 @@
|
|||
import * as express from 'express';
|
||||
import * as bodyParser from 'body-parser';
|
||||
import * as errorhandler from 'strong-error-handler';
|
||||
import * as cors from 'cors';
|
||||
import { posts, users, auth, files } from '@routes/index';
|
||||
import { errors } from 'celebrate'
|
||||
import * as express from "express"
|
||||
import * as bodyParser from "body-parser"
|
||||
import * as errorhandler from "strong-error-handler"
|
||||
import * as cors from "cors"
|
||||
import { posts, users, auth, files } from "@routes/index"
|
||||
import { errors } from "celebrate"
|
||||
|
||||
export const app = express();
|
||||
export const app = express()
|
||||
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
app.use(bodyParser.json({ limit: '5mb' }));
|
||||
app.use(bodyParser.urlencoded({ extended: true }))
|
||||
app.use(bodyParser.json({ limit: "5mb" }))
|
||||
|
||||
const corsOptions = {
|
||||
origin: `http://localhost:3001`,
|
||||
};
|
||||
app.use(cors(corsOptions));
|
||||
origin: `http://localhost:3001`
|
||||
}
|
||||
app.use(cors(corsOptions))
|
||||
|
||||
app.use("/auth", auth)
|
||||
app.use("/posts", posts)
|
||||
app.use("/users", users)
|
||||
app.use("/files", files)
|
||||
|
||||
app.use(errors());
|
||||
|
||||
app.use(errorhandler({
|
||||
debug: process.env.ENV !== 'production',
|
||||
log: true,
|
||||
}));
|
||||
app.use(errors())
|
||||
|
||||
app.use(
|
||||
errorhandler({
|
||||
debug: process.env.ENV !== "production",
|
||||
log: true
|
||||
})
|
||||
)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
export default {
|
||||
port: process.env.PORT || 3000,
|
||||
jwt_secret: process.env.JWT_SECRET || 'myjwtsecret',
|
||||
jwt_secret: process.env.JWT_SECRET || "myjwtsecret"
|
||||
}
|
||||
|
|
|
@ -1,27 +1,31 @@
|
|||
import { NextFunction, Request, Response } from 'express';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import config from '../config';
|
||||
import { User as UserModel } from '../models/User';
|
||||
import { NextFunction, Request, Response } from "express"
|
||||
import * as jwt from "jsonwebtoken"
|
||||
import config from "../config"
|
||||
import { User as UserModel } from "../models/User"
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface UserJwtRequest extends Request {
|
||||
user?: User;
|
||||
user?: User
|
||||
}
|
||||
|
||||
export default function authenticateToken(req: UserJwtRequest, res: Response, next: NextFunction) {
|
||||
const authHeader = req.headers['authorization']
|
||||
const token = authHeader && authHeader.split(' ')[1]
|
||||
export default function authenticateToken(
|
||||
req: UserJwtRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const authHeader = req.headers["authorization"]
|
||||
const token = authHeader && authHeader.split(" ")[1]
|
||||
|
||||
if (token == null) return res.sendStatus(401)
|
||||
|
||||
jwt.verify(token, config.jwt_secret, async (err: any, user: any) => {
|
||||
if (err) return res.sendStatus(403)
|
||||
const userObj = await UserModel.findByPk(user.id);
|
||||
const userObj = await UserModel.findByPk(user.id)
|
||||
if (!userObj) {
|
||||
return res.sendStatus(403);
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
req.user = user
|
||||
|
||||
|
|
|
@ -1,12 +1,16 @@
|
|||
import { NextFunction, Request, Response } from 'express';
|
||||
import { NextFunction, Request, Response } from "express"
|
||||
|
||||
const key = process.env.SECRET_KEY;
|
||||
const key = process.env.SECRET_KEY
|
||||
if (!key) {
|
||||
throw new Error('SECRET_KEY is not set.');
|
||||
throw new Error("SECRET_KEY is not set.")
|
||||
}
|
||||
|
||||
export default function authenticateToken(req: Request, res: Response, next: NextFunction) {
|
||||
const requestKey = req.headers['x-secret-key']
|
||||
export default function authenticateToken(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const requestKey = req.headers["x-secret-key"]
|
||||
if (requestKey !== key) {
|
||||
return res.sendStatus(401)
|
||||
}
|
||||
|
|
|
@ -1,21 +1,33 @@
|
|||
import { BelongsTo, Column, CreatedAt, DataType, ForeignKey, IsUUID, Model, PrimaryKey, Scopes, Table, Unique } from 'sequelize-typescript';
|
||||
import { Post } from './Post';
|
||||
import { User } from './User';
|
||||
|
||||
import {
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
ForeignKey,
|
||||
IsUUID,
|
||||
Model,
|
||||
PrimaryKey,
|
||||
Scopes,
|
||||
Table,
|
||||
Unique
|
||||
} from "sequelize-typescript"
|
||||
import { Post } from "./Post"
|
||||
import { User } from "./User"
|
||||
|
||||
@Scopes(() => ({
|
||||
full: {
|
||||
include: [{
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
through: { attributes: [] },
|
||||
through: { attributes: [] }
|
||||
},
|
||||
{
|
||||
model: Post,
|
||||
through: { attributes: [] },
|
||||
}]
|
||||
through: { attributes: [] }
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
|
||||
@Table
|
||||
export class File extends Model {
|
||||
@IsUUID(4)
|
||||
|
@ -23,31 +35,31 @@ export class File extends Model {
|
|||
@Unique
|
||||
@Column({
|
||||
type: DataType.UUID,
|
||||
defaultValue: DataType.UUIDV4,
|
||||
defaultValue: DataType.UUIDV4
|
||||
})
|
||||
id!: string
|
||||
|
||||
@Column
|
||||
title!: string;
|
||||
title!: string
|
||||
|
||||
@Column
|
||||
content!: string;
|
||||
content!: string
|
||||
|
||||
@Column
|
||||
sha!: string;
|
||||
sha!: string
|
||||
|
||||
@Column
|
||||
html!: string;
|
||||
html!: string
|
||||
|
||||
@ForeignKey(() => User)
|
||||
@BelongsTo(() => User, 'userId')
|
||||
user!: User;
|
||||
@BelongsTo(() => User, "userId")
|
||||
user!: User
|
||||
|
||||
@ForeignKey(() => Post)
|
||||
@BelongsTo(() => Post, 'postId')
|
||||
post!: Post;
|
||||
@BelongsTo(() => Post, "postId")
|
||||
post!: Post
|
||||
|
||||
@CreatedAt
|
||||
@Column
|
||||
createdAt!: Date;
|
||||
createdAt!: Date
|
||||
}
|
||||
|
|
|
@ -1,27 +1,43 @@
|
|||
import { BelongsToMany, Column, CreatedAt, DataType, HasMany, IsUUID, Model, PrimaryKey, Scopes, Table, Unique, UpdatedAt } from 'sequelize-typescript';
|
||||
import { PostAuthor } from './PostAuthor';
|
||||
import { User } from './User';
|
||||
import { File } from './File';
|
||||
import {
|
||||
BelongsToMany,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
HasMany,
|
||||
IsUUID,
|
||||
Model,
|
||||
PrimaryKey,
|
||||
Scopes,
|
||||
Table,
|
||||
Unique,
|
||||
UpdatedAt
|
||||
} from "sequelize-typescript"
|
||||
import { PostAuthor } from "./PostAuthor"
|
||||
import { User } from "./User"
|
||||
import { File } from "./File"
|
||||
|
||||
@Scopes(() => ({
|
||||
user: {
|
||||
include: [{
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
through: { attributes: [] },
|
||||
}],
|
||||
through: { attributes: [] }
|
||||
}
|
||||
]
|
||||
},
|
||||
full: {
|
||||
include: [{
|
||||
include: [
|
||||
{
|
||||
model: User,
|
||||
through: { attributes: [] },
|
||||
through: { attributes: [] }
|
||||
},
|
||||
{
|
||||
model: File,
|
||||
through: { attributes: [] },
|
||||
}]
|
||||
through: { attributes: [] }
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
|
||||
@Table
|
||||
export class Post extends Model {
|
||||
@IsUUID(4)
|
||||
|
@ -29,30 +45,30 @@ export class Post extends Model {
|
|||
@Unique
|
||||
@Column({
|
||||
type: DataType.UUID,
|
||||
defaultValue: DataType.UUIDV4,
|
||||
defaultValue: DataType.UUIDV4
|
||||
})
|
||||
id!: string
|
||||
|
||||
@Column
|
||||
title!: string;
|
||||
title!: string
|
||||
|
||||
@BelongsToMany(() => User, () => PostAuthor)
|
||||
users?: User[];
|
||||
users?: User[]
|
||||
|
||||
@HasMany(() => File, { constraints: false })
|
||||
files?: File[];
|
||||
files?: File[]
|
||||
|
||||
@CreatedAt
|
||||
@Column
|
||||
createdAt!: Date;
|
||||
createdAt!: Date
|
||||
|
||||
@Column
|
||||
visibility!: string;
|
||||
visibility!: string
|
||||
|
||||
@Column
|
||||
password?: string;
|
||||
password?: string
|
||||
|
||||
@UpdatedAt
|
||||
@Column
|
||||
updatedAt!: Date;
|
||||
updatedAt!: Date
|
||||
}
|
||||
|
|
|
@ -1,6 +1,15 @@
|
|||
import { Model, Column, Table, ForeignKey, IsUUID, PrimaryKey, DataType, Unique } from "sequelize-typescript";
|
||||
import { Post } from "./Post";
|
||||
import { User } from "./User";
|
||||
import {
|
||||
Model,
|
||||
Column,
|
||||
Table,
|
||||
ForeignKey,
|
||||
IsUUID,
|
||||
PrimaryKey,
|
||||
DataType,
|
||||
Unique
|
||||
} from "sequelize-typescript"
|
||||
import { Post } from "./Post"
|
||||
import { User } from "./User"
|
||||
|
||||
@Table
|
||||
export class PostAuthor extends Model {
|
||||
|
@ -9,15 +18,15 @@ export class PostAuthor extends Model {
|
|||
@Unique
|
||||
@Column({
|
||||
type: DataType.UUID,
|
||||
defaultValue: DataType.UUIDV4,
|
||||
defaultValue: DataType.UUIDV4
|
||||
})
|
||||
id!: string
|
||||
|
||||
@ForeignKey(() => Post)
|
||||
@Column
|
||||
postId!: number;
|
||||
postId!: number
|
||||
|
||||
@ForeignKey(() => User)
|
||||
@Column
|
||||
authorId!: number;
|
||||
authorId!: number
|
||||
}
|
||||
|
|
|
@ -1,15 +1,27 @@
|
|||
import { Model, Column, Table, BelongsToMany, Scopes, CreatedAt, UpdatedAt, IsUUID, PrimaryKey, DataType, Unique } from "sequelize-typescript";
|
||||
import { Post } from "./Post";
|
||||
import { PostAuthor } from "./PostAuthor";
|
||||
import {
|
||||
Model,
|
||||
Column,
|
||||
Table,
|
||||
BelongsToMany,
|
||||
Scopes,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
IsUUID,
|
||||
PrimaryKey,
|
||||
DataType,
|
||||
Unique
|
||||
} from "sequelize-typescript"
|
||||
import { Post } from "./Post"
|
||||
import { PostAuthor } from "./PostAuthor"
|
||||
|
||||
@Scopes(() => ({
|
||||
posts: {
|
||||
include: [
|
||||
{
|
||||
model: Post,
|
||||
through: { attributes: [] },
|
||||
},
|
||||
],
|
||||
through: { attributes: [] }
|
||||
}
|
||||
]
|
||||
},
|
||||
withoutPassword: {
|
||||
attributes: {
|
||||
|
@ -17,7 +29,6 @@ import { PostAuthor } from "./PostAuthor";
|
|||
}
|
||||
}
|
||||
}))
|
||||
|
||||
@Table
|
||||
export class User extends Model {
|
||||
@IsUUID(4)
|
||||
|
@ -25,24 +36,24 @@ export class User extends Model {
|
|||
@Unique
|
||||
@Column({
|
||||
type: DataType.UUID,
|
||||
defaultValue: DataType.UUIDV4,
|
||||
defaultValue: DataType.UUIDV4
|
||||
})
|
||||
id!: string
|
||||
|
||||
@Column
|
||||
username!: string;
|
||||
username!: string
|
||||
|
||||
@Column
|
||||
password!: string;
|
||||
password!: string
|
||||
|
||||
@BelongsToMany(() => Post, () => PostAuthor)
|
||||
posts?: Post[];
|
||||
posts?: Post[]
|
||||
|
||||
@CreatedAt
|
||||
@Column
|
||||
createdAt!: Date;
|
||||
createdAt!: Date
|
||||
|
||||
@UpdatedAt
|
||||
@Column
|
||||
updatedAt!: Date;
|
||||
updatedAt!: Date
|
||||
}
|
||||
|
|
|
@ -1,9 +1,12 @@
|
|||
import { Sequelize } from 'sequelize-typescript';
|
||||
import { Sequelize } from "sequelize-typescript"
|
||||
|
||||
export const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
database: 'drift',
|
||||
storage: process.env.MEMORY_DB === "true" ? ":memory:" : __dirname + '/../../drift.sqlite',
|
||||
models: [__dirname + '/models'],
|
||||
host: 'localhost',
|
||||
});
|
||||
dialect: "sqlite",
|
||||
database: "drift",
|
||||
storage:
|
||||
process.env.MEMORY_DB === "true"
|
||||
? ":memory:"
|
||||
: __dirname + "/../../drift.sqlite",
|
||||
models: [__dirname + "/models"],
|
||||
host: "localhost"
|
||||
})
|
||||
|
|
|
@ -1,66 +1,82 @@
|
|||
import { Router } from 'express'
|
||||
import { Router } from "express"
|
||||
import { genSalt, hash, compare } from "bcrypt"
|
||||
import { User } from '@lib/models/User'
|
||||
import { sign } from 'jsonwebtoken'
|
||||
import config from '@lib/config'
|
||||
import jwt from '@lib/middleware/jwt'
|
||||
import { celebrate, Joi } from 'celebrate'
|
||||
import { User } from "@lib/models/User"
|
||||
import { sign } from "jsonwebtoken"
|
||||
import config from "@lib/config"
|
||||
import jwt from "@lib/middleware/jwt"
|
||||
import { celebrate, Joi } from "celebrate"
|
||||
|
||||
const NO_EMPTY_SPACE_REGEX = /^\S*$/
|
||||
|
||||
export const requiresServerPassword = (process.env.MEMORY_DB || process.env.ENV === 'production') && !!process.env.REGISTRATION_PASSWORD
|
||||
export const requiresServerPassword =
|
||||
(process.env.MEMORY_DB || process.env.ENV === "production") &&
|
||||
!!process.env.REGISTRATION_PASSWORD
|
||||
console.log(`Registration password required: ${requiresServerPassword}`)
|
||||
|
||||
export const auth = Router()
|
||||
|
||||
const validateAuthPayload = (username: string, password: string, serverPassword?: string): void => {
|
||||
const validateAuthPayload = (
|
||||
username: string,
|
||||
password: string,
|
||||
serverPassword?: string
|
||||
): void => {
|
||||
if (!NO_EMPTY_SPACE_REGEX.test(username) || password.length < 6) {
|
||||
throw new Error("Authentication data does not fulfill requirements")
|
||||
}
|
||||
|
||||
if (requiresServerPassword) {
|
||||
if (!serverPassword || process.env.REGISTRATION_PASSWORD !== serverPassword) {
|
||||
throw new Error("Server password is incorrect. Please contact the server administrator.")
|
||||
if (
|
||||
!serverPassword ||
|
||||
process.env.REGISTRATION_PASSWORD !== serverPassword
|
||||
) {
|
||||
throw new Error(
|
||||
"Server password is incorrect. Please contact the server administrator."
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auth.post('/signup',
|
||||
auth.post(
|
||||
"/signup",
|
||||
celebrate({
|
||||
body: {
|
||||
username: Joi.string().required(),
|
||||
password: Joi.string().required(),
|
||||
serverPassword: Joi.string().required().allow('', null),
|
||||
serverPassword: Joi.string().required().allow("", null)
|
||||
}
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
validateAuthPayload(req.body.username, req.body.password, req.body.serverPassword)
|
||||
const username = req.body.username.toLowerCase();
|
||||
validateAuthPayload(
|
||||
req.body.username,
|
||||
req.body.password,
|
||||
req.body.serverPassword
|
||||
)
|
||||
const username = req.body.username.toLowerCase()
|
||||
|
||||
const existingUser = await User.findOne({
|
||||
where: { username: username },
|
||||
});
|
||||
where: { username: username }
|
||||
})
|
||||
if (existingUser) {
|
||||
throw new Error("Username already exists");
|
||||
throw new Error("Username already exists")
|
||||
}
|
||||
|
||||
const salt = await genSalt(10);
|
||||
const salt = await genSalt(10)
|
||||
const user = {
|
||||
username: username as string,
|
||||
password: await hash(req.body.password, salt),
|
||||
};
|
||||
password: await hash(req.body.password, salt)
|
||||
}
|
||||
|
||||
const created_user = await User.create(user);
|
||||
const created_user = await User.create(user)
|
||||
|
||||
const token = generateAccessToken(created_user.id);
|
||||
const token = generateAccessToken(created_user.id)
|
||||
|
||||
res.status(201).json({ token: token, userId: created_user.id });
|
||||
res.status(201).json({ token: token, userId: created_user.id })
|
||||
} catch (e) {
|
||||
next(e);
|
||||
next(e)
|
||||
}
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
auth.post(
|
||||
"/signin",
|
||||
|
@ -68,54 +84,54 @@ auth.post(
|
|||
body: {
|
||||
username: Joi.string().required(),
|
||||
password: Joi.string().required(),
|
||||
serverPassword: Joi.string().required().allow('', null),
|
||||
},
|
||||
serverPassword: Joi.string().required().allow("", null)
|
||||
}
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
const error = "User does not exist or password is incorrect";
|
||||
const errorToThrow = new Error(error);
|
||||
const error = "User does not exist or password is incorrect"
|
||||
const errorToThrow = new Error(error)
|
||||
try {
|
||||
if (!req.body.username || !req.body.password) {
|
||||
throw errorToThrow;
|
||||
throw errorToThrow
|
||||
}
|
||||
|
||||
const username = req.body.username.toLowerCase();
|
||||
const user = await User.findOne({ where: { username: username } });
|
||||
const username = req.body.username.toLowerCase()
|
||||
const user = await User.findOne({ where: { username: username } })
|
||||
if (!user) {
|
||||
throw errorToThrow;
|
||||
throw errorToThrow
|
||||
}
|
||||
|
||||
const password_valid = await compare(req.body.password, user.password);
|
||||
const password_valid = await compare(req.body.password, user.password)
|
||||
if (password_valid) {
|
||||
const token = generateAccessToken(user.id);
|
||||
res.status(200).json({ token: token, userId: user.id });
|
||||
const token = generateAccessToken(user.id)
|
||||
res.status(200).json({ token: token, userId: user.id })
|
||||
} else {
|
||||
throw errorToThrow;
|
||||
throw errorToThrow
|
||||
}
|
||||
} catch (e) {
|
||||
next(e);
|
||||
next(e)
|
||||
}
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
auth.get("/requires-passcode", async (req, res, next) => {
|
||||
if (requiresServerPassword) {
|
||||
res.status(200).json({ requiresPasscode: true });
|
||||
res.status(200).json({ requiresPasscode: true })
|
||||
} else {
|
||||
res.status(200).json({ requiresPasscode: false });
|
||||
res.status(200).json({ requiresPasscode: false })
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
function generateAccessToken(id: string) {
|
||||
return sign({ id: id }, config.jwt_secret, { expiresIn: "2d" });
|
||||
return sign({ id: id }, config.jwt_secret, { expiresIn: "2d" })
|
||||
}
|
||||
|
||||
auth.get("/verify-token", jwt, async (req, res, next) => {
|
||||
try {
|
||||
res.status(200).json({
|
||||
message: "You are authenticated",
|
||||
});
|
||||
message: "You are authenticated"
|
||||
})
|
||||
} catch (e) {
|
||||
next(e);
|
||||
next(e)
|
||||
}
|
||||
});
|
||||
})
|
||||
|
|
|
@ -1,15 +1,16 @@
|
|||
import { celebrate, Joi } from "celebrate";
|
||||
import { Router } from "express";
|
||||
import { File } from "@lib/models/File";
|
||||
import secretKey from "@lib/middleware/secret-key";
|
||||
import { celebrate, Joi } from "celebrate"
|
||||
import { Router } from "express"
|
||||
import { File } from "@lib/models/File"
|
||||
import secretKey from "@lib/middleware/secret-key"
|
||||
|
||||
export const files = Router();
|
||||
export const files = Router()
|
||||
|
||||
files.get("/raw/:id",
|
||||
files.get(
|
||||
"/raw/:id",
|
||||
celebrate({
|
||||
params: {
|
||||
id: Joi.string().required(),
|
||||
},
|
||||
id: Joi.string().required()
|
||||
}
|
||||
}),
|
||||
secretKey,
|
||||
async (req, res, next) => {
|
||||
|
@ -18,7 +19,7 @@ files.get("/raw/:id",
|
|||
where: {
|
||||
id: req.params.id
|
||||
},
|
||||
attributes: ["title", "content"],
|
||||
attributes: ["title", "content"]
|
||||
})
|
||||
|
||||
if (!file) {
|
||||
|
@ -30,23 +31,22 @@ files.get("/raw/:id",
|
|||
// jwt(req as UserJwtRequest, res, () => {
|
||||
// res.json(file);
|
||||
// })
|
||||
res.json(file);
|
||||
res.json(file)
|
||||
} else {
|
||||
res.json(file);
|
||||
res.json(file)
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
next(e);
|
||||
} catch (e) {
|
||||
next(e)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
files.get("/html/:id",
|
||||
files.get(
|
||||
"/html/:id",
|
||||
celebrate({
|
||||
params: {
|
||||
id: Joi.string().required(),
|
||||
},
|
||||
id: Joi.string().required()
|
||||
}
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
|
@ -54,15 +54,15 @@ files.get("/html/:id",
|
|||
where: {
|
||||
id: req.params.id
|
||||
},
|
||||
attributes: ["html"],
|
||||
attributes: ["html"]
|
||||
})
|
||||
|
||||
if (!file) {
|
||||
return res.status(404).json({ error: "File not found" })
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.setHeader('Cache-Control', 'public, max-age=4800')
|
||||
res.setHeader("Content-Type", "text/plain")
|
||||
res.setHeader("Cache-Control", "public, max-age=4800")
|
||||
res.status(200).write(file.html)
|
||||
res.end()
|
||||
} catch (error) {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
export { auth } from "./auth";
|
||||
export { posts } from "./posts";
|
||||
export { users } from "./users";
|
||||
export { files } from "./files";
|
||||
export { auth } from "./auth"
|
||||
export { posts } from "./posts"
|
||||
export { users } from "./users"
|
||||
export { files } from "./files"
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
import { Router } from "express";
|
||||
import { celebrate, Joi } from "celebrate";
|
||||
import { File } from '@lib/models/File'
|
||||
import { Post } from '@lib/models/Post';
|
||||
import jwt, { UserJwtRequest } from '@lib/middleware/jwt';
|
||||
import * as crypto from "crypto";
|
||||
import { User } from '@lib/models/User';
|
||||
import secretKey from '@lib/middleware/secret-key';
|
||||
import markdown from '@lib/render-markdown';
|
||||
import { Router } from "express"
|
||||
import { celebrate, Joi } from "celebrate"
|
||||
import { File } from "@lib/models/File"
|
||||
import { Post } from "@lib/models/Post"
|
||||
import jwt, { UserJwtRequest } from "@lib/middleware/jwt"
|
||||
import * as crypto from "crypto"
|
||||
import { User } from "@lib/models/User"
|
||||
import secretKey from "@lib/middleware/secret-key"
|
||||
import markdown from "@lib/render-markdown"
|
||||
|
||||
export const posts = Router();
|
||||
export const posts = Router()
|
||||
|
||||
const postVisibilitySchema = (value: string) => {
|
||||
if (value === 'public' || value === 'private') {
|
||||
return value;
|
||||
if (value === "public" || value === "private") {
|
||||
return value
|
||||
} else {
|
||||
throw new Error('Invalid post visibility');
|
||||
throw new Error("Invalid post visibility")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -23,66 +23,79 @@ posts.post(
|
|||
jwt,
|
||||
celebrate({
|
||||
body: {
|
||||
title: Joi.string().required(),
|
||||
title: Joi.string().required().allow("", null),
|
||||
files: Joi.any().required(),
|
||||
visibility: Joi.string().custom(postVisibilitySchema, 'valid visibility').required(),
|
||||
visibility: Joi.string()
|
||||
.custom(postVisibilitySchema, "valid visibility")
|
||||
.required(),
|
||||
userId: Joi.string().required(),
|
||||
password: Joi.string().optional(),
|
||||
},
|
||||
password: Joi.string().optional()
|
||||
}
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
let hashedPassword: string = ''
|
||||
if (req.body.visibility === 'protected') {
|
||||
hashedPassword = crypto.createHash('sha256').update(req.body.password).digest('hex');
|
||||
let hashedPassword: string = ""
|
||||
if (req.body.visibility === "protected") {
|
||||
hashedPassword = crypto
|
||||
.createHash("sha256")
|
||||
.update(req.body.password)
|
||||
.digest("hex")
|
||||
}
|
||||
|
||||
const newPost = new Post({
|
||||
title: req.body.title,
|
||||
visibility: req.body.visibility,
|
||||
password: hashedPassword,
|
||||
password: hashedPassword
|
||||
})
|
||||
|
||||
await newPost.save()
|
||||
await newPost.$add('users', req.body.userId);
|
||||
const newFiles = await Promise.all(req.body.files.map(async (file) => {
|
||||
const html = getHtmlFromFile(file);
|
||||
await newPost.$add("users", req.body.userId)
|
||||
const newFiles = await Promise.all(
|
||||
req.body.files.map(async (file) => {
|
||||
const html = getHtmlFromFile(file)
|
||||
const newFile = new File({
|
||||
title: file.title,
|
||||
title: file.title || "",
|
||||
content: file.content,
|
||||
sha: crypto.createHash('sha256').update(file.content).digest('hex').toString(),
|
||||
sha: crypto
|
||||
.createHash("sha256")
|
||||
.update(file.content)
|
||||
.digest("hex")
|
||||
.toString(),
|
||||
html
|
||||
})
|
||||
|
||||
await newFile.$set("user", req.body.userId);
|
||||
await newFile.$set("post", newPost.id);
|
||||
await newFile.save();
|
||||
return newFile;
|
||||
}))
|
||||
await newFile.$set("user", req.body.userId)
|
||||
await newFile.$set("post", newPost.id)
|
||||
await newFile.save()
|
||||
return newFile
|
||||
})
|
||||
)
|
||||
|
||||
await Promise.all(newFiles.map((file) => {
|
||||
newPost.$add("files", file.id);
|
||||
newPost.save();
|
||||
}))
|
||||
await Promise.all(
|
||||
newFiles.map((file) => {
|
||||
newPost.$add("files", file.id)
|
||||
newPost.save()
|
||||
})
|
||||
)
|
||||
|
||||
res.json(newPost);
|
||||
res.json(newPost)
|
||||
} catch (e) {
|
||||
next(e);
|
||||
next(e)
|
||||
}
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
posts.get("/", secretKey, async (req, res, next) => {
|
||||
try {
|
||||
const posts = await Post.findAll({
|
||||
attributes: ["id", "title", "visibility", "createdAt"],
|
||||
attributes: ["id", "title", "visibility", "createdAt"]
|
||||
})
|
||||
|
||||
res.json(posts);
|
||||
res.json(posts)
|
||||
} catch (e) {
|
||||
next(e);
|
||||
next(e)
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
posts.get("/mine", jwt, secretKey, async (req: UserJwtRequest, res, next) => {
|
||||
if (!req.user) {
|
||||
|
@ -101,13 +114,15 @@ posts.get("/mine", jwt, secretKey, async (req: UserJwtRequest, res, next) => {
|
|||
as: "files"
|
||||
}
|
||||
]
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
})
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: "User not found" })
|
||||
}
|
||||
return res.json(user.posts?.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()))
|
||||
return res.json(
|
||||
user.posts?.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
|
||||
)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
|
@ -117,14 +132,14 @@ posts.get(
|
|||
"/:id",
|
||||
celebrate({
|
||||
params: {
|
||||
id: Joi.string().required(),
|
||||
},
|
||||
id: Joi.string().required()
|
||||
}
|
||||
}),
|
||||
async (req: UserJwtRequest, res, next) => {
|
||||
try {
|
||||
const post = await Post.findOne({
|
||||
where: {
|
||||
id: req.params.id,
|
||||
id: req.params.id
|
||||
},
|
||||
include: [
|
||||
{
|
||||
|
@ -136,74 +151,86 @@ posts.get(
|
|||
"content",
|
||||
"sha",
|
||||
"createdAt",
|
||||
"updatedAt",
|
||||
],
|
||||
"updatedAt"
|
||||
]
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "users",
|
||||
attributes: ["id", "username"],
|
||||
},
|
||||
],
|
||||
});
|
||||
attributes: ["id", "username"]
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
if (!post) {
|
||||
return res.status(404).json({ error: "Post not found" })
|
||||
}
|
||||
|
||||
// if public or unlisted, cache
|
||||
if (post.visibility === 'public' || post.visibility === 'unlisted') {
|
||||
res.set('Cache-Control', 'public, max-age=4800')
|
||||
if (post.visibility === "public" || post.visibility === "unlisted") {
|
||||
res.set("Cache-Control", "public, max-age=4800")
|
||||
}
|
||||
|
||||
if (post.visibility === 'public' || post?.visibility === 'unlisted') {
|
||||
if (post.visibility === "public" || post?.visibility === "unlisted") {
|
||||
secretKey(req, res, () => {
|
||||
res.json(post);
|
||||
res.json(post)
|
||||
})
|
||||
} else if (post.visibility === 'private') {
|
||||
} else if (post.visibility === "private") {
|
||||
jwt(req as UserJwtRequest, res, () => {
|
||||
res.json(post);
|
||||
res.json(post)
|
||||
})
|
||||
} else if (post.visibility === 'protected') {
|
||||
} else if (post.visibility === "protected") {
|
||||
const { password } = req.query
|
||||
if (!password || typeof password !== 'string') {
|
||||
if (!password || typeof password !== "string") {
|
||||
return jwt(req as UserJwtRequest, res, () => {
|
||||
res.json(post);
|
||||
res.json(post)
|
||||
})
|
||||
}
|
||||
const hash = crypto.createHash('sha256').update(password).digest('hex').toString()
|
||||
const hash = crypto
|
||||
.createHash("sha256")
|
||||
.update(password)
|
||||
.digest("hex")
|
||||
.toString()
|
||||
if (hash !== post.password) {
|
||||
return res.status(400).json({ error: "Incorrect password." })
|
||||
}
|
||||
|
||||
res.json(post);
|
||||
res.json(post)
|
||||
}
|
||||
} catch (e) {
|
||||
next(e)
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
next(e);
|
||||
}
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
function getHtmlFromFile(file: any) {
|
||||
const renderAsMarkdown = ['markdown', 'md', 'mdown', 'mkdn', 'mkd', 'mdwn', 'mdtxt', 'mdtext', 'text', ''];
|
||||
const renderAsMarkdown = [
|
||||
"markdown",
|
||||
"md",
|
||||
"mdown",
|
||||
"mkdn",
|
||||
"mkd",
|
||||
"mdwn",
|
||||
"mdtxt",
|
||||
"mdtext",
|
||||
"text",
|
||||
""
|
||||
]
|
||||
const fileType = () => {
|
||||
const pathParts = file.title.split(".");
|
||||
const language = pathParts.length > 1 ? pathParts[pathParts.length - 1] : "";
|
||||
return language;
|
||||
};
|
||||
const type = fileType();
|
||||
let contentToRender: string = (file.content || '');
|
||||
const pathParts = file.title.split(".")
|
||||
const language = pathParts.length > 1 ? pathParts[pathParts.length - 1] : ""
|
||||
return language
|
||||
}
|
||||
const type = fileType()
|
||||
let contentToRender: string = file.content || ""
|
||||
|
||||
if (!renderAsMarkdown.includes(type)) {
|
||||
contentToRender =
|
||||
`~~~${type}
|
||||
contentToRender = `~~~${type}
|
||||
${file.content}
|
||||
~~~`;
|
||||
~~~`
|
||||
} else {
|
||||
contentToRender = '\n' + file.content;
|
||||
contentToRender = "\n" + file.content
|
||||
}
|
||||
const html = markdown(contentToRender);
|
||||
return html;
|
||||
const html = markdown(contentToRender)
|
||||
return html
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import { Router } from "express";
|
||||
import { Router } from "express"
|
||||
// import jwt from "@lib/middleware/jwt";
|
||||
// import { User } from "@lib/models/User";
|
||||
|
||||
export const users = Router();
|
||||
export const users = Router()
|
||||
|
||||
// users.get("/", jwt, async (req, res, next) => {
|
||||
// try {
|
||||
|
|
|
@ -1,13 +1,11 @@
|
|||
import { createServer } from 'http';
|
||||
import { app } from './app';
|
||||
import config from './lib/config';
|
||||
import { sequelize } from './lib/sequelize';
|
||||
import { createServer } from "http"
|
||||
import { app } from "./app"
|
||||
import config from "./lib/config"
|
||||
import { sequelize } from "./lib/sequelize"
|
||||
|
||||
(async () => {
|
||||
await sequelize.sync({});
|
||||
createServer(app)
|
||||
.listen(
|
||||
config.port,
|
||||
() => console.info(`Server running on port ${config.port}`)
|
||||
);
|
||||
})();
|
||||
;(async () => {
|
||||
await sequelize.sync({})
|
||||
createServer(app).listen(config.port, () =>
|
||||
console.info(`Server running on port ${config.port}`)
|
||||
)
|
||||
})()
|
||||
|
|
|
@ -2027,6 +2027,11 @@ prepend-http@^2.0.0:
|
|||
resolved "https://registry.yarnpkg.com/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897"
|
||||
integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=
|
||||
|
||||
prettier@^2.6.0:
|
||||
version "2.6.0"
|
||||
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.6.0.tgz#12f8f504c4d8ddb76475f441337542fa799207d4"
|
||||
integrity sha512-m2FgJibYrBGGgQXNzfd0PuDGShJgRavjUoRCw1mZERIWVSXF0iLzLm+aOqTAbLnC3n6JzUhAA8uZnFVghHJ86A==
|
||||
|
||||
prism-react-renderer@^1.3.1:
|
||||
version "1.3.1"
|
||||
resolved "https://registry.yarnpkg.com/prism-react-renderer/-/prism-react-renderer-1.3.1.tgz#88fc9d0df6bed06ca2b9097421349f8c2f24e30d"
|
||||
|
|
Loading…
Reference in a new issue