コンテンツにスキップ

サインアップ画面を作る

05 章 サインアップ画面を作る

いまは誰でもノートを作れます。この章では、03 章で設計したとおりに、ログインした人だけがノートを作れる ようにします(認証)。

この節では、Cognito のエミュレーター Floci を起動してユーザープールを作り、ユーザーを登録する サインアップ画面 を作ります。

サインアップ画面が Cognito(Floci)に SignUp を送ると、Cognito が確認コードをメールで送る。Floci はメールを /_aws/ses にためておくので、そこで読んだ確認コードを ConfirmSignUp で送る

compose.yaml に Floci を足します。

compose.yaml
10
10
DB_PATH: /data/notes.db
11
11
volumes:
12
12
- db:/data
13
# apps/api/scripts/setup-cognito.js が書いた、ユーザープール ID とクライアント ID
14
env_file:
15
- path: .env
16
required: false
13
17
14
18
web:
15
19
# 画面(apps/ui/)を配るだけの静的サーバー
compose.yaml
20
24
volumes:
21
25
- ./apps/ui:/usr/share/nginx/html:ro
22
26
27
# Cognito のエミュレーター
28
floci:
29
image: docker.io/floci/floci:2.4.0
30
ports:
31
# ほかのマシンから届かないよう、ループバックにだけ公開する(Floci は認証なしで API を受け付ける)
32
- "127.0.0.1:4566:4566"
33
environment:
34
# トークンの発行元(iss)を、API のコンテナから届く http://floci:4566 にする
35
FLOCI_BASE_URL: http://floci:4566
36
# 画面(http://localhost:3000)から Cognito の API を直接呼べるようにする
37
FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS: http://localhost:3000
38
healthcheck:
39
# 起動が終わったか(/_floci/health が 200 を返すか)を確かめる
40
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/4566 && printf 'GET /_floci/health HTTP/1.0\\r\\n\\r\\n' >&3 && read -r status <&3 && [[ $$status == *' 200 '* ]]"]
41
interval: 3s
42
timeout: 3s
43
retries: 20
44
23
45
volumes:
24
46
# SQLite のファイルを置く場所。コンテナを作り直しても残る
25
47
db:
  • env_file … 次に作るスクリプトが書く .env(ユーザープール ID とクライアント ID)を、API のコンテナに渡します
  • FLOCI_BASE_URL … 発行するトークンの発行元を http://floci:4566 にします。compose の中では、ほかのコンテナに サービス名(floci)で届くので、API のコンテナから確かめられる名前にしておきます
  • FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS … 画面(http://localhost:3000)から Floci を直接呼ぶので、その呼び出しを許します

Cognito の API を呼んで、ユーザープールとアプリケーションクライアントを作るスクリプトです。作った ID を、API が読む .env と、画面が読む apps/ui/config.json に書き出します。

apps/api/scripts/setup-cognito.js を作成する

Section titled “apps/api/scripts/setup-cognito.js を作成する”
apps/api/scripts/setup-cognito.js
1
// Floci の Cognito に、ユーザープールとアプリケーションクライアントを作り、ID を書き出す。
2
// Floci は止めるとデータが消えるので、Floci を起動し直したらもう一度実行する。
3
import { writeFile } from 'node:fs/promises';
4
5
const endpoint = 'http://localhost:4566';
6
7
// Cognito の API を 1 つ呼ぶ。Floci は AWS の認証情報を確かめないので、付けずに呼べる
8
async function cognito(action, params) {
9
const response = await fetch(endpoint, {
10
method: 'POST',
11
headers: {
12
'content-type': 'application/x-amz-json-1.1',
13
'x-amz-target': `AWSCognitoIdentityProviderService.${action}`,
14
},
15
body: JSON.stringify(params),
16
});
17
const json = await response.json();
18
if (!response.ok)
19
throw new Error(`${action}: ${json.__type} ${json.message}`);
20
return json;
21
}
22
23
// ユーザープール。メールアドレスでサインインし、サインアップのときにメールで確認コードを送る
24
const { UserPool } = await cognito('CreateUserPool', {
25
PoolName: 'notes',
26
UsernameAttributes: ['email'],
27
AutoVerifiedAttributes: ['email'],
28
});
29
30
// アプリケーションクライアント。ブラウザは秘密を守れないので、クライアントシークレットは持たせない。
31
// メールアドレスとパスワードでのログイン(USER_PASSWORD_AUTH)を許す
32
const { UserPoolClient } = await cognito('CreateUserPoolClient', {
33
UserPoolId: UserPool.Id,
34
ClientName: 'notes',
35
GenerateSecret: false,
36
ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],
37
});
38
39
// API が読む設定(.env)
40
await writeFile(
41
'.env',
42
`COGNITO_USER_POOL_ID=${UserPool.Id}\nCOGNITO_CLIENT_ID=${UserPoolClient.ClientId}\n`,
43
);
44
// 画面が読む設定。どのユーザープールに、どのクライアントとしてログインするか(どれもブラウザに渡る値で、秘密ではない)
45
await writeFile(
46
'apps/ui/config.json',
47
`${JSON.stringify({ issuer: `${endpoint}/${UserPool.Id}`, clientId: UserPoolClient.ClientId })}\n`,
48
);
49
console.log(
50
`ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId} を作り、.env と apps/ui/config.json に書きました`,
51
);
  • AutoVerifiedAttributes: ['email'] … サインアップしたら、メールで確認コードを送ります
  • GenerateSecret: false … ブラウザで動くコードは誰でも中身を見られるので、クライアントシークレットは持たせません
  • ALLOW_USER_PASSWORD_AUTH … メールアドレスとパスワードでのログインを許します(次の節)

画面が使う部品を apps/ui/lib/ に足します。config.js は config.json を読み、cognito.js は Cognito の API を呼びます。

apps/ui/lib/config.js
1
// apps/api/scripts/setup-cognito.js が書き出す config.json を読む。どのユーザープールに、どのクライアントとしてログインするか(作り直したときに古い値を使わないよう、キャッシュしない)
2
const response = await fetch('/config.json', { cache: 'no-store' });
3
if (!response.ok) {
4
document.body.insertAdjacentHTML('afterbegin', '<p class="error">config.json がありません。<code>node apps/api/scripts/setup-cognito.js</code> を実行してから、読み込み直してください</p>');
5
throw new Error('config.json がありません');
6
}
7
export const config = await response.json();
8
9
// Cognito の API の入口は、issuer のオリジン(Floci は http://localhost:4566、本物は https://cognito-idp.<リージョン>.amazonaws.com)
10
export const cognitoEndpoint = new URL(config.issuer).origin;
apps/ui/lib/cognito.js
1
import { cognitoEndpoint, config } from './config.js';
2
3
// 画面から Cognito の API を 1 つ呼ぶ。
4
// サインアップやログインの API は、AWS の認証情報なしで、クライアント ID だけで呼べる
5
export async function cognito(action, params) {
6
const response = await fetch(cognitoEndpoint, {
7
method: 'POST',
8
headers: {
9
'content-type': 'application/x-amz-json-1.1',
10
'x-amz-target': `AWSCognitoIdentityProviderService.${action}`,
11
},
12
body: JSON.stringify({ ClientId: config.clientId, ...params }),
13
});
14
const json = await response.json();
15
// 失敗すると {"__type":"UsernameExistsException","message":"..."} の形で返る
16
if (!response.ok) throw new Error(`${json.__type}: ${json.message}`);
17
return json;
18
}
  • どの操作かを x-amz-target ヘッダーで伝えます。サインアップやログインの API は、クライアント ID だけで呼べます
apps/ui/signup.html
1
<!doctype html>
2
<html lang="ja">
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1">
6
<title>サインアップ</title>
7
<link rel="stylesheet" href="./style.css">
8
</head>
9
<body>
10
<h1>サインアップ</h1>
11
12
<form id="sign-up">
13
<label>メールアドレス <input name="email" type="email" required></label>
14
<label>パスワード <input name="password" type="password" required></label>
15
<button>サインアップ</button>
16
</form>
17
18
<form id="confirm" hidden>
19
<label>確認コード <input name="code" required></label>
20
<button>確認する</button>
21
</form>
22
23
<p id="message" class="message"></p>
24
25
<script type="module" src="./signup.js"></script>
26
</body>
27
</html>
apps/ui/signup.js
1
import { cognito } from './lib/cognito.js';
2
3
const message = document.querySelector('#message');
4
let email;
5
6
// 1. メールアドレスとパスワードで登録する。Cognito がメールで確認コードを送る
7
document.querySelector('#sign-up').addEventListener('submit', async (event) => {
8
event.preventDefault();
9
const form = new FormData(event.target);
10
email = form.get('email');
11
try {
12
await cognito('SignUp', {
13
Username: email,
14
Password: form.get('password'),
15
UserAttributes: [{ Name: 'email', Value: email }],
16
});
17
document.querySelector('#confirm').hidden = false;
18
message.textContent = '確認コードを送りました';
19
} catch (error) {
20
message.textContent = error.message;
21
}
22
});
23
24
// 2. 届いた確認コードを送って、登録を確定する
25
document.querySelector('#confirm').addEventListener('submit', async (event) => {
26
event.preventDefault();
27
const form = new FormData(event.target);
28
try {
29
await cognito('ConfirmSignUp', { Username: email, ConfirmationCode: form.get('code') });
30
message.textContent = 'サインアップできました';
31
} catch (error) {
32
message.textContent = error.message;
33
}
34
});
  • SignUp … メールアドレスとパスワードで登録します。Cognito が確認コードをメールで送ります
  • ConfirmSignUp … 届いた確認コードを送ると、登録が確定します

ルートで起動し、ユーザープールを作ってから、.env を読ませるためにもう一度起動します。.env はルートに置かれ、compose.yaml が API のコンテナに渡します。

ターミナルウィンドウ
podman compose up -d --build --wait
node apps/api/scripts/setup-cognito.js
podman compose up -d --wait
ユーザープール us-east-1_6511add1f とクライアント 49d9ff2864944c0cb99ce8f1e4 を作り、.env と apps/ui/config.json に書きました

http://localhost:3000/signup.html を開き、alice@example.com とパスワード Passw0rd! で サインアップ を押します。

Floci はメールを本当には送らず、手元にためておきます。http://localhost:4566/_aws/ses を開くと、Your verification code is 273386. のように確認コードが読めます。これを入れて 確認する を押し、「サインアップできました」と出れば大丈夫です。

この節は、次の公式ドキュメントをもとに書いています。

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
この節を終えた状態をダウンロード
画面に「config.json がありません」と出る

node apps/api/scripts/setup-cognito.js をまだ実行していないか、Floci を起動し直してユーザープールが消えています。「動作確認する」の 3 つのコマンドをやり直し、読み込み直してください。

Failed to fetch や ResourceNotFoundException と出る

Floci が止まっているか、起動し直してユーザープールが消えています。「動作確認する」の 3 つのコマンドをやり直してください。