Guards
Guards are classes that are decorated with the @Injectable()
decorator and implement the CanActivate
interface. A guard is responsible for determining if a request should be handled by a route handler or route. Guards are executed after every middleware, but before pipes. Unlike middleware, guards have access to the ExecutionContext
object, so they know exactly what is going to evaluated.
In our blog application, we use the CheckLoggedInUserGuard
in the UserController
to only allow a user to access and access their own user information.
import
{
Injectable
,
CanActivate
,
ExecutionContext
}
from
'@nestjs/common'
;
import
{
Observable
}
from
'rxjs'
;
@
Injectable
()
export
class
CheckLoggedInUserGuard
implements
CanActivate
{
canActivate
(
context
:ExecutionContext
)
:
boolean
|
Promise
<
boolean
>
|
Observable
<
boolean
>
{
const
req
=
context
.
switchToHttp
().
getRequest
();
return
Number
(
req
.
params
.
userId
)
===
req
.
user
.
id
;
...