You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
199 lines
6.8 KiB
199 lines
6.8 KiB
import bcrypt from "bcrypt";
|
|
import {getClient} from "../utils/database.js";
|
|
import jwt from "jsonwebtoken";
|
|
import path, {dirname} from "path";
|
|
import fs from "fs";
|
|
import {fileURLToPath} from "url";
|
|
|
|
export async function register(req, res) {
|
|
try {
|
|
const user = {
|
|
email: req.body.email,
|
|
username: req.body.username,
|
|
password: req.body.password,
|
|
picture: req.body.picture,
|
|
}
|
|
|
|
const logger = req.body.logger;
|
|
logger.action("try to register a user with username: " + req.body.username + " and email: " + req.body.email, user);
|
|
|
|
user.password = await bcrypt.hash(req.body.password, 10);
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
let file = req.file.buffer;
|
|
if (file) {
|
|
const finalName = user.username + "." + req.file.originalname.split(".")[1];
|
|
const destinationPath = path.join(__dirname, "../uploads/profiles/" + finalName)
|
|
console.log(destinationPath)
|
|
|
|
fs.writeFileSync(destinationPath, file);
|
|
user.picture = "/api/media/profile/" + finalName;
|
|
} else {
|
|
user.picture = "/api/media/profile/default.png";
|
|
}
|
|
|
|
const client = await getClient();
|
|
|
|
const query = `INSERT INTO users (email, username, password, picture) VALUES ('${user.email}','${user.username}','${user.password}', '${user.picture}')`;
|
|
|
|
await client.query(query);
|
|
console.log("Successfully registered");
|
|
client.end();
|
|
logger.write("successfully registered", 200);
|
|
res.status(200).send({user: user});
|
|
} catch (err) {
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
export async function login(req, res) {
|
|
const user = {
|
|
username: req.body.username,
|
|
password: req.body.password,
|
|
}
|
|
|
|
const logger = req.body.logger;
|
|
logger.action("try to login with username '" + user.username + "'");
|
|
|
|
const client = await getClient();
|
|
|
|
let query = `SELECT id, username, email, picture, password FROM users WHERE username = '${user.username}'`;
|
|
|
|
const result = await client.query(query);
|
|
|
|
const userInBase = result.rows[0];
|
|
|
|
if (!userInBase) {
|
|
logger.write("failed to login", 401)
|
|
res.status(401).json({error: "Invalid credentials"});
|
|
return
|
|
}
|
|
|
|
const isPasswordValid = await bcrypt.compare(req.body.password, userInBase.password);
|
|
|
|
if (!isPasswordValid) {
|
|
logger.write("failed to login", 401)
|
|
res.status(401).json({error: "Invalid credentials"});
|
|
return
|
|
}
|
|
|
|
const payload = {
|
|
id: userInBase.id,
|
|
username: userInBase.username,
|
|
}
|
|
|
|
const token = jwt.sign(payload, process.env.JWT_SECRET);
|
|
|
|
const userData = {
|
|
id: userInBase.id,
|
|
username: userInBase.username,
|
|
email: userInBase.email,
|
|
picture: userInBase.picture
|
|
}
|
|
|
|
logger.write("Successfully logged in", 200);
|
|
res.status(200).json({token: token, user: userData});
|
|
|
|
}
|
|
|
|
export async function getById(req, res) {
|
|
const id = req.params.id;
|
|
const logger = req.body.logger;
|
|
logger.action("try to retrieve user " + id);
|
|
const client = await getClient();
|
|
const query = `SELECT id, email, username, picture FROM users WHERE id = ${id}`;
|
|
const result = await client.query(query);
|
|
if (!result.rows[0]) {
|
|
logger.write("failed to retrieve user " + id + " because it doesn't exist", 404);
|
|
res.status(404).json({error: "Not Found"});
|
|
return
|
|
}
|
|
logger.write("successfully retrieved user " + id, 200);
|
|
return res.status(200).json({user: result.rows[0]});
|
|
}
|
|
|
|
export async function getByUsername(req, res) {
|
|
const username = req.params.username;
|
|
const client = await getClient();
|
|
const logger = req.body.logger;
|
|
logger.action("try to retrieve user " + username);
|
|
const query = `SELECT id, email, username, picture FROM users WHERE username = '${username}'`;
|
|
const result = await client.query(query);
|
|
if (!result.rows[0]) {
|
|
logger.write("failed to retrieve user " + username + " because it doesn't exist", 404);
|
|
res.status(404).json({error: "Not Found"});
|
|
return
|
|
}
|
|
logger.write("successfully retrieved user " + username, 200);
|
|
return res.status(200).json({user: result.rows[0]});
|
|
}
|
|
|
|
export async function update(req, res) {
|
|
|
|
try {
|
|
const id = req.params.id;
|
|
let user = {
|
|
email: req.body.email,
|
|
username: req.body.username,
|
|
password: req.body.password,
|
|
picture: req.body.picture,
|
|
}
|
|
|
|
const client = await getClient();
|
|
const userQuery = `SELECT * FROM users WHERE id = ${id}`;
|
|
const userResult = await client.query(userQuery);
|
|
const userInBase = userResult.rows[0];
|
|
|
|
const logger = req.body.logger;
|
|
logger.action("try to update user " + id);
|
|
|
|
if (user.email !== userInBase.email) {
|
|
const emailQuery = `SELECT email FROM users WHERE email = '${user.email}'`;
|
|
const emailResult = await client.query(emailQuery);
|
|
if (emailResult.rows[0]) {
|
|
logger.write("failed to update because email is already used", 400)
|
|
res.status(400).json({error: "Email already exists"});
|
|
}
|
|
}
|
|
|
|
if (user.username !== userInBase.username) {
|
|
const usernameQuery = `SELECT username FROM users WHERE username = '${user.username}'`;
|
|
const usernameResult = await client.query(usernameQuery);
|
|
if (usernameResult.rows[0]) {
|
|
logger.write("failed to update because username is already used", 400)
|
|
res.status(400).json({error: "Username already exists"});
|
|
}
|
|
}
|
|
|
|
const isPasswordValid = await bcrypt.compare(req.body.password, userInBase.password);
|
|
|
|
if (!isPasswordValid) {
|
|
user.password = await bcrypt.hash(req.body.password, 10);
|
|
} else {
|
|
user.password = userInBase.password;
|
|
}
|
|
|
|
const updateQuery = `UPDATE users SET email = '${user.email}', username = '${user.username}', password = '${user.password}', picture = '${user.picture}' WHERE id = ${id}`;
|
|
const result = await client.query(updateQuery);
|
|
logger.write("successfully updated user " + id, 200);
|
|
res.status(200).send({user: result.rows[0]});
|
|
} catch (err) {
|
|
console.log(err);
|
|
res.status(500).json({error: err});
|
|
}
|
|
|
|
}
|
|
|
|
export async function deleteUser(req, res) {
|
|
const id = req.params.id;
|
|
const client = await getClient();
|
|
const logger = req.body.logger;
|
|
logger.action("try to delete user " + id);
|
|
const query = `DELETE FROM users WHERE id = ${id}`;
|
|
await client.query(query);
|
|
logger.write("successfully deleted user " + id);
|
|
res.status(200).json({message: 'User deleted'});
|
|
}
|