Created
August 4, 2021 22:34
-
-
Save erodactyl/8cc531d8073484b3c392bfc4939de10e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NotLoggedIn } from '../models/errors' | |
const AuthGuardMethods = Symbol('AuthGuardMethods') | |
export function AuthGuard() { | |
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { | |
target[AuthGuardMethods] = target[AuthGuardMethods] || new Map() | |
// Here we just add some information that class decorator will use | |
target[AuthGuardMethods].set(propertyKey, descriptor) | |
} | |
} | |
export function InjectAuth<T extends { new (...args: any[]): {} }>(Base: T): T { | |
return class extends Base { | |
constructor(...args: any[]) { | |
super(...args) | |
const authGuardMethods = Base.prototype[AuthGuardMethods] | |
if (authGuardMethods) { | |
authGuardMethods.forEach((descriptor: PropertyDescriptor, propertyKey: string) => { | |
// @ts-ignore | |
this[propertyKey] = function(...args: any[]) { | |
if (!(this as any).models.user) return Promise.reject(new NotLoggedIn('You must be logged in')) | |
return descriptor.value.apply(this, args) | |
} | |
}) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment