2020-04-29 02:04:42 -05:00
|
|
|
import { handleLogin, handleTokenRevocation } from '@server/lib/auth'
|
2020-04-23 04:36:50 -05:00
|
|
|
import * as RateLimit from 'express-rate-limit'
|
|
|
|
import { CONFIG } from '@server/initializers/config'
|
|
|
|
import * as express from 'express'
|
|
|
|
import { Hooks } from '@server/lib/plugins/hooks'
|
|
|
|
import { asyncMiddleware, authenticate } from '@server/middlewares'
|
2020-08-13 08:07:23 -05:00
|
|
|
import { ScopedToken } from '@shared/models/users/user-scoped-token'
|
|
|
|
import { v4 as uuidv4 } from 'uuid'
|
2020-04-23 04:36:50 -05:00
|
|
|
|
|
|
|
const tokensRouter = express.Router()
|
|
|
|
|
|
|
|
const loginRateLimiter = RateLimit({
|
|
|
|
windowMs: CONFIG.RATES_LIMIT.LOGIN.WINDOW_MS,
|
|
|
|
max: CONFIG.RATES_LIMIT.LOGIN.MAX
|
|
|
|
})
|
|
|
|
|
|
|
|
tokensRouter.post('/token',
|
|
|
|
loginRateLimiter,
|
2020-04-29 02:04:42 -05:00
|
|
|
handleLogin,
|
2020-04-23 04:36:50 -05:00
|
|
|
tokenSuccess
|
|
|
|
)
|
|
|
|
|
|
|
|
tokensRouter.post('/revoke-token',
|
|
|
|
authenticate,
|
2020-04-24 04:33:01 -05:00
|
|
|
asyncMiddleware(handleTokenRevocation)
|
2020-04-23 04:36:50 -05:00
|
|
|
)
|
|
|
|
|
2020-08-13 08:07:23 -05:00
|
|
|
tokensRouter.get('/scoped-tokens',
|
|
|
|
authenticate,
|
|
|
|
getScopedTokens
|
|
|
|
)
|
|
|
|
|
|
|
|
tokensRouter.post('/scoped-tokens',
|
|
|
|
authenticate,
|
|
|
|
asyncMiddleware(renewScopedTokens)
|
|
|
|
)
|
|
|
|
|
2020-04-23 04:36:50 -05:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
|
|
|
tokensRouter
|
|
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function tokenSuccess (req: express.Request) {
|
|
|
|
const username = req.body.username
|
|
|
|
|
|
|
|
Hooks.runAction('action:api.user.oauth2-got-token', { username, ip: req.ip })
|
|
|
|
}
|
2020-08-13 08:07:23 -05:00
|
|
|
|
|
|
|
function getScopedTokens (req: express.Request, res: express.Response) {
|
|
|
|
const user = res.locals.oauth.token.user
|
|
|
|
|
|
|
|
return res.json({
|
|
|
|
feedToken: user.feedToken
|
|
|
|
} as ScopedToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
async function renewScopedTokens (req: express.Request, res: express.Response) {
|
|
|
|
const user = res.locals.oauth.token.user
|
|
|
|
|
|
|
|
user.feedToken = uuidv4()
|
|
|
|
await user.save()
|
|
|
|
|
|
|
|
return res.json({
|
|
|
|
feedToken: user.feedToken
|
|
|
|
} as ScopedToken)
|
|
|
|
}
|