SurrealDB 2.1.2
✅ この Surreql を実行すれば、SurrealDB に直接アクセスして会員登録・ログイン・アクセス制御ができる!
-- ユーザーテーブルの定義(SCHEMAFULL)と権限の設定
DEFINE TABLE user SCHEMAFULL PERMISSIONS
FOR select WHERE auth.role = 'admin' OR id = auth.id
FOR create WHERE (((!auth) OR auth.role != 'admin') AND new.role = 'general')
OR (auth AND auth.role = 'admin')
FOR update WHERE auth.role = 'admin' OR id = auth.id
FOR delete WHERE auth.role = 'admin';
-- 各フィールドの定義と検証ルール
DEFINE FIELD username ON TABLE user TYPE string ASSERT $value != "";
DEFINE FIELD email ON TABLE user TYPE string ASSERT string::contains($value, "@");
DEFINE FIELD password ON TABLE user TYPE string;
DEFINE FIELD role ON TABLE user TYPE string ASSERT $value IN ['admin', 'general'];
補足
※ こちらはテーブルのデフォルトフィルターではなく、サインアップ/サインイン処理の定義用です。
DEFINE SCOPEは非推奨。v2.0からDEFINE ACCESS
DEFINE ACCESS user_access ON DATABASE TYPE RECORD
SIGNUP (
CREATE user CONTENT {
username: $username,
email: $email,
pass: crypto::argon2::generate($pass),
role: "general" -- 常に一般ユーザーとして登録する
}
)
SIGNIN (
SELECT * FROM user
WHERE username = $username
AND crypto::argon2::compare(pass, $pass)
);
ユーザー登録の実行例
curl -X POST -H "Content-Type: application/json" \
-d '{
"NS": "test",
"DB": "test",
"AC": "user_access",
"username": "user001",
"email": "user001@example.com",
"pass": "mypassword"
}' \
http://localhost:8000/signup
0 件のコメント:
コメントを投稿