auth.js 1.96 KB
Newer Older
1
/* global WIKI */
2

3 4
const express = require('express')
const router = express.Router()
5
const moment = require('moment')
6
const _ = require('lodash')
NGPixel's avatar
NGPixel committed
7 8 9 10

/**
 * Login form
 */
Nick's avatar
Nick committed
11
router.get('/login', (req, res, next) => {
12
  _.set(res.locals, 'pageMeta.title', 'Login')
13
  res.render('login')
14
})
Nick's avatar
Nick committed
15 16
router.get('/login/:strategy', async (req, res, next) => {
  try {
Nick's avatar
Nick committed
17
    await WIKI.models.users.login({
Nick's avatar
Nick committed
18 19 20 21 22 23
      strategy: req.params.strategy
    }, { req, res })
  } catch (err) {
    next(err)
  }
})
Nick's avatar
Nick committed
24 25 26
router.all('/login/:strategy/callback', async (req, res, next) => {
  if (req.method !== 'GET' && req.method !== 'POST') { return next() }

Nick's avatar
Nick committed
27 28 29 30
  try {
    const authResult = await WIKI.models.users.login({
      strategy: req.params.strategy
    }, { req, res })
31 32
    res.cookie('jwt', authResult.jwt, { expires: moment().add(1, 'y').toDate() })
    res.redirect('/')
Nick's avatar
Nick committed
33 34 35 36
  } catch (err) {
    next(err)
  }
})
NGPixel's avatar
NGPixel committed
37 38 39 40

/**
 * Logout
 */
41 42 43 44
router.get('/logout', function (req, res) {
  req.logout()
  res.redirect('/')
})
NGPixel's avatar
NGPixel committed
45

46 47 48
/**
 * Register form
 */
49
router.get('/register', async (req, res, next) => {
50
  _.set(res.locals, 'pageMeta.title', 'Register')
51 52 53 54 55 56
  const localStrg = await WIKI.models.authentication.getStrategy('local')
  if (localStrg.selfRegistration) {
    res.render('register')
  } else {
    next(new WIKI.Error.AuthRegistrationDisabled())
  }
57 58
})

59 60 61 62 63 64 65 66 67 68 69
/**
 * Verify
 */
router.get('/verify/:token', async (req, res, next) => {
  const usr = await WIKI.models.userKeys.validateToken({ kind: 'verify', token: req.params.token })
  await WIKI.models.users.query().patch({ isVerified: true }).where('id', usr.id)
  const result = await WIKI.models.users.refreshToken(usr)
  res.cookie('jwt', result.token, { expires: moment().add(1, 'years').toDate() })
  res.redirect('/')
})

70 71 72 73 74 75 76 77 78 79
/**
 * JWT Public Endpoints
 */
router.get('/.well-known/jwk.json', function (req, res, next) {
  res.json(WIKI.config.certs.jwk)
})
router.get('/.well-known/jwk.pem', function (req, res, next) {
  res.send(WIKI.config.certs.public)
})

80
module.exports = router