3

I want to make a private access to an application using express.js like .htaccess and .htpasswd do in my php project.

I'm using http-auth

Here is my code :

app.get('/', function(req, res) {
  basic.apply(req, res, function(username) {
    res.redirect(routes.index);
  });
});

The problem is I get an error :

500 TypeError: Object function (req, res){ res.render('index', { title: 'Express' }); } has no method 'indexOf'

Without authentication,

app.get('/', routes.index);

works without any troubles.

I think about a middleware to read my index and then use res.send()... May it works? or what did I miss?

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
Jérôme
  • 1,060
  • 1
  • 7
  • 18

2 Answers2

2

I think the argument to res.redirect needs to be a URL string, right ? You seem to be passing in a request handler (function (req, res) {...}).

lmjohns3
  • 7,422
  • 5
  • 36
  • 56
  • well, in that way, using res.redirect is not good. Because I need url rewriting. http:// url.com / -> call routes/index.js – Jérôme Aug 06 '13 at 17:02
  • Yeah. You could probably just remove the call to `res.redirect` entirely and just invoke your `routes.index` handler function directly inside the `basic.apply` callback ? – lmjohns3 Aug 06 '13 at 17:08
  • I already tried it, but maybe I was wrong. basic.apply(req, res, function(username) { //... }, routes.index); This doesn't return an error but it doesn't call index neither – Jérôme Aug 07 '13 at 08:52
  • That's right, you need to actually call the handler yourself: `routes.index(req, res)`. – lmjohns3 Aug 07 '13 at 14:11
  • Isn't question about `http-auth` usage, if so this don't answer it. – gevorg Jun 05 '16 at 11:00
1

I think usage pattern now is different

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ...
});

// Application setup.
var app = express();

// Setup route.
app.get('/', auth.connect(basic), routes.index);
gevorg
  • 4,835
  • 4
  • 35
  • 52