Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.4 kB
0
Indexable
Never
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const { register } = require("module");
// const jwtSecret = "secretkey";

const app = express();
const port = process.env.PORT || 5500;

const users = [];

app.use(bodyParser.json()); // support json encoded bodies

app.post("/register", async (req, res) => {
    try {
        const existingUser = users.find(
            (user) => user.username === req.body.username
        );

        if (existingUser) {
            return res.status(409).send("User already exists");
        }

        const userSecretKey = generateSecretKey();

        const hashedPassword = await bcrypt.hash(req.body.password, 10);
        const user = {
            username: req.body.username,
            password: hashedPassword,
            secretKey: userSecretKey,
        };

        users.push(user);

        const token = jwt.sign({ username: user.username }, user.secretKey);
        res.status(201).json({ token });
    } catch (error) {
        console.error(error);
        res.status(500).send("Something went wrong");
    }
});

app.get("/account", (req, res) => {
    // return array users
    res.send(users);
});

app.post("/login", async (req, res) => {
    try {
        const user = users.find((user) => user.username === req.body.username);

        if (!user) {
            return res.status(401).send("User not found");
        }

        const validPassword = await bcrypt.compare(
            req.body.password,
            user.password
        );

        if (!validPassword) {
            return res.status(401).send("Invalid password");
        }

        // Generate a JWT token for the authenticated user
        const token = jwt.sign({ username: user.username }, user.secretKey);

        res.status(200).json({ token });
    } catch (error) {
        console.error(error);
        res.status(500).send("Something went wrong");
    }
});

app.use(express.static("public"));

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

function generateSecretKey() {
    const secretKey = crypto.randomBytes(32).toString("hex");
    return secretKey;
}

// Client-side code for HTML forms