如何在服务器端构建Node,Express,Connect-Auth和Backbone应用程序? [英] How to structure a Node, Express, Connect-Auth and Backbone application on the server-side?

查看:124
本文介绍了如何在服务器端构建Node,Express,Connect-Auth和Backbone应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个客户端的人,刚刚进入服务器端的JavaScript世界。我有这个想法,我想我想要构建我的第一个Nodejs应用程序。我想要一个服务器端,几乎只提供一个空的shell和大量的JSON。我想将其余的逻辑放在装有Backbone.js的前端。

I'm a client-side guy that just stepped into the world of server-side javascript. I've got this idea about how I think I want to build my first Nodejs application. I want a server-side that pretty much only serves an empty shell and lots of JSON. I want to put the rest of the logic in a Backbone.js-equipped front-end.

所以我快速鞭打了一个小应用程序(底部的代码)和我有几个问题。

So I quick whipped up a small application (code in the bottom) and I've got a few questions.


  1. 会话变量是否安全?我可以使用会话变量来存储稍后读取以获取敏感日期的用户标识符。是否可以修改会话变量,以便在我的情况下,一个用户可以掌握其他用户的数据?

  1. Are session variables safe? Can I use session variables to store an user identifier that I later read to fetch sensitive date. Is it possible to modify sessions variables so that, in my case, one user could get hold of another user's data?

我在我的'/ profile'路线上的方式。在我的应用程序中,将有很多路线就像那个。从数据库中获取内容并将其作为客户端的JSON提供的路由。

Does it make sense to serve JSON in the way I'm doing it on my '/profile' route. In my application there will be a lot of routes just like that one. Routes that fetch something from the database and serves them as JSON to the client.

看我的代码,你有什么提示或技巧吗?我应该做的不同。模块我可能应该看看?

Looking at my code, do you have any tips or tricks? Things I should do differently. Modules I probably should have a look at?

我的想法几乎是JSON的后端是有意义的吗?

Does my idea of an almost JSON-only backend makes sense?

我的应用程序在下面。

My application below.

var facebook = {
    'appId'         : "my app id",
    'appSecret'     : "my app secret",
    'scope'         : "email",
    'callback'      : "http://localhost:2000/"
}

var express         = require('express');
var MongoStore      = require('connect-mongo');
var auth            = require('connect-auth')
var UserProvider    = require('./providers/user').UserProvider;
var app             = module.exports = express.createServer();

// Configuration
app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(auth([auth.Facebook(facebook)]));
    app.use(express.session({secret: 'my secret',store: new MongoStore({db: 'app'})}));
    app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
    app.use(express.errorHandler()); 
});


// Providers
var UserProvider = new UserProvider('localhost', 27017);

// Routes
app.get('/', function( request, response ) {

    if( !request.session.userId ) {
        request.authenticate(['facebook'], function(error, authenticated) {
            if( authenticated ) {
                request.session.userId = request.getAuthDetails().user.id;
            }
        });
    }

    response.render( 'index.jade' );

});

app.get('/profile', function( request, response ) {

    response.contentType('application/json');
    if( request.session.userId ){
        UserProvider.findById( request.session.userId, function( error, user ){
            var userJSON = JSON.stringify( user );
            response.send( userJSON );
        });
    } else {
        response.writeHead(303, { 'Location': "/" });
    }

});

app.get('/logout', function( request, response, params ) {

    request.session.destroy();
    request.logout();
    response.writeHead(303, { 'Location': "/" });
    response.end('');

});

app.listen(2000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);


推荐答案

我认为你有正确的想法,会抛出几个想法:

I think you have the right idea, although I'll throw out a couple of thoughts:


  • 定义路线 - 如果您定义了很多路线,特别是使用JSON,您可能需要通过MVC类型框架动态定义它们。您可以在这里的快速样本中找到一个很好的例子。它将为您节省大量手写路由,您可以将节点对象作为JSON传回客户端,而无需在服务器端执行其他任何操作。
  • 强> - 如果你想去一点点疯狂(我从来没有使用过这种技术),开发种子已经建成一个名为骨骼的框架,在服务器端使用骨干
  • 登录示例 - 关于用户会话管理的DailyJS 的一个很好的教程。

  • 辅助功能 - 只要您没有辅助功能问题,通过REST API提供数据是有道理的。如果您不得不担心合规性或其他javascript限制,您可能会遇到问题。

  • Defining Routes - If you are defining a lot of routes, especially with JSON, you may want to define them dynamically via an MVC type framework. You can find a good example of that in the express samples here. It would save you a lot of handwritten routes and you could pass node objects back to the client as JSON without doing much else on the server side.
  • Backbone on the Server - If you want to go a little crazier (and I have not ever used this technique), Development Seed have built a framework called bones that uses backbone on the server side.
  • Login Example - There is a good tutorial over at DailyJS regarding user session management.
  • Accessibility - As long as you don't have accessibility concerns, providing data via a REST API makes sense. If you have to worry about 508 compliance or other javascript limitations you might run into problems.

至于安全性,将会话超时设置为较低的值并选择适当的密钥可能会有助于确保某人无法生成会话cookie(默认情况下实际数据不存储在客户端上)。我不知道node.js使用什么算法来生成会话cookie。以下是快件会话中间件的一些详细信息。

As for security, setting your session timeout to a lower value and choosing an appropriate secret key would probably go a long way toward making sure someone can't generate session cookies (by default the actual data isn't stored on the client). I'm not sure what algorithm node.js uses to generate session cookies. Here are some details on the express session middleware.

这篇关于如何在服务器端构建Node,Express,Connect-Auth和Backbone应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆