2022-10-29 22:21:24 +02:00
|
|
|
import cors from 'cors'
|
2022-11-05 18:55:59 +01:00
|
|
|
import http from 'passport-http'
|
2022-10-29 22:21:24 +02:00
|
|
|
import jwt from 'passport-jwt'
|
2022-11-05 18:55:59 +01:00
|
|
|
import { ApikeyModel } from './models/apikey.mjs'
|
2023-08-13 10:33:24 +02:00
|
|
|
import { UserModel } from './models/user.mjs'
|
|
|
|
|
|
|
|
/*
|
|
|
|
* In v2 we ended up with a bug where we did not properly track the last login
|
|
|
|
* So in v3 we switch to `lastSeen` and every authenticated API call we update
|
|
|
|
* this field. It's a bit of a perf hit to write to the database on ever API call
|
|
|
|
* but it's worth it to actually know which accounts are used and which are not.
|
|
|
|
*/
|
2023-08-13 10:41:11 +02:00
|
|
|
async function updateLastSeen(uid, tools, type) {
|
2023-08-13 10:33:24 +02:00
|
|
|
const User = new UserModel(tools)
|
2023-08-13 10:41:11 +02:00
|
|
|
await User.seen(uid, type)
|
2023-08-13 10:33:24 +02:00
|
|
|
}
|
2022-10-29 22:21:24 +02:00
|
|
|
|
|
|
|
function loadExpressMiddleware(app) {
|
|
|
|
app.use(cors())
|
|
|
|
}
|
|
|
|
|
2022-11-05 18:55:59 +01:00
|
|
|
function loadPassportMiddleware(passport, tools) {
|
|
|
|
passport.use(
|
|
|
|
new http.BasicStrategy(async (key, secret, done) => {
|
|
|
|
const Apikey = new ApikeyModel(tools)
|
|
|
|
await Apikey.verify(key, secret)
|
2023-08-13 10:33:24 +02:00
|
|
|
/*
|
|
|
|
* Update lastSeen field
|
|
|
|
*/
|
2023-08-13 10:41:11 +02:00
|
|
|
if (Apikey.verified) await updateLastSeen(Apikey.record.userId, tools, 'key')
|
2023-08-13 10:33:24 +02:00
|
|
|
|
2022-11-08 21:04:32 +01:00
|
|
|
return Apikey.verified
|
|
|
|
? done(null, { ...Apikey.record, apikey: true, uid: Apikey.record.userId })
|
|
|
|
: done(false)
|
2022-11-05 18:55:59 +01:00
|
|
|
})
|
|
|
|
)
|
2022-10-29 22:21:24 +02:00
|
|
|
passport.use(
|
|
|
|
new jwt.Strategy(
|
|
|
|
{
|
|
|
|
jwtFromRequest: jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
|
2022-11-05 18:55:59 +01:00
|
|
|
...tools.config.jwt,
|
2022-10-29 22:21:24 +02:00
|
|
|
},
|
2023-08-13 10:33:24 +02:00
|
|
|
async (jwt_payload, done) => {
|
|
|
|
/*
|
|
|
|
* Update lastSeen field
|
|
|
|
*/
|
2023-08-13 10:41:11 +02:00
|
|
|
await updateLastSeen(jwt_payload._id, tools, 'jwt')
|
2023-08-13 10:33:24 +02:00
|
|
|
|
2022-11-12 17:33:55 +01:00
|
|
|
return done(null, {
|
|
|
|
...jwt_payload,
|
|
|
|
uid: jwt_payload._id,
|
2023-05-06 12:52:26 +02:00
|
|
|
level: tools.config.roles.levels[jwt_payload.role] || 0,
|
2022-11-12 17:33:55 +01:00
|
|
|
})
|
2022-10-29 22:21:24 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-10-29 22:25:00 +02:00
|
|
|
export { loadExpressMiddleware, loadPassportMiddleware }
|