Build a public rights platform from scratch (3)

Continuing from the previous article, let’s optimize our backend code, add error handling, enhance security, and add user management and permission control.

Error handling:

We can add a global error handler to catch and handle all unhandled errors. Here's how to add an error handler in Express:

// 在所有路由之后添加
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send({ message: 'An error occurred' });
});

Enhanced Security:

  1. Limit request rate : We can use express-rate-limita library such as to limit the request rate of each IP to prevent brute force cracking.

  2. Enhanced password security : Use a more complex hash algorithm, such as argon2, and increase password complexity requirements.

  3. HTTPS : In a production environment, HTTPS should be used to encrypt transmitted data.

  4. Hide error details : In a production environment, error details should be hidden, and only error codes and general error messages should be returned to prevent leakage of sensitive information.

User management and access control:

We can add new routes to manage users, such as getting user list, modifying user information, deleting users, etc. Moreover, we can store the user's role information through the JWT payload, and then determine whether to allow an operation according to the user's role in the route processor. Here is some sample code:

// server.js
// 添加角色到用户数据模型
const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  phone: String,
  role: { type: String, default: 'user' } // 默认为'user'
});
// ...

// 用户登录时添加角色到JWT的payload
const token = jwt.sign({ id: user.id, role: user.role }, 'secret');
// ...

// 添加一个中间件来验证用户的角色
function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return res.status(403).send({ message: 'Forbidden' });
    }
    next();
  };
}

// 添加新的路由来管理用户,只有管理员可以访问
app.get('/api/users', requireRole('admin'), async (req, res) => {
  const users = await User.find();
  res.send(users);
});

app.delete('/api/users/:id', requireRole('admin'), async (req, res) => {
  await User.findByIdAndDelete(req.params.id);
  res.send({ message: 'User deleted' });
});

The above codes are some basic optimizations of existing functions, and there are still many details and other functions that need to be improved and implemented by you. In the follow-up, our column will update more complex permission control (each user may have multiple roles, each role has different permissions, etc.), user password retrieval and change, user personal information management and other functions.

Guess you like

Origin blog.csdn.net/a871923942/article/details/131253711