node.js - 如何在Google登录中识别用户

时间:2015-02-20 05:15:12

标签: node.js express login oauth-2.0 google-api

我为我的应用程序设置了Google登录信息,并尝试为用户获取唯一标识符,因此当用户输入读数时,我可以将其作为特定用户的条目输入数据库。我怎么能这样做?

以下是我目前为止设置的一些登录代码。对于node.js来说很新,所以下面的代码可能会相当邋and和黑客攻击。我碰巧在教程中使用名为index.js的路径中的文件拆分app.js。

app.js

var express = require('express');
var passport = require('passport');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());

//Make db accessible to the router
app.use(function(req,res,next){
        req.db = db;
        next();
});
app.use('/', routes);
app.use('/users', users);

路由/ index.js

 passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

var processRequest = function(token, refreshToken, profile, callback){
   process.nextTick(function(){
           console.log('id : '+ profile.id);
           console.log('name :'+ profile.displayName);
           console.log('email :' + profile.emails);
           console.log('token : '+ token);
   });
};

passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://ec2-#########.compute-1.amazonaws.com:8080/Glucometer"
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      return done(null, profile);
    });
  }
));


router.get('/auth/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.profile',
                                            'https://www.googleapis.com/auth/userinfo.email'] }),
  function(req, res){
    // The request will be redirected to Google for authentication, so this
    // function will not be called.
  });

router.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
    res.redirect('/Glucometer');
  });

glucometer.jade - 用户在登录时被定向到的视图。目前,为了在数据库中存储项目,我只是让用户手动输入用户名。但显然这是不可靠的,我应该让用户输入读数,应用程序将处理时间戳/用户名条目。

extends layout

block content
        h1.
                Glucometer Application
        table
                thead
                        tr
                                th Username
                                th Timestamp
                                th Blood Sugar
                tbody
                        each reading, i in glucometer
                                tr
                                        td #{reading.username}
                                        td #{reading.Timestamp}
                                        td #{reading.Bloodsugar}

        h1.
                Add An Entry
        form#formAddEntry(name="glucometer",method="post",action="/glucometer")
                input#inputUserName(type="text", placeholder="Username", name="username")
                input#inputTimestamp(type="text", placeholder="Timestamp", name="Timestamp")
                input#inputBloodsugar(type="text", placeholder="Blood Sugar", name="Bloodsugar")
                button#btnSubmit(type="submit") submit

        a(href='/logout') Logout

0 个答案:

没有答案