役割で認可する
役割 で認可します。Cognito の グループ admin に入っている人は、だれのノートでも消せるようにします。グループはアクセストークンの cognito:groups に入るので、API はトークンを見るだけで分かります。
グループと管理者を作る
Section titled “グループと管理者を作る”セットアップのスクリプトで、グループ admin と、そこに入れる管理者のユーザー admin@example.com を作ります。
apps/api/scripts/setup-cognito.js を変更する
Section titled “apps/api/scripts/setup-cognito.js を変更する”3636 ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],3737});3838
39// 管理者のグループ(admin)と、そこに入れる管理者のユーザー(admin@example.com)40await cognito('CreateGroup', { UserPoolId: UserPool.Id, GroupName: 'admin' });41await cognito('AdminCreateUser', {42 UserPoolId: UserPool.Id,43 Username: 'admin@example.com',44 UserAttributes: [45 { Name: 'email', Value: 'admin@example.com' },46 { Name: 'email_verified', Value: 'true' },47 ],48 MessageAction: 'SUPPRESS',49});50await cognito('AdminSetUserPassword', {51 UserPoolId: UserPool.Id,52 Username: 'admin@example.com',53 Password: 'Passw0rd!',54 Permanent: true,55});56await cognito('AdminAddUserToGroup', {57 UserPoolId: UserPool.Id,58 Username: 'admin@example.com',59 GroupName: 'admin',60});61
3962// API が読む設定(.env)4063await writeFile(4164 '.env',4770 `${JSON.stringify({ issuer: `${endpoint}/${UserPool.Id}`, clientId: UserPoolClient.ClientId })}\n`,4871);4972console.log(50 `ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId} を作り、.env と apps/ui/config.json に書きました`,73 `ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId}、admin グループと admin@example.com を作り、.env と apps/ui/config.json に書きました`,5174);CreateGroup… グループを作りますAdminCreateUser・AdminSetUserPassword… サインアップの画面を通さずにユーザーを作り、パスワードを決めます(MessageAction: 'SUPPRESS'で、招待のメールは送りません)AdminAddUserToGroup… ユーザーをグループに入れます
admin なら消せるようにする
Section titled “admin なら消せるようにする”apps/api/src/notes/notes.controller.ts を変更する
Section titled “apps/api/src/notes/notes.controller.ts を変更する”7373if (!note) {7474 throw new NotFoundException(`Note ${id} not found`);7575}76// 作った人でなければ 40377if (note.ownerId !== user.sub) {76// admin グループの人は、だれのノートでも消せる77const isAdmin = user['cognito:groups']?.includes('admin') ?? false;78// 作った人でも admin でもなければ 40379if (note.ownerId !== user.sub && !isAdmin) {7880 throw new ForbiddenException();7981}8082this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);user['cognito:groups']… トークンに入っているグループの配列です。グループに入っていない人には、この項目がありません
動作確認する
Section titled “動作確認する”スクリプトを変えたので、Floci を起動し直して作り直します。Floci のユーザーは消えるので、alice と bob はサインアップし直します。
podman compose downpodman compose up -d --build --waitnode apps/api/scripts/setup-cognito.jspodman compose up -d --waithttp://localhost:3000/login.html で admin@example.com と Passw0rd! でログインし、出たアクセストークンの中身を見ます。
node -e "console.log(JSON.parse(Buffer.from(process.argv[1].split('.')[1], 'base64url')))" <アクセストークン>'cognito:groups': [ 'admin' ] が入っていれば大丈夫です。
alice と bob をサインアップし直し、alice のトークンでノートを作ります。そのノートを、bob と admin のトークンで消します。
curl -i -X DELETE http://localhost:3001/notes/21a481a3-b808-4653-a833-89ffe6a9db37 -H 'Authorization: Bearer <bob のアクセストークン>'curl -i -X DELETE http://localhost:3001/notes/21a481a3-b808-4653-a833-89ffe6a9db37 -H 'Authorization: Bearer <admin のアクセストークン>'1 行目が、順に HTTP/1.1 403 Forbidden、HTTP/1.1 204 No Content になれば大丈夫です。
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- Amazon Cognito: Adding groups to a user pool … グループと、トークンの
cognito:groups - Amazon Cognito API: CreateGroup … グループを作る
- Amazon Cognito API: AdminCreateUser …
MessageAction - Amazon Cognito API: AdminSetUserPassword …
Permanent - Amazon Cognito API: AdminAddUserToGroup … ユーザーをグループに入れる