좋아요! Windows 환경에서 Google Cloud Functions를 설정하고 JavaScript를 작성하여 인증 시스템을 구현하는 과정을 단계별로 설명드릴게요.
Google Cloud Functions를 배포하려면 Google Cloud CLI가 필요합니다.
1. 다운로드 및 설치:
gcloud --versiongcloud auth loginNode.js는 Google Cloud Functions에서 사용하는 런타임입니다.
1. 다운로드:
node -v
npm -vFirestore로 이동해 활성화합니다.새로운 디렉토리를 만들어 작업을 시작합니다:
mkdir cloud-functions-auth
cd cloud-functions-auth
Node.js 프로젝트 초기화:
npm init -y
Firestore와 통신하기 위해 Firebase Admin SDK를 설치합니다:
npm install firebase-admin firebase-functions
index.js 파일 생성:
디렉토리 내에 index.js 파일을 만듭니다.
코드 작성:
아래 코드를 index.js에 붙여넣습니다:
const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp(); // Firebase Admin SDK 초기화
const db = admin.firestore(); // Firestore 데이터베이스 참조
// 하드웨어 ID 인증 함수
exports.checkLicense = functions.https.onRequest(async (req, res) => {
const hardwareId = req.query.hardwareId; // 클라이언트에서 하드웨어 ID 수신
if (!hardwareId) {
return res.status(400).send("Hardware ID is required.");
}
try {
// Firestore에서 하드웨어 ID 상태 확인
const docRef = db.collection("license_keys").doc(hardwareId);
const doc = await docRef.get();
if (!doc.exists) {
return res.status(404).send("NG"); // 등록되지 않은 ID
}
const { status } = doc.data();
if (status === "approved") {
return res.send("OK"); // 승인된 하드웨어 ID
} else {
return res.status(403).send("NG"); // 거부된 하드웨어 ID
}
} catch (error) {
console.error(error);
return res.status(500).send("NG"); // 서버 오류 발생 시 NG 반환
}
});
Google Cloud CLI에서 프로젝트를 선택합니다:
gcloud config set project [PROJECT_ID]
[PROJECT_ID]는 Google Cloud Console에서 확인할 수 있습니다.
작성한 코드를 Cloud Functions에 배포합니다:
gcloud functions deploy checkLicense \
--runtime nodejs16 \
--trigger-http \
--allow-unauthenticated
--runtime nodejs16: Node.js 16 환경 사용.--trigger-http: HTTP 요청을 통해 트리거.--allow-unauthenticated: 인증 없이 누구나 호출 가능.배포가 완료되면 출력에 URL이 표시됩니다.
예: https://REGION-PROJECT_ID.cloudfunctions.net/checkLicense
Firestore 데이터베이스 열기:
Google Cloud Console에서 Firestore로 이동.
license_keys 컬렉션 생성:
license_keys.1234).status: "approved" 또는 "rejected".예시:
| Document ID | Field Name | Value |
|-------------|------------|------------|
| 1234 | status | approved |
| 5678 | status | rejected |
string serverUrl = "https://REGION-PROJECT_ID.cloudfunctions.net/checkLicense";
하드웨어 ID와 함께 HTTP GET 요청 전송:
GET https://REGION-PROJECT_ID.cloudfunctions.net/checkLicense?hardwareId=1234
서버 응답:
"OK": 인증 성공."NG": 인증 실패.Google Cloud Functions는 요청 시에만 실행되므로 항상 서버를 유지하지 않아도 됩니다!