Last active
December 19, 2015 06:29
-
-
Save kikuchy/5912004 to your computer and use it in GitHub Desktop.
Passportを使ったテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies. | |
*/ | |
var express = require('express') | |
, routes = require('./routes') | |
, http = require('http') | |
, path = require('path'); | |
// ハッシュ値を求めるために必要なもの | |
var crypto = require("crypto"); | |
var secretKey = "some_random_secret"; // シークレットは適当に変えてください | |
var getHash = function(target){ | |
var sha = crypto.createHmac("sha256", secretKey); | |
sha.update(target); | |
return sha.digest("hex"); | |
}; | |
// passportで必要なもの | |
var flash = require("connect-flash") | |
, passport = require("passport") | |
, LocalStrategy = require("passport-local").Strategy; | |
// MongoDBを使うのに必要なもの | |
var mongoose = require("mongoose"); | |
// ユーザーのモデルを作成 | |
var db = mongoose.createConnection("mongodb://localhost/passporttest", function(error, res){}); | |
var UserSchema = new mongoose.Schema({ | |
email: {type: String, required: true}, | |
password: {type: String, requird: true} | |
}); | |
var User = db.model("User", UserSchema); | |
// サーバー起動時にユーザーが無ければ、テスト用のデータを投入します。 | |
// 間違っても本番用のサーバーにこんなコードを入れちゃ駄目です。 | |
if(User.count({}) == 0){ | |
var aaaUser = new User(); | |
aaaUser.email = "aaa@example.com"; | |
aaaUser.password = getHash("aaa"); | |
aaaUser.save(); | |
} | |
// passportでのセッション設定 | |
// シリアライズの設定をしないと、user.passwordでパスワードがポロリする可能性があるので、必要な項目だけ持たせる | |
passport.serializeUser(function(user, done){ | |
done(null, {email: user.email, _id: user._id}); | |
}); | |
passport.deserializeUser(function(serializedUser, done){ | |
User.findById(serializedUser._id, function(err, user){ | |
done(err, user); | |
}); | |
}); | |
// LOcalStrategyを使う設定 | |
passport.use(new LocalStrategy( | |
// フォームの名前をオプションとして渡す。 | |
// 今回はusernameの代わりにemailを使っているので、指定が必要 | |
{usernameField: "email", passwordField: "password"}, | |
function(email, password, done){ | |
// 非同期で処理させるといいらしいです | |
process.nextTick(function(){ | |
User.findOne({email: email}, function(err, user){ | |
if(err) | |
return done(err); | |
if(!user) | |
return done(null, false, {message: "ユーザーが見つかりませんでした。"}); | |
var hashedPassword = getHash(password); | |
if(user.password !== hashedPassword) | |
return done(null, false, {message: "パスワードが間違っています。"}); | |
return done(null, user); | |
}); | |
}); | |
})); | |
// リクエストがあったとき、ログイン済みかどうか確認する関数 | |
var isLogined = function(req, res, next){ | |
if(req.isAuthenticated()) | |
return next(); // ログイン済み | |
// ログインしてなかったらログイン画面に飛ばす | |
res.redirect("/login"); | |
}; | |
var app = express(); | |
// all environments | |
app.set('port', process.env.PORT || 3000); | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'jade'); | |
app.use(express.favicon()); | |
app.use(express.logger('dev')); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(express.cookieParser()); | |
app.use(express.session({secret: "another_random_sevret_again"})); // こちらにも別のシークレットが必要です | |
// app.router を使う前にpassportの設定が必要です | |
app.use(flash()); | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
app.use(app.router); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
// development only | |
if ('development' == app.get('env')) { | |
app.use(express.errorHandler()); | |
} | |
app.get('/', routes.index); | |
app.get("/login", function(req, res){ | |
res.render("login", {user: req.user, message: req.flash("error")}); | |
}); | |
app.post("/login", | |
passport.authenticate("local", {failureRedirect: '/login', failureFlash: true}), | |
function(req, res){ | |
// ログインに成功したらトップへリダイレクト | |
res.redirect("/"); | |
}); | |
app.get("/logout", function(req, res){ | |
req.logout(); | |
res.redirect("/"); | |
}); | |
app.get("/member_only", isLogined, function(req, res){ | |
res.render("member_only", {user: req.user}); | |
}); | |
http.createServer(app).listen(app.get('port'), function(){ | |
console.log('Express server listening on port ' + app.get('port')); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends layout | |
block content | |
h1= title | |
p | |
a(href="/login") login | |
br | |
a(href="/logout") logout | |
br | |
a(href="/member_only") Member only page |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends layout | |
block content | |
if(message) | |
p= message | |
form(action="/login", method="post") | |
input(type="text", name="email", placeholder="Email") | |
br | |
input(type="password", name="password", placeholder="Password") | |
input(type="submit", value="Login") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends layout | |
block content | |
h1 It's member only page!! | |
p Welcome, #{user.email} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "application-name", | |
"version": "0.0.1", | |
"private": true, | |
"scripts": { | |
"start": "node app.js" | |
}, | |
"dependencies": { | |
"express": "3.3.1", | |
"jade": "*", | |
"passport": "*", | |
"passport-local": "*", | |
"connect-flash": "*", | |
"mongoose": "*" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment