Skip to content

Instantly share code, notes, and snippets.

@erodactyl
Created August 4, 2021 22:34
Show Gist options
  • Save erodactyl/8cc531d8073484b3c392bfc4939de10e to your computer and use it in GitHub Desktop.
Save erodactyl/8cc531d8073484b3c392bfc4939de10e to your computer and use it in GitHub Desktop.
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