101 lines
2.2 KiB
TypeScript
101 lines
2.2 KiB
TypeScript
import bcrypt from 'bcrypt';
|
|
import sql from '$lib/db/db.server';
|
|
import type { Cookies } from '@sveltejs/kit';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
export async function createUser(username: string, password: string): Promise<void> {
|
|
const password_hash: string = await bcrypt.hash(password, 12);
|
|
const timestamp = new Date(Date.now()).toISOString();
|
|
|
|
console.log(timestamp);
|
|
|
|
const response = await sql`
|
|
INSERT INTO users (username, password_hash, perms, created_at, last_signin, active)
|
|
VALUES (${username}, ${password_hash}, 3, ${timestamp}, ${timestamp}, ${true});
|
|
`;
|
|
}
|
|
|
|
export async function checkUserCreds(username: string, password: string): Promise<number> {
|
|
const [user] = await sql`
|
|
SELECT password_hash, perms
|
|
FROM users
|
|
WHERE username = ${username}
|
|
`;
|
|
|
|
if (!user) {
|
|
return -1;
|
|
}
|
|
if (await bcrypt.compare(password, user.password_hash)) {
|
|
return user['perms'];
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
export function getUserPerms(cookies: Cookies): number {
|
|
if (process.env.JWT_SECRET === undefined) {
|
|
throw new Error('JWT_SECRET not defined');
|
|
}
|
|
|
|
const JWT = cookies.get('jwt');
|
|
if (JWT) {
|
|
try {
|
|
const decoded = jwt.verify(JWT, process.env.JWT_SECRET);
|
|
if (typeof decoded === 'object' && 'perms' in decoded) {
|
|
return decoded['perms'];
|
|
}
|
|
} catch (err) {
|
|
return -1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
// should require MANAGE_USERS permission
|
|
export async function getUsers(): Promise<User[]> {
|
|
const users = await sql<
|
|
{
|
|
id: number;
|
|
username: string;
|
|
perms: number;
|
|
created_at: Date;
|
|
last_signin: Date;
|
|
active: boolean;
|
|
}[]
|
|
>`
|
|
SELECT id, username, perms,
|
|
created_at AT TIME ZONE 'UTC' AS created_at,
|
|
last_signin AT TIME ZONE 'UTC' AS last_signin,
|
|
active
|
|
FROM users;
|
|
`;
|
|
return users.map(
|
|
(user): User => ({
|
|
id: user.id,
|
|
username: user.username,
|
|
perms: user.perms,
|
|
created_at: user.created_at,
|
|
last_signin: user.last_signin,
|
|
active: user.active
|
|
})
|
|
);
|
|
}
|
|
|
|
// should require MANAGE_TAGS permission
|
|
export async function getTags(): Promise<Tag[]> {
|
|
const tags = await sql<
|
|
{
|
|
id: number;
|
|
display_name: string;
|
|
}[]
|
|
>`
|
|
SELECT id, display_name
|
|
FROM tags;
|
|
`;
|
|
return tags.map(
|
|
(tag): Tag => ({
|
|
id: tag.id,
|
|
display_name: tag.display_name
|
|
})
|
|
);
|
|
}
|