Added missing files and descriptions

pull/1104/merge
Zvonimir Sabljic 2 years ago
parent a513215264
commit 511dcdfc12

@ -0,0 +1,34 @@
const UserService = require('../../services/user.js');
const authenticateWithToken = (req, res, next) => {
const authHeader = req.get('Authorization');
if (authHeader) {
const m = authHeader.match(/^(Token|Bearer) (.+)/i);
if (m) {
UserService.authenticateWithToken(m[2])
.then((user) => {
req.user = user;
next();
})
.catch((err) => {
next(err);
});
return;
}
}
next();
};
const requireUser = (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Authentication required' });
}
next();
};
module.exports = {
authenticateWithToken,
requireUser,
};

@ -0,0 +1,107 @@
const { randomUUID } = require('crypto');
const User = require('../models/user.js');
const { generatePasswordHash, validatePassword } = require('../utils/password.js');
class UserService {
static async list() {
try {
return User.find();
} catch (err) {
throw `Database error while listing users: ${err}`;
}
}
static async get(id) {
try {
return User.findOne({ _id: id }).exec();
} catch (err) {
throw `Database error while getting the user by their ID: ${err}`;
}
}
static async getByEmail(email) {
try {
return User.findOne({ email }).exec();
} catch (err) {
throw `Database error while getting the user by their email: ${err}`;
}
}
static async update(id, data) {
try {
return User.findOneAndUpdate({ _id: id }, data, { new: true, upsert: false });
} catch (err) {
throw `Database error while updating user ${id}: ${err}`;
}
}
static async delete(id) {
try {
const result = await User.deleteOne({ _id: id }).exec();
return (result.deletedCount === 1);
} catch (err) {
throw `Database error while deleting user ${id}: ${err}`;
}
}
static async authenticateWithPassword(email, password) {
if (!email) throw 'Email is required';
if (!password) throw 'Password is required';
try {
const user = await User.findOne({email}).exec();
if (!user) return null;
const passwordValid = await validatePassword(password, user.password);
if (!passwordValid) return null;
user.lastLoginAt = Date.now();
const updatedUser = await user.save();
return updatedUser;
} catch (err) {
throw `Database error while authenticating user ${email} with password: ${err}`;
}
}
static async createUser({ email, password, name = '' }) {
if (!email) throw 'Email is required';
if (!password) throw 'Password is required';
const existingUser = await UserService.getByEmail(email);
if (existingUser) throw 'User with this email already exists';
const hash = await generatePasswordHash(password);
try {
const user = new User({
email,
password: hash,
name,
token: randomUUID(),
});
await user.save();
return user;
} catch (err) {
throw `Database error while creating new user: ${err}`;
}
}
static async setPassword(user, password) {
if (!password) throw 'Password is required';
user.password = await generatePasswordHash(password); // eslint-disable-line
try {
if (!user.isNew) {
await user.save();
}
return user;
} catch (err) {
throw `Database error while setting user password: ${err}`;
}
}
}
module.exports = UserService;

@ -0,0 +1,13 @@
const pino = require('pino');
const DEFAULT_LOG_LEVEL = process.env.NODE_ENV === "production" ? "info" : "debug";
const level = process.env.LOG_LEVEL || DEFAULT_LOG_LEVEL;
if (!pino.levels.values[level]) {
const validLevels = Object.keys(pino.levels.values).join(', ');
throw new Error(`Log level must be one of: ${validLevels}`);
}
const logger = (name) => pino({ name, level });
module.exports = logger;

@ -83,9 +83,11 @@ class ViteReactProjectTemplate(BaseProjectTemplate):
"server/package.json": "Server configuration with dependencies, scripts, and metadata. [References: server.js]",
"server/routes/auth.js": "This file defines routes for user authentication including registration, login, and logout. It interacts with a User model to handle user data and uses bcrypt for password hashing and comparison. [References: models/User.js]",
"server/routes/index.js": "This file defines routes for the home page.",
"server/routes/middleware/auth-middleware.js": "This file defines a middleware function called isAuthenticated, which checks if a user is authenticated based on the presence of a userId in the session object. If authenticated, it allows the request to proceed to the next middleware or route handler; otherwise, it returns a 401 status response indicating the user is not authenticated.",
"server/routes/middleware/auth.js": "This file defines a middleware function called isAuthenticated, which checks if a user is authenticated based on the presence of a userId in the session object. If authenticated, it allows the request to proceed to the next middleware or route handler; otherwise, it returns a 401 status response indicating the user is not authenticated.",
"server/models/User.js": "This file defines a Mongoose model for a user with fields for username and password. It includes a pre-save hook to hash the user's password before saving it to the database using bcrypt. [References: mongoose, bcrypt]",
"server/services/llm.js": "The file `llm.js` implements functionality for interacting with two large language model (LLM) providers: OpenAI and Anthropic. It uses the `axios` library for HTTP requests and the `dotenv` library to manage environment variables for API keys. The file defines functions to send requests to both providers, handling retries in case of errors. The `sendLLMRequest` function serves as a unified interface to send messages to either provider based on the specified provider name. The file exports sendLLMRequest() function for use in other parts of the application.",
"server/services/user.js": "The file `user.js` implements functionality for interacting with the User model defined in `models/User.js`. It includes functions to create a new user, find a user by username, and validate a user's password. The file exports createUser(...), list(...), get(...), getByEmail(...), update(...), delete(...), authenticateWithPassword(...), and setPassword(...) functions for use in other parts of the application.",
"server/utils/log.js": "This file defines a logger utility using the `pino` library. It configures logging to console and file with different log levels and formats. The logger is exported for use in other parts of the application. [References: pino]",
"package.json": "Project configuration with dependencies, scripts, and metadata.",
".gitignore": "Git configuration to exclude files and directories from version control.",
}

Loading…
Cancel
Save