Example 1
Input
can admin delete can viewer write who publish
Expected output
can admin delete: true can viewer write: false who publish: admin, editor
Example 2
Input
can editor publish who read
Expected output
can editor publish: true who read: admin, editor, viewer
6 hidden tests · Limit 2 s · 256 MB
Bạn đang viết phần phân quyền cho một CMS. Có 3 vai trò và 4 hành động:
| Vai trò | Được phép |
|---|---|
admin | read, write, delete, publish |
editor | read, write, publish |
viewer | read |
Hoàn thiện code khởi đầu:
PERMISSIONS theo đúng bảng trên. Giữ as const satisfies Record<Role, readonly Action[]> để compiler báo lỗi nếu thiếu vai trò hoặc gõ sai tên hành động.isRole(x: string): x is Role — type predicate kiểm tra chuỗi có phải vai trò hợp lệ.can(role: string, action: string): boolean — role và action đến từ request (chuỗi bất kỳ). Vai trò lạ hoặc hành động lạ → false.rolesFor(action: string): Role[] — danh sách vai trò được làm action, theo thứ tự trong ROLES.Ví dụ
can("editor", "publish"); // true
can("viewer", "write"); // false
can("guest", "read"); // false
rolesFor("publish"); // ["admin", "editor"]WARNING
Chuỗi từ người dùng có thể là "toString" hay "constructor". PERMISSIONS["toString"] không phải undefined (nó là hàm kế thừa từ Object.prototype)! Đừng dùng role in PERMISSIONS để kiểm tra vai trò.
Định dạng chấm: mỗi dòng input là can <role> <action> hoặc who <action>; trình chấm in kết quả tương ứng.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
type Action = "read" | "write" | "delete" | "publish";
const PERMISSIONS = {
// TODO: admin, editor, viewer
} as const satisfies Record<Role, readonly Action[]>;
function isRole(x: string): x is Role {
// TODO
}
function can(role: string, action: string): boolean {
// TODO
}
function rolesFor(action: string): Role[] {
// TODO
}
Comments