You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.0 KiB

  1. /* global WIKI */
  2. const express = require('express')
  3. const router = express.Router()
  4. const moment = require('moment')
  5. const _ = require('lodash')
  6. /**
  7. * Login form
  8. */
  9. router.get('/login', (req, res, next) => {
  10. _.set(res.locals, 'pageMeta.title', 'Login')
  11. res.render('login')
  12. })
  13. router.get('/login/:strategy', async (req, res, next) => {
  14. try {
  15. await WIKI.models.users.login({
  16. strategy: req.params.strategy
  17. }, { req, res })
  18. } catch (err) {
  19. next(err)
  20. }
  21. })
  22. router.all('/login/:strategy/callback', async (req, res, next) => {
  23. if (req.method !== 'GET' && req.method !== 'POST') { return next() }
  24. try {
  25. const authResult = await WIKI.models.users.login({
  26. strategy: req.params.strategy
  27. }, { req, res })
  28. res.cookie('jwt', authResult.jwt, { expires: moment().add(1, 'y').toDate() })
  29. res.redirect('/')
  30. } catch (err) {
  31. next(err)
  32. }
  33. })
  34. /**
  35. * Logout
  36. */
  37. router.get('/logout', function (req, res) {
  38. req.logout()
  39. res.redirect('/')
  40. })
  41. /**
  42. * Register form
  43. */
  44. router.get('/register', async (req, res, next) => {
  45. _.set(res.locals, 'pageMeta.title', 'Register')
  46. const localStrg = await WIKI.models.authentication.getStrategy('local')
  47. if (localStrg.selfRegistration) {
  48. res.render('register')
  49. } else {
  50. next(new WIKI.Error.AuthRegistrationDisabled())
  51. }
  52. })
  53. /**
  54. * Verify
  55. */
  56. router.get('/verify/:token', async (req, res, next) => {
  57. const usr = await WIKI.models.userKeys.validateToken({ kind: 'verify', token: req.params.token })
  58. await WIKI.models.users.query().patch({ isVerified: true }).where('id', usr.id)
  59. const result = await WIKI.models.users.refreshToken(usr)
  60. res.cookie('jwt', result.token, { expires: moment().add(1, 'years').toDate() })
  61. res.redirect('/')
  62. })
  63. /**
  64. * JWT Public Endpoints
  65. */
  66. router.get('/.well-known/jwk.json', function (req, res, next) {
  67. res.json(WIKI.config.certs.jwk)
  68. })
  69. router.get('/.well-known/jwk.pem', function (req, res, next) {
  70. res.send(WIKI.config.certs.public)
  71. })
  72. module.exports = router