MusicServer/routes/auth.ts

59 lines
2.0 KiB
TypeScript

import { Application } from "express";
import createHttpError from "http-errors";
import { dbExists, dbRead, dbStore } from "../database.js";
import md5 from "md5";
import jwt from 'jsonwebtoken';
import { config } from "../index.js";
export default function authRoutes(app: Application) {
app.use((req, res, next) => {
if (req.path.startsWith('/auth/')) return next();
var authHeader = req.headers['authorization'];
if (!authHeader) throw createHttpError[401]();
if (req.headers['x-username']) throw createHttpError[403]('bruh');
if (authHeader.startsWith('Bearer ')) authHeader = authHeader.slice(7);
const username = jwt.verify(authHeader, config.jwt_privkey, {
complete: false
}) as string;
req.headers['x-username'] = username;
next();
});
app.post('/auth/register', (req, res) => {
if (typeof req.body.username !== 'string' || typeof req.body.password !== 'string') {
throw createHttpError[400]();
}
if (dbExists('users', req.body.username)) throw createHttpError[409]('Username is already taken');
const user = {
username: req.body.username,
password: md5(req.body.password),
playlists: []
};
dbStore('users', req.body.username, user);
const token = jwt.sign(req.body.username, config.jwt_privkey);
res.send({
token
});
});
app.post('/auth/login', (req, res) => {
if (typeof req.body.username !== 'string' || typeof req.body.password !== 'string') {
throw createHttpError[400]();
}
if (!dbExists('users', req.body.username)) throw createHttpError[404]('User not found');
const user = dbRead('users', req.body.username);
if (user.password !== md5(req.body.password)) throw createHttpError[403]('Invalid password');
const token = jwt.sign(req.body.username, config.jwt_privkey);
res.send({
token
});
});
}