feat: oauth2 login (wip)

This commit is contained in:
Nick 2019-04-21 02:04:00 -04:00
parent 6fe49309c1
commit 8af21c02af
7 changed files with 67 additions and 26 deletions

View File

@ -189,7 +189,7 @@ export default {
this.screen = 'login' this.screen = 'login'
if (!strategy.useForm) { if (!strategy.useForm) {
this.isLoading = true this.isLoading = true
window.location.assign(this.$helpers.resolvePath('login/' + strategy.key)) window.location.assign('/login/' + strategy.key)
} else { } else {
this.$nextTick(() => { this.$nextTick(() => {
this.$refs.iptEmail.focus() this.$refs.iptEmail.focus()

View File

@ -67,6 +67,7 @@
"emoji-regex": "8.0.0", "emoji-regex": "8.0.0",
"express": "4.16.4", "express": "4.16.4",
"express-brute": "1.0.1", "express-brute": "1.0.1",
"express-session": "1.16.1",
"file-type": "10.7.1", "file-type": "10.7.1",
"filesize": "4.0.0", "filesize": "4.0.0",
"fs-extra": "7.0.1", "fs-extra": "7.0.1",

View File

@ -8,10 +8,30 @@ const _ = require('lodash')
/** /**
* Login form * Login form
*/ */
router.get('/login', function (req, res, next) { router.get('/login', (req, res, next) => {
_.set(res.locals, 'pageMeta.title', 'Login') _.set(res.locals, 'pageMeta.title', 'Login')
res.render('login') res.render('login')
}) })
router.get('/login/:strategy', async (req, res, next) => {
try {
const authResult = await WIKI.models.users.login({
strategy: req.params.strategy
}, { req, res })
console.info(authResult)
} catch (err) {
next(err)
}
})
router.get('/login/:strategy/callback', async (req, res, next) => {
try {
const authResult = await WIKI.models.users.login({
strategy: req.params.strategy
}, { req, res })
console.info(authResult)
} catch (err) {
next(err)
}
})
/** /**
* Logout * Logout

View File

@ -4,6 +4,7 @@ const compression = require('compression')
const cookieParser = require('cookie-parser') const cookieParser = require('cookie-parser')
const cors = require('cors') const cors = require('cors')
const express = require('express') const express = require('express')
const session = require('express-session')
const favicon = require('serve-favicon') const favicon = require('serve-favicon')
const fs = require('fs-extra') const fs = require('fs-extra')
const http = require('http') const http = require('http')
@ -65,6 +66,11 @@ module.exports = async () => {
// ---------------------------------------- // ----------------------------------------
app.use(cookieParser()) app.use(cookieParser())
app.use(session({
secret: WIKI.config.sessionSecret,
resave: false,
saveUninitialized: false
}))
app.use(WIKI.auth.passport.initialize()) app.use(WIKI.auth.passport.initialize())
app.use(WIKI.auth.authenticate) app.use(WIKI.auth.authenticate)

View File

@ -154,10 +154,11 @@ module.exports = class User extends Model {
// Model Methods // Model Methods
// ------------------------------------------------ // ------------------------------------------------
static async processProfile(profile) { static async processProfile({ profile, provider }) {
// -> Parse email
let primaryEmail = '' let primaryEmail = ''
if (_.isArray(profile.emails)) { if (_.isArray(profile.emails)) {
let e = _.find(profile.emails, ['primary', true]) const e = _.find(profile.emails, ['primary', true])
primaryEmail = (e) ? e.value : _.first(profile.emails).value primaryEmail = (e) ? e.value : _.first(profile.emails).value
} else if (_.isString(profile.email) && profile.email.length > 5) { } else if (_.isString(profile.email) && profile.email.length > 5) {
primaryEmail = profile.email primaryEmail = profile.email
@ -166,30 +167,29 @@ module.exports = class User extends Model {
} else if (profile.user && profile.user.email && profile.user.email.length > 5) { } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
primaryEmail = profile.user.email primaryEmail = profile.user.email
} else { } else {
return Promise.reject(new Error(WIKI.lang.t('auth:errors.invaliduseremail'))) return Promise.reject(new Error('Missing or invalid email address from profile.'))
} }
profile.provider = _.lowerCase(profile.provider)
primaryEmail = _.toLower(primaryEmail) primaryEmail = _.toLower(primaryEmail)
// -> Find user
let user = await WIKI.models.users.query().findOne({ let user = await WIKI.models.users.query().findOne({
email: primaryEmail, email: primaryEmail,
provider: profile.provider providerKey: provider
}) })
if (user) { if (user) {
user.$query().patchAdnFetch({ user.$query().patchAdnFetch({
email: primaryEmail, email: primaryEmail,
provider: profile.provider, providerKey: provider,
providerId: profile.id, providerId: profile.id,
name: profile.displayName || _.split(primaryEmail, '@')[0] name: _.get(profile, 'displayName', primaryEmail.split('@')[0])
}) })
} else { } else {
user = await WIKI.models.users.query().insertAndFetch({ // user = await WIKI.models.users.query().insertAndFetch({
email: primaryEmail, // email: primaryEmail,
provider: profile.provider, // providerKey: provider,
providerId: profile.id, // providerId: profile.id,
name: profile.displayName || _.split(primaryEmail, '@')[0] // name: profile.displayName || _.split(primaryEmail, '@')[0]
}) // })
} }
// Handle unregistered accounts // Handle unregistered accounts
@ -215,12 +215,20 @@ module.exports = class User extends Model {
static async login (opts, context) { static async login (opts, context) {
if (_.has(WIKI.auth.strategies, opts.strategy)) { if (_.has(WIKI.auth.strategies, opts.strategy)) {
_.set(context.req, 'body.email', opts.username) const strInfo = _.find(WIKI.data.authentication, ['key', opts.strategy])
_.set(context.req, 'body.password', opts.password)
// Inject form user/pass
if (strInfo.useForm) {
_.set(context.req, 'body.email', opts.username)
_.set(context.req, 'body.password', opts.password)
}
// Authenticate // Authenticate
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
WIKI.auth.passport.authenticate(opts.strategy, { session: false }, async (err, user, info) => { WIKI.auth.passport.authenticate(opts.strategy, {
session: !strInfo.useForm,
scope: strInfo.scopes ? strInfo.scopes.join(' ') : null
}, async (err, user, info) => {
if (err) { return reject(err) } if (err) { return reject(err) }
if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) } if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
@ -239,7 +247,7 @@ module.exports = class User extends Model {
} }
} else { } else {
// No 2FA, log in user // No 2FA, log in user
return context.req.logIn(user, { session: false }, async err => { return context.req.logIn(user, { session: !strInfo.useForm }, async err => {
if (err) { return reject(err) } if (err) { return reject(err) }
const jwtToken = await WIKI.models.users.refreshToken(user) const jwtToken = await WIKI.models.users.refreshToken(user)
resolve({ resolve({

View File

@ -14,12 +14,14 @@ module.exports = {
clientID: conf.clientId, clientID: conf.clientId,
clientSecret: conf.clientSecret, clientSecret: conf.clientSecret,
callbackURL: conf.callbackURL callbackURL: conf.callbackURL
}, function (accessToken, refreshToken, profile, cb) { }, async (accessToken, refreshToken, extraParams, profile, cb) => {
WIKI.models.users.processProfile(profile).then((user) => { console.info(accessToken, refreshToken, extraParams, profile)
return cb(null, user) || true try {
}).catch((err) => { const user = WIKI.models.users.processProfile({ profile, provider: 'auth0' })
return cb(err, null) || true cb(null, user)
}) } catch (err) {
cb(err, null)
}
} }
)) ))
} }

View File

@ -7,6 +7,10 @@ color: deep-orange
website: https://auth0.com/ website: https://auth0.com/
isAvailable: true isAvailable: true
useForm: false useForm: false
scopes:
- openid
- profile
- email
props: props:
domain: domain:
type: String type: String