1

我正在尝试将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
4

1 回答 1

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)
于 2013-06-25T17:00:34.583 回答