From cc33e4932a321c5e0c0e047cb5842c9a5073a3fe Mon Sep 17 00:00:00 2001 From: Lilian Abiven Date: Mon, 10 Oct 2022 11:50:42 +0200 Subject: [PATCH] add module to authenticate with a jwt token --- .../authentication/jwt/authentication.js | 41 +++++++++++++++++++ .../modules/authentication/jwt/definition.yml | 15 +++++++ 2 files changed, 56 insertions(+) create mode 100644 server/modules/authentication/jwt/authentication.js create mode 100644 server/modules/authentication/jwt/definition.yml diff --git a/server/modules/authentication/jwt/authentication.js b/server/modules/authentication/jwt/authentication.js new file mode 100644 index 00000000..238e8367 --- /dev/null +++ b/server/modules/authentication/jwt/authentication.js @@ -0,0 +1,41 @@ +/* global WIKI */ + +// ------------------------------------ +// JWT Token +// ------------------------------------ + +const JwtStrategy = require('passport-jwt').Strategy +const ExtractJwt = require('passport-jwt').ExtractJwt + +module.exports = { + init (passport, conf) { + passport.use(conf.key, + new JwtStrategy({ + algorithms: ['HS256'], + secretOrKey: conf.jwtSecret, + jwtFromRequest: ExtractJwt.fromUrlQueryParameter('auth_token') + }, async (jwtPayload, cb) => { + try { + if (jwtPayload.iat == null) { + throw new WIKI.Error.AuthLoginFailed() + } + const millisElapsed = Date.now() - jwtPayload.iat * 1000 + const minutesElapsed = Math.floor(millisElapsed / 1000 / 60) + if (minutesElapsed > 60) { + throw new WIKI.Error.AuthLoginFailed() + } + const user = await WIKI.models.users.processProfile({ + providerKey: jwtPayload.providerKey, + profile: { + id: jwtPayload.id, + email: jwtPayload.email + } + }) + cb(null, user) + } catch (err) { + cb(err, null) + } + }) + ) + } +} diff --git a/server/modules/authentication/jwt/definition.yml b/server/modules/authentication/jwt/definition.yml new file mode 100644 index 00000000..b7b62fdd --- /dev/null +++ b/server/modules/authentication/jwt/definition.yml @@ -0,0 +1,15 @@ +key: jwt +title: JWT +description: Authenticate via JWT token +author: Lilian Abiven +logo: https://static.requarks.io/logo/wikijs.svg +color: primary +website: https://wiki.js.org +isAvailable: true +useForm: false +props: + jwtSecret: + type: String + title: JWT secret + hint: JWT secret + order: 1