client/server: lint

This commit is contained in:
Max Leiter 2022-03-29 00:19:33 -07:00
parent 6afc4c915e
commit 85ae8173bb
No known key found for this signature in database
GPG key ID: A3512F2F2F17EBDA
20 changed files with 323 additions and 328 deletions

View file

@ -77,7 +77,7 @@ const Admin = () => {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{posts?.map((post, i) => ( {posts?.map((post) => (
<tr key={post.id}> <tr key={post.id}>
<td><PostModal id={post.id} /></td> <td><PostModal id={post.id} /></td>
<td>{post.visibility}</td> <td>{post.visibility}</td>

View file

@ -53,10 +53,9 @@ export const allowedFileNames = [
".fish_prompt", ".fish_prompt",
".zshrc", ".zshrc",
".zsh", ".zsh",
".zprofile", ".zprofile"
] ]
export const codeFileExtensions = [ export const codeFileExtensions = [
"awk", "awk",
"bat", "bat",
@ -120,5 +119,5 @@ export const allowedFileExtensions = [
"txt", "txt",
"webmanifest", "webmanifest",
"log", "log",
...codeFileExtensions, ...codeFileExtensions
] ]

View file

@ -1,11 +1,13 @@
import { User } from "@lib/types"; import { User } from "@lib/types"
import Cookies from "js-cookie"; import Cookies from "js-cookie"
import { useRouter } from "next/router"; import { useRouter } from "next/router"
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react"
const useUserData = () => { const useUserData = () => {
const [authToken, setAuthToken] = useState<string>(Cookies.get("drift-token") || ''); const [authToken, setAuthToken] = useState<string>(
const [user, setUser] = useState<User>(); Cookies.get("drift-token") || ""
)
const [user, setUser] = useState<User>()
const router = useRouter() const router = useRouter()
useEffect(() => { useEffect(() => {
const token = Cookies.get("drift-token") const token = Cookies.get("drift-token")
@ -19,7 +21,7 @@ const useUserData = () => {
const fetchUser = async () => { const fetchUser = async () => {
const response = await fetch(`/server-api/users/self`, { const response = await fetch(`/server-api/users/self`, {
headers: { headers: {
"Authorization": `Bearer ${authToken}` Authorization: `Bearer ${authToken}`
} }
}) })
if (response.ok) { if (response.ok) {
@ -35,7 +37,7 @@ const useUserData = () => {
} }
}, [authToken, router]) }, [authToken, router])
return user; return user
} }
export default useUserData export default useUserData

View file

@ -1,14 +1,11 @@
import databasePath from "@lib/get-database-path"; import databasePath from "@lib/get-database-path"
import { Sequelize } from "sequelize-typescript" import { Sequelize } from "sequelize-typescript"
import { SequelizeStorage, Umzug } from "umzug" import { SequelizeStorage, Umzug } from "umzug"
export const sequelize = new Sequelize({ export const sequelize = new Sequelize({
dialect: "sqlite", dialect: "sqlite",
database: "drift", database: "drift",
storage: storage: process.env.MEMORY_DB === "true" ? ":memory:" : databasePath,
process.env.MEMORY_DB === "true"
? ":memory:"
: databasePath,
models: [__dirname + "/lib/models"], models: [__dirname + "/lib/models"],
logging: true logging: true
}) })
@ -20,14 +17,18 @@ if (process.env.MEMORY_DB !== "true") {
} }
const umzug = new Umzug({ const umzug = new Umzug({
migrations: { glob: process.env.NODE_ENV === "production" ? __dirname + "/migrations/*.js" : __dirname + "/migrations/*.ts" }, migrations: {
glob:
process.env.NODE_ENV === "production"
? __dirname + "/migrations/*.js"
: __dirname + "/migrations/*.ts"
},
context: sequelize.getQueryInterface(), context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({ sequelize }), storage: new SequelizeStorage({ sequelize }),
logger: console logger: console
}) })
export type Migration = typeof umzug._types.migration export type Migration = typeof umzug._types.migration
;(async () => { ;(async () => {
// Checks migrations and run them if they are not already applied. To keep // Checks migrations and run them if they are not already applied. To keep
// track of the executed migrations, a table (and sequelize model) called SequelizeMeta // track of the executed migrations, a table (and sequelize model) called SequelizeMeta

View file

@ -1,5 +1,5 @@
export default { export default {
port: process.env.PORT || 3000, port: process.env.PORT || 3000,
jwt_secret: process.env.JWT_SECRET || "myjwtsecret", jwt_secret: process.env.JWT_SECRET || "myjwtsecret",
drift_home: process.env.DRIFT_HOME || "~/.drift", drift_home: process.env.DRIFT_HOME || "~/.drift"
} }

View file

@ -7,10 +7,11 @@ import config from "./config"
// This does *not* support `~other_user/tmp` => `/home/other_user/tmp`. // This does *not* support `~other_user/tmp` => `/home/other_user/tmp`.
function getDatabasePath() { function getDatabasePath() {
const fileName = "drift.sqlite" const fileName = "drift.sqlite"
const databasePath = `${config.drift_home}/${fileName}` || `~/.drift/${fileName}` const databasePath =
`${config.drift_home}/${fileName}` || `~/.drift/${fileName}`
const home = os.homedir().replace("$", "$$$$"); const home = os.homedir().replace("$", "$$$$")
return path.resolve(databasePath.replace(/^~($|\/|\\)/, home + "$1")); return path.resolve(databasePath.replace(/^~($|\/|\\)/, home + "$1"))
} }
export default getDatabasePath() export default getDatabasePath()

View file

@ -25,11 +25,11 @@ export default function authenticateToken(
if (err) return res.sendStatus(403) if (err) return res.sendStatus(403)
const userObj = await UserModel.findByPk(user.id, { const userObj = await UserModel.findByPk(user.id, {
attributes: { attributes: {
exclude: ["password"], exclude: ["password"]
} }
}) })
if (!userObj || userObj.role !== 'admin') { if (!userObj || userObj.role !== "admin") {
return res.sendStatus(403) return res.sendStatus(403)
} }

View file

@ -28,11 +28,9 @@ import { User } from "./User"
] ]
} }
})) }))
@Table({ @Table({
tableName: "files", tableName: "files"
}) })
export class File extends Model { export class File extends Model {
@IsUUID(4) @IsUUID(4)
@PrimaryKey @PrimaryKey

View file

@ -38,11 +38,9 @@ import { File } from "./File"
] ]
} }
})) }))
@Table( @Table({
{ tableName: "posts"
tableName: "posts", })
}
)
export class Post extends Model { export class Post extends Model {
@IsUUID(4) @IsUUID(4)
@PrimaryKey @PrimaryKey

View file

@ -12,9 +12,8 @@ import { Post } from "./Post"
import { User } from "./User" import { User } from "./User"
@Table({ @Table({
tableName: "post_authors", tableName: "post_authors"
}) })
export class PostAuthor extends Model { export class PostAuthor extends Model {
@IsUUID(4) @IsUUID(4)
@PrimaryKey @PrimaryKey

View file

@ -30,9 +30,8 @@ import { PostAuthor } from "./PostAuthor"
} }
})) }))
@Table({ @Table({
tableName: "users", tableName: "users"
}) })
export class User extends Model { export class User extends Model {
@IsUUID(4) @IsUUID(4)
@PrimaryKey @PrimaryKey

View file

@ -11,19 +11,19 @@ export const up: Migration = async ({ context: queryInterface }) =>
unique: true unique: true
}, },
username: { username: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
password: { password: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
createdAt: { createdAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
updatedAt: { updatedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
deletedAt: { deletedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
} }
}) })

View file

@ -11,22 +11,22 @@ export const up: Migration = async ({ context: queryInterface }) =>
unique: true unique: true
}, },
title: { title: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
visibility: { visibility: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
password: { password: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
createdAt: { createdAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
updatedAt: { updatedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
deletedAt: { deletedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
} }
}) })

View file

@ -12,26 +12,25 @@ export const up: Migration = async ({ context: queryInterface }) =>
unique: true unique: true
}, },
title: { title: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
content: { content: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
sha: { sha: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
html: { html: {
type: DataTypes.STRING, type: DataTypes.STRING
}, },
createdAt: { createdAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
updatedAt: { updatedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
deletedAt: { deletedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
userId: { userId: {
type: DataTypes.UUID, type: DataTypes.UUID,

View file

@ -7,13 +7,13 @@ export const up: Migration = async ({ context: queryInterface }) =>
id: { id: {
type: DataTypes.UUID, type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4, defaultValue: DataTypes.UUIDV4,
primaryKey: true, primaryKey: true
}, },
createdAt: { createdAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
updatedAt: { updatedAt: {
type: DataTypes.DATE, type: DataTypes.DATE
}, },
postId: { postId: {
type: DataTypes.UUID, type: DataTypes.UUID,

View file

@ -1,8 +1,8 @@
import isAdmin from "@lib/middleware/is-admin"; import isAdmin from "@lib/middleware/is-admin"
import { Post } from "@lib/models/Post"; import { Post } from "@lib/models/Post"
import { User } from "@lib/models/User"; import { User } from "@lib/models/User"
import { File } from "@lib/models/File"; import { File } from "@lib/models/File"
import { Router } from "express"; import { Router } from "express"
export const admin = Router() export const admin = Router()
@ -27,7 +27,7 @@ admin.get("/users", async (req, res, next) => {
as: "posts", as: "posts",
attributes: ["id"] attributes: ["id"]
} }
], ]
}) })
res.json(users) res.json(users)
} catch (e) { } catch (e) {
@ -112,4 +112,3 @@ admin.delete("/post/:id", async (req, res, next) => {
next(e) next(e)
} }
}) })

View file

@ -68,7 +68,10 @@ auth.post(
const user = { const user = {
username: username as string, username: username as string,
password: await hash(req.body.password, salt), password: await hash(req.body.password, salt),
role: (!!process.env.MEMORY_DB && process.env.ENABLE_ADMIN && count === 0) ? "admin" : "user" role:
!!process.env.MEMORY_DB && process.env.ENABLE_ADMIN && count === 0
? "admin"
: "user"
} }
const created_user = await User.create(user) const created_user = await User.create(user)

View file

@ -80,7 +80,7 @@ posts.post(
.update(file.content) .update(file.content)
.digest("hex") .digest("hex")
.toString(), .toString(),
html: html || '', html: html || "",
userId: req.body.userId, userId: req.body.userId,
postId: newPost.id postId: newPost.id
}) })
@ -183,9 +183,7 @@ posts.get(
{ "$files.title$": { [Op.like]: `%${q}%` } }, { "$files.title$": { [Op.like]: `%${q}%` } },
{ "$files.content$": { [Op.like]: `%${q}%` } } { "$files.content$": { [Op.like]: `%${q}%` } }
], ],
[Op.and]: [ [Op.and]: [{ "$users.id$": req.user?.id || "" }]
{ "$users.id$": req.user?.id || "" },
]
}, },
include: [ include: [
{ {
@ -195,7 +193,7 @@ posts.get(
}, },
{ {
model: User, model: User,
as: "users", as: "users"
} }
], ],
attributes: ["id", "title", "visibility", "createdAt", "deletedAt"], attributes: ["id", "title", "visibility", "createdAt", "deletedAt"],
@ -296,7 +294,6 @@ posts.delete("/:id", jwt, async (req: UserJwtRequest, res, next) => {
return res.status(404).json({ error: "Post not found" }) return res.status(404).json({ error: "Post not found" })
} }
if (req.user?.id !== post.users![0].id) { if (req.user?.id !== post.users![0].id) {
return res.status(403).json({ error: "Forbidden" }) return res.status(403).json({ error: "Forbidden" })
} }