Zhang
Zhang

Reputation: 11607

SailsJS how to specify file paths at the root level of project

I got a SailsJS application in which I need to reference a htpasswd file that is located at the root of my project:

var auth = require('http-auth');

var basic = auth.basic({
    authRealm: "Admin Panel",
    authFile: 'htpasswd', // <-- how do I specify the path to this file ?
    authType: 'basic'
});

module.exports = function(req, res, next) {
    basic.apply(req, res, function(username) {
        if(!username) {
            return res.serverError(403, 'You are not authorized');
        }

        next();
    })(req, res);
}

I have tried using:

authFile: '/htpasswd'

As well as:

authFile: '~/htpasswd'

Neither works.

Update

Hurmm....it seems like it's not the code that has error, somehow, my Sailsjs application can't find the htpasswd module.

I did do:

sudo npm install -g htpasswd

I also used htpasswd command line to generate the htpasswd file...somethings wrong with my project setup...

My console error says:

Error: Cannot find module 'htpasswd'
at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/MacUser/SailsProjects/SecurePanel/node_modules/http-auth/gensrc/auth/basic.js:11:14)

Upvotes: 2

Views: 1254

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

Use the native __dirname variable which evaluates to the path of the current file.

See what it is using console.log(__dirname). And then you could do:

var basic = auth.basic({
    realm: "Admin Panel",
    file: __dirname + "/path_from_current_file_to/htpasswd"
});

So if the root was a folder up from this the folder that this script is in, you could do

__dirname + "/../htpasswd"

Upvotes: 3

Related Questions