lib/src/auth/middleware/GuestRequiredMiddleware.ts

31 lines
1.1 KiB
TypeScript
Raw Normal View History

import {Middleware} from '../../http/routing/Middleware'
import {Inject, Injectable} from '../../di'
2021-11-26 20:32:25 +00:00
import {SecurityContext} from '../context/SecurityContext'
import {ResponseObject} from '../../http/routing/Route'
import {error} from '../../http/response/ErrorResponseFactory'
import {NotAuthorizedError} from '../NotAuthorizedError'
import {HTTPStatus} from '../../util'
2021-07-17 17:49:07 +00:00
import {Routing} from '../../service/Routing'
import {redirect} from '../../http/response/RedirectResponseFactory'
2021-11-26 20:32:25 +00:00
// TODO handle JSON and non-web
@Injectable()
export class GuestRequiredMiddleware extends Middleware {
@Inject()
protected readonly security!: SecurityContext
2021-07-17 17:49:07 +00:00
@Inject()
protected readonly routing!: Routing
async apply(): Promise<ResponseObject> {
if ( this.security.hasUser() ) {
2021-07-17 17:49:07 +00:00
if ( this.routing.hasNamedRoute('@auth.redirectFromGuest') ) {
return redirect(this.routing.getNamedPath('@auth.redirectFromGuest').toRemote)
} else {
return error(new NotAuthorizedError(), HTTPStatus.FORBIDDEN)
}
}
}
}