]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - shared/core-utils/plugins/hooks.ts
Redirect to default login url on 401
[github/Chocobozzz/PeerTube.git] / shared / core-utils / plugins / hooks.ts
index 047c04f7b63a426b11c767c314399ad9c63cf683..96bcc945e895e195eab3317d0cea83290064692e 100644 (file)
@@ -1,5 +1,6 @@
+import { RegisteredExternalAuthConfig } from '@shared/models'
 import { HookType } from '../../models/plugins/hook-type.enum'
-import { isCatchable, isPromise } from '../miscs/miscs'
+import { isCatchable, isPromise } from '../common/promises'
 
 function getHookType (hookName: string) {
   if (hookName.startsWith('filter:')) return HookType.FILTER
@@ -8,25 +9,39 @@ function getHookType (hookName: string) {
   return HookType.STATIC
 }
 
-async function internalRunHook (handler: Function, hookType: HookType, param: any, onError: (err: Error) => void) {
-  let result = param
+async function internalRunHook <T> (options: {
+  handler: Function
+  hookType: HookType
+  result: T
+  params: any
+  onError: (err: Error) => void
+}) {
+  const { handler, hookType, result, params, onError } = options
 
   try {
-    const p = handler(result)
+    if (hookType === HookType.FILTER) {
+      const p = handler(result, params)
 
-    switch (hookType) {
-      case HookType.FILTER:
-        if (isPromise(p)) result = await p
-        else result = p
-        break
+      const newResult = isPromise(p)
+        ? await p
+        : p
 
-      case HookType.STATIC:
-        if (isPromise(p)) await p
-        break
+      return newResult
+    }
+
+    // Action/static hooks do not have result value
+    const p = handler(params)
+
+    if (hookType === HookType.STATIC) {
+      if (isPromise(p)) await p
+
+      return undefined
+    }
+
+    if (hookType === HookType.ACTION) {
+      if (isCatchable(p)) p.catch((err: any) => onError(err))
 
-      case HookType.ACTION:
-        if (isCatchable(p)) p.catch(err => onError(err))
-        break
+      return undefined
     }
   } catch (err) {
     onError(err)
@@ -35,7 +50,12 @@ async function internalRunHook (handler: Function, hookType: HookType, param: an
   return result
 }
 
+function getExternalAuthHref (apiUrl: string, auth: RegisteredExternalAuthConfig) {
+  return apiUrl + `/plugins/${auth.name}/${auth.version}/auth/${auth.authName}`
+}
+
 export {
   getHookType,
-  internalRunHook
+  internalRunHook,
+  getExternalAuthHref
 }