我正在尝试将Everyauth用于Google OAuth2,如果Google在我公司的Google Apps域中向用户发送用户,我只希望身份验证成功。我无法弄清楚如何根据findOrCreateUser的参数优雅地中止身份验证。
express = require "express"
everyauth = require "everyauth"
app = express()
nextUserId = 0
usersById = {}
app.get "/", (req, res) ->
res.send "Secret"
everyauth.everymodule
.findUserById (id, callback) ->
callback null, usersById[id]
everyauth.google
.appId(process.env.GOOGLE_CLIENT_ID)
.appSecret(process.env.GOOGLE_CLIENT_SECRET)
.scope("...")
.redirectPath("/")
.findOrCreateUser (session, token, extra, googleUser) ->
# I want to abort authentication if googleUser.email != foo
# Redirecting to /unauthorized would be awesome but I don't know how
googleUser.id = nextUserId++
usersById[googleUser.id] = googleUser
app.use express.cookieParser()
app.use express.session { secret: "secret" }
app.use everyauth.middleware()
app.listen process.env.PORT
答案 0 :(得分:1)
根据https://github.com/bnoguchi/everyauth/issues/206的线索,下面的代码可以按您的要求运行。请注意,代码顺序很重要,我不得不将app.use调用移到文件的后面,以使会话正常工作。
express = require "express"
everyauth = require "everyauth"
util = require "util"
everyauth.everymodule
.findUserById (req, id, callback) ->
callback(null, usersById[id])
everyauth.google
.appId(process.env.GOOGLE_CLIENT_ID)
.appSecret(process.env.GOOGLE_CLIENT_SECRET)
.scope("https://www.googleapis.com/auth/userinfo.email")
.redirectPath("/")
.findOrCreateUser (session, token, extra, googleUser) ->
#console.log(util.inspect(googleUser))
if googleUser.email == "some.user@gmail.com"
return null
else
return usersById[googleUser.id] = googleUser
.sendResponse (res, data) ->
user = data.user
if !user
return this.redirect(res, '/failure')
this.redirect(res, "/")
app = express()
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session({secret: "SECRETIVE"})
app.use everyauth.middleware()
nextUserId = 0
usersById = {}
app.get "/", (req, res) ->
if req.loggedIn
res.send "You are logged in as " + req.user.email + ". Click <a href='/logout'>here to logout</a>"
else
res.send "click <a href='/auth/google'>here to login</a>"
app.get "/failure", (req, res) ->
# clear the login stuff from the session since we went through auth
# but didn't set a user object. This makes req.loggedIn return false.
req.logout()
res.send "Victory has defeated you."
app.listen process.env.PORT
console.log('listening on ', process.env.PORT)