]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/auth.ts
Merge branch 'release/5.0.0' into develop
[github/Chocobozzz/PeerTube.git] / server / middlewares / auth.ts
index f38373624c1cccf006c3be35de067cdf7c552516..e6025c8ce273bf60a13d20c09e118dd65cd91ec4 100644 (file)
@@ -1,12 +1,12 @@
-import * as express from 'express'
+import express from 'express'
 import { Socket } from 'socket.io'
 import { getAccessToken } from '@server/lib/auth/oauth-model'
-import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
+import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
 import { logger } from '../helpers/logger'
 import { handleOAuthAuthenticate } from '../lib/auth/oauth'
 
-function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
-  handleOAuthAuthenticate(req, res, authenticateInQuery)
+function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
+  handleOAuthAuthenticate(req, res)
     .then((token: any) => {
       res.locals.oauth = { token }
       res.locals.authenticated = true
@@ -14,13 +14,13 @@ function authenticate (req: express.Request, res: express.Response, next: expres
       return next()
     })
     .catch(err => {
-      logger.warn('Cannot authenticate.', { err })
+      logger.info('Cannot authenticate.', { err })
 
-      return res.status(err.status)
-        .json({
-          error: 'Token is invalid.',
-          code: err.name
-        })
+      return res.fail({
+        status: err.status,
+        message: 'Token is invalid',
+        type: err.name
+      })
     })
 }
 
@@ -47,14 +47,19 @@ function authenticateSocket (socket: Socket, next: (err?: any) => void) {
     .catch(err => logger.error('Cannot get access token.', { err }))
 }
 
-function authenticatePromiseIfNeeded (req: express.Request, res: express.Response, authenticateInQuery = false) {
+function authenticatePromise (req: express.Request, res: express.Response) {
   return new Promise<void>(resolve => {
     // Already authenticated? (or tried to)
     if (res.locals.oauth?.token.User) return resolve()
 
-    if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401)
+    if (res.locals.authenticated === false) {
+      return res.fail({
+        status: HttpStatusCode.UNAUTHORIZED_401,
+        message: 'Not authenticated'
+      })
+    }
 
-    authenticate(req, res, () => resolve(), authenticateInQuery)
+    authenticate(req, res, () => resolve())
   })
 }
 
@@ -71,6 +76,6 @@ function optionalAuthenticate (req: express.Request, res: express.Response, next
 export {
   authenticate,
   authenticateSocket,
-  authenticatePromiseIfNeeded,
+  authenticatePromise,
   optionalAuthenticate
 }