Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
intrn(policy): use model chain to check for ownership
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethTrecy committed Sep 11, 2022
1 parent c1d3619 commit a25e10c
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions server/policies/belongs_to_current_user.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,43 @@
import type { AuthenticatedIDRequest } from "!/types/dependent"
import type { BaseManagerClass } from "!/types/independent"
import type { AuthenticatedRequest } from "!/types/dependent"
import type { DeserializedUserProfile } from "$/types/documents/user"

import isUndefined from "$/type_guards/is_undefined"
import deserialize from "$/object/deserialize"
import AuthorizationError from "$!/errors/authorization"
import AuthenticationBasedPolicy from "!/policies/authentication-based"

/**
* Creates a policy to limit the operation to the owner of the resource.
* Creates a policy to limit the operation to the owner of the resource only.
*
* Requires that the resource has been validated ID route parameter which is then compared if the
* current logged in user has the same primary ID.
* Requires that the resource represented by `id` parameter is owned by the current logged in user.
*
* Hint: If the resource can be processed by other users through advance permissions, do not use
* the policy.
*/
export default class extends AuthenticationBasedPolicy {
constructor() {
private readonly Class: BaseManagerClass

constructor(managerClass: BaseManagerClass) {
super(true)

this.Class = managerClass
}

async authorize(request: AuthenticatedIDRequest): Promise<void> {
async authorize(request: AuthenticatedRequest): Promise<void> {
await super.authorize(request)

if (isUndefined(request.params.id)) {
throw new AuthorizationError("Resource ID should be provided.")
}

const user = deserialize(request.user) as DeserializedUserProfile
if (String(user.data.id) !== String(request.params.id)) {
const manager = new this.Class(request.transaction, request.cache)
if (!await manager.isModelBelongsTo(
Number(request.params.id),
Number(user.data.id),
manager.modelChainToUser
)) {
throw new AuthorizationError("Only the owner of the resource can do the operation.")
}
}
Expand Down

0 comments on commit a25e10c

Please sign in to comment.