【问题标题】:How do I create a superadmin account for an express.js app?如何为 express.js 应用创建超级管理员帐户?
【发布时间】:2016-12-23 08:37:52
【问题描述】:

我想确保每次 express.js 应用程序启动时,都会对 mongodb 实例用户集合进行查询,以确保超级管理员帐户存在。但是,express.js 应用程序设置阶段的所有内容都是同步的。

我的一些想法是:

  1. 拥有一个注册模块的系统。每个模块都可以用 require 加载,并有一个 init 方法,可以使用 async 模块的 each 方法调用,该方法传递一个回调。一旦模块上的所有 init 方法执行完回调函数,就会运行app.listen(process.env.PORT)。

  2. 编写在 express.js 应用程序之外在命令行执行的安装脚本。该脚本使用 mongoose 连接到 mongodb 数据库,进行一些查询,然后终止。它可以添加到 heroku.sh 文件中,以确保它在每次启动 express.js 应用程序时运行。

  3. 在 express.js 设置阶段使用waitfor 同步运行数据库查询?这将使想法和代码保持干净和简单,但仅将 Fibers 用于这一项任务似乎有点过头了。

【问题讨论】:

  • 为什么不在设置/启动 express 之前检查您的超级管理员用户是否存在?
  • 因为它需要使用 mongoose 进行异步调用。在 express 启动时,我应该使用 waitfor 节点模块来同步运行该代码吗?

标签: javascript node.js mongodb express


【解决方案1】:

我只是将一个 init 函数隔离到一个单独的文件中。它只在这里检查管理员用户的数据库,但在未来,我可以注册通过app 和db 对象的模块,我将使用async.each 异步加载模块并运行init 方法在每个启动系统。一旦他们都注册了,就在快递服务器上运行init。

server.js:

'use strict';
// Set the 'NODE_ENV' variable
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
process.env.PORT = process.env.PORT || 3000;

// Apparently __dirname doesn't work on Heroku
// @link http://stackoverflow.com/questions/17212624/deploy-nodejs-on-heroku-fails-serving-static-files-located-in-subfolders
process.env.PWD = process.cwd();

// Load the module dependencies
var mongoose = require('./server/config/mongoose'),
    express = require('./server/config/express'),
    init = require('./server/config/init');

// Create a new Mongoose connection instance
var db = mongoose();

// Create a new Express application instance
var app = express(db);

// Run the init this way in future refactor modules into separate folders.
init(app, db)
    .then(function initialized() {

        // Use the Express application instance to listen to the '3000' port
        app.listen(process.env.PORT);

        // Log the server status to the console
        console.log('Server running at http://localhost:' + process.env.PORT + '/');
    });

// Use the module.exports property to expose our Express application instance for external ussage
module.exports = app;

服务器/配置/init.js:

'use strict';

var config = require('./config');

module.exports = function(app, db) {
    return new Promise(function(resolve) {
        var User = db.model('User');
        User.findOne({ email: config.adminAccountEmail}, function(err, user) {
            if (err) throw err;
            if (!user) {
                var newAdmin = new User({
                    email: config.adminAccountEmail,
                    password: config.adminAccountPassword,
                    roles: ['administrator', 'authenticated', 'anonymous']
                });
                newAdmin.save(function(err) {
                    if (err) throw err;
                    resolve();
                })
            } else {
                resolve();
            }
        })
    })
};

服务器/配置/production.js:

'use strict';

/**
 * Set the 'production' environment configuration object
 * @link http://docs.mongolab.com/migrating/
 */

module.exports = {
    db: process.env.MONGODB_URI,
    // set this to build
    // dir: 'build/',
    dir: 'client/',
    fileDir: 'files/',
    sessionSecret: process.env.SESSION_SECRET || 'MEAN',
    adminAccountEmail: process.env.ADMIN_ACCOUNT_EMAIL || 'admin@simpleyachtjobs.com',
    adminAccountPassword: process.env.ADMIN_ACCOUNT_PASSWORD || 'password'
}

【讨论】:

    【解决方案2】:

    您不需要同步执行数据库查找。验证用户存在后,只需在数据库请求的回调中启动 express 服务器即可。这是一个伪示例:

    mongoclient.open(function (err, mongoclient) {
        if (err) throw err;  // or otherwise handle it
    
        var db = client.db("dbname");
        var findAdminUserJSON = {
            // whatever your lookup criteria
        };
        db.collection("user").findOne(findAdminUserJSON, function(err, adminUserData){
            if (err) throw err;  // or otherwise handle it
    
            if(adminUserData){
                // start express server
            } else {
                // however you want to handle the case of no admin user
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2016-07-02
      • 2016-05-09
      • 2021-08-22
      相关资源
      最近更新 更多