我們在前一篇,說明了使用 DynamoDB 的好處後,這邊就是來實作了。
import json, boto3, bcrypt
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("vlog-nipapa-tw-user")
def lambda_handler(event, context):
body = json.loads(event["body"])
username = body["username"]
password = body["password"]
# 密碼 Hash
pw_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
# 存入 DynamoDB
table.put_item(Item={"username": username, "password_hash": pw_hash})
return {"statusCode": 200, "body": json.dumps({"message": "User registered"})}
- 前端:只負責輸入密碼,交給 API(必須用 HTTPS!)。
- Lambda:
> 註冊:bcrypt.hashpw() → 存 hash
> 登入:bcrypt.checkpw() → 驗證- 永遠不要在 DB 裡存前端算好的 hash。
import json, boto3, bcrypt, jwt, os
SECRET = os.environ.get("JWT_SECRET", "mysecret")
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("vlog-nipapa-tw-user")
def lambda_handler(event, context):
body = json.loads(event["body"])
username = body["username"]
password = body["password"]
# 查 DB
resp = table.get_item(Key={"username": username})
if "Item" not in resp:
return {"statusCode": 401, "body": json.dumps({"error": "User not found"})}
pw_hash = resp["Item"]["password_hash"]
if not bcrypt.checkpw(password.encode("utf-8"), pw_hash.encode("utf-8")):
return {"statusCode": 401, "body": json.dumps({"error": "Invalid password"})}
# 產生 JWT
token = jwt.encode({"username": username}, SECRET, algorithm="HS256")
return {"statusCode": 200, "body": json.dumps({"token": token})}
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form id="loginForm">
<input type="text" id="username" placeholder="Username" required><br>
<input type="password" id="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
<script>
document.getElementById("loginForm").addEventListener("submit", async (e) => {
e.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const res = await fetch("https://vlog.nipapa.tw/prod/login", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({ username, password })
});
const data = await res.json();
if (data.token) {
localStorage.setItem("jwt", data.token);
window.location.href = "main.html"; // 成功跳轉
} else {
alert("Login failed");
}
});
</script>
</body>
</html>