Google Cloud Functions 사용

Chanhongv·2024년 12월 6일

좋아요! Windows 환경에서 Google Cloud Functions를 설정하고 JavaScript를 작성하여 인증 시스템을 구현하는 과정을 단계별로 설명드릴게요.


1. 사전 준비

1) Google Cloud CLI 설치

Google Cloud Functions를 배포하려면 Google Cloud CLI가 필요합니다.
1. 다운로드 및 설치:

  1. 환경 변수 설정 확인:
    설치 후 명령어를 실행하여 설치가 제대로 되었는지 확인:
    gcloud --version
  2. Google 계정 로그인:
    설치가 완료되면 다음 명령어로 Google 계정에 로그인:
    gcloud auth login

2) Node.js 설치

Node.js는 Google Cloud Functions에서 사용하는 런타임입니다.
1. 다운로드:

  1. 설치 확인:
    • 명령어로 설치 확인:
      node -v
      npm -v

3) Google Cloud 프로젝트 설정

  1. 프로젝트 생성:
  2. Firestore 활성화:
    • Firestore는 Google Cloud Console에서 Firestore로 이동해 활성화합니다.
    • Native 모드로 설정.

2. Cloud Functions 구현

1) 작업 폴더 생성

  1. 새로운 디렉토리를 만들어 작업을 시작합니다:

    mkdir cloud-functions-auth
    cd cloud-functions-auth
  2. Node.js 프로젝트 초기화:

    npm init -y

2) Firebase Admin SDK 설치

Firestore와 통신하기 위해 Firebase Admin SDK를 설치합니다:

npm install firebase-admin firebase-functions

3) JavaScript 코드 작성

  1. index.js 파일 생성:
    디렉토리 내에 index.js 파일을 만듭니다.

  2. 코드 작성:
    아래 코드를 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 반환
        }
    });

3. Cloud Functions 배포

1) Google Cloud 프로젝트 선택

Google Cloud CLI에서 프로젝트를 선택합니다:

gcloud config set project [PROJECT_ID]

[PROJECT_ID]는 Google Cloud Console에서 확인할 수 있습니다.


2) Cloud Function 배포

작성한 코드를 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


4. Firestore 데이터베이스 설정

  1. Firestore 데이터베이스 열기:
    Google Cloud Console에서 Firestore로 이동.

  2. license_keys 컬렉션 생성:

    • 컬렉션 이름: license_keys.
    • Document ID: 클라이언트 하드웨어 ID (예: 1234).
    • 필드:
      • status: "approved" 또는 "rejected".

예시:
| Document ID | Field Name | Value |
|-------------|------------|------------|
| 1234 | status | approved |
| 5678 | status | rejected |


5. C#에서 호출 및 테스트

  1. C# 클라이언트 코드에서 아래처럼 URL을 사용:
string serverUrl = "https://REGION-PROJECT_ID.cloudfunctions.net/checkLicense";
  1. 하드웨어 ID와 함께 HTTP GET 요청 전송:

    GET https://REGION-PROJECT_ID.cloudfunctions.net/checkLicense?hardwareId=1234
  2. 서버 응답:

    • "OK": 인증 성공.
    • "NG": 인증 실패.

완료 후 테스트

  1. Firestore에서 승인 상태를 변경하며 테스트.
  2. C# 클라이언트 프로그램과 연동하여 OK/NG 응답에 따라 동작 구현.

Google Cloud Functions는 요청 시에만 실행되므로 항상 서버를 유지하지 않아도 됩니다!

profile
어제보다 더 나은 개발자가 되자

0개의 댓글