Как я могу зарегистрировать конечного пользователя в своем приложении с одной страницей и перенаправить их в приложение с одной страницей, используя Backbone.js. Express.js и passport.js.Как я могу зарегистрировать конечного пользователя в своем приложении с одной страницей и перенаправить их на приложение с одной страницей?
У меня есть паспорт, mongo.db, express и позвоночник, все работают над моим приложением. Однако, после успешного входа в систему, я хочу загрузить одну страницу, базовую js, веб-приложение. На данный момент у меня есть система входа в систему. Но когда я перехожу к перенаправлению пользователя к приложению, после успешного входа в систему по какой-то причине он просто перенаправляет обратно на страницу входа. Я использовал консольный журнал, чтобы убедиться, что с кодом входа на сервер ничего нет, и все работает нормально. Странно то, что когда я открываю инструменты для разработчиков Chrome и смотрю заголовки и ответ, я возвращаю правильную индексную страницу, но она не загружается в браузере, а Url остается http://localhost:3000/login
.
Вот код, который я подозреваю, что должно быть как-то преступник:
См редактировать # 2
Я попытался как res.sendfile(__dirname + '/public/index.html');
и res.render('index', { user: req.user });
в моей базе («/») путь, но ни из них, похоже, загружается index.html. Обратите внимание, что public/index.html и индекс ejs - это, по сути, одни и те же файлы. Я начал с загрузки всего приложения на стороне клиента, но теперь я пытаюсь переместить основной файл index.html на серверную сторону, чтобы защитить его паролем.
Пожалуйста, дайте мне знать, если возникнут какие-либо вопросы, которые помогут мне лучше объяснить эту проблему, или если вам больше не нужен код. Я действительно хочу, чтобы эта штука поняла.
Редактировать Как вы можете видеть на этом снимке экрана моего браузера, у меня есть не что иное, как простая форма. Когда эта форма отправляется, я возвращаю желаемую страницу в ответе, но она не загружается в браузере. Я также получаю, что не удалось загрузить ошибку ресурса в консоли, но по какой-то причине не удается загрузить/войти, даже если я пытаюсь загрузить индекс.
Edit # 2 Столько, сколько я ненавижу, чтобы вставить бесконечные блоки кода, я думаю, что единственный способ решить эту проблему, чтобы вставить бесконечные блоки кода. Так вот server.js во всех его слава - минус некоторые из API маршрутов, которые не имеют отношения:
var express = require('express')
, http = require('http')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, bcrypt = require('bcrypt')
, SALT_WORK_FACTOR = 10
, mongoose = require('mongoose')
, path = require('path');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('ejs', require('ejs-locals'));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
//Connect to database
var db = mongoose.connect('mongodb://localhost/attorneyapp');
/*
|-------------------------------------------------------------------------------
| Schemas
|-------------------------------------------------------------------------------
*/
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true},
});
// Bcrypt middleware
userSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if(err) return next(err);
user.password = hash;
next();
});
});
});
// Password verification
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};
var Client = new mongoose.Schema({
first_name: String,
last_name: String,
status: String,
});
var Case = new mongoose.Schema({
case_name: String,
status: String,
});
/*
|-------------------------------------------------------------------------------
| Models
|-------------------------------------------------------------------------------
*/
var User = mongoose.model('User', userSchema);
var ClientModel = mongoose.model('Client', Client);
var CaseModel = mongoose.model('Case', Case);
// Seed a user
// var user = new User({ username: 'bob', email: '[email protected]', password: 'secret' });
// user.save(function(err) {
// if(err) {
// console.log(err);
// } else {
// console.log('user: ' + user.username + " saved.");
// }
// });
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) {
console.log('error: ', err);
return done(err);
}
if (!user) {
console.log('Unknown user ', username);
return done(null, false, { message: 'Unknown user ' + username });
}
user.comparePassword(password, function(err, isMatch) {
if (err){
console.log('error: ', err);
return done(err);
}
if(isMatch) {
console.log('it is a match');
return done(null, user);
} else {
console.log('invalid password');
return done(null, false, { message: 'Invalid password' });
}
});
});
}));
/*
|-------------------------------------------------------------------------------
| User
|-------------------------------------------------------------------------------
*/
// POST /login
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
//
// curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
//
/***** This version has a problem with flash messages
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res) {
res.redirect('/');
});
*/
// POST /login
// This is an alternative implementation that uses a custom callback to
// acheive the same functionality.
app.get('/', function(req, res){
console.log('base router is being called');
// res.sendfile(__dirname + '/public/index.html');
res.render('index');
});
app.get('/login', function(req, res) {
return res.render('login');
});
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
console.log('NOT USER', info.message);
req.session.messages = [info.message];
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) { return next(err); }
console.log('YES USER is loged in');
// return res.sendfile(__dirname + '/public/index.html');
return res.redirect('/');
});
})(req, res, next);
});
app.get('/users', function(req, res){
return User.find(function(err, users) {
if(!err) {
return res.send(users);
} else {
return console.log(err);
}
});
});
Кроме того, не уверен, если это уместно, но вот мой структура каталогов и файлов.
Я пробовал это, и он все еще не работает. Я больше не получаю, что не удалось загрузить ошибку ресурса в консоли. – Scott
Попробуйте удалить странные '(req, res, next);' в конце кода. Похоже, это ничего не делает. –
Я попытался удалить, но затем 'app.get ('/', function (req, res)' было известно, что больше вызывается после того, как пользователь был аутентифицирован – Scott