Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: プロフィール画像を登録する API を作成 #256

Merged
merged 20 commits into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/backend/lambda/upload_profile_image/upload_profile_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import base64
import logging
import os

import boto3

# ログ設定
logger = logging.getLogger()
logger.setLevel(logging.INFO)


def decode_image_data(encoded_body):
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved
"""
Base64 エンコードされた画像データをデコード

Args:
encoded_body (string): Base64 エンコードされた画像データ。

Returns:
bytes: デコードされた画像データ。

Raises:
ValueError: `encoded_body` が無効な Base64 データの場合。
"""
try:
return base64.b64decode(encoded_body)
except Exception as e:
raise ValueError("Invalid base64-encoded image data") from e
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved


def upload_to_s3(key, data, content_type="image/png"):
"""
S3 に画像データをアップロード

Args:
key (string): S3 バケット内のファイルのキー(パス)。
data (bytes): アップロードする画像データ。
content_type (string): 画像のコンテンツタイプ(デフォルトは "image/png")。

Raises:
RuntimeError: S3 アップロード中にエラーが発生した場合。
"""
# S3 クライアントの初期化
s3_client = boto3.client("s3")
# S3 バケット名
bucket = os.environ["USER_SETTINGS_BUCKET"]
try:
s3_client.put_object(
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved
Bucket=bucket, Key=key, Body=data, ContentType=content_type
)
logger.info(f"Image uploaded successfully to {bucket}/{key}")
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved
except Exception as e:
raise RuntimeError(f"Failed to upload image to S3: {str(e)}") from e


def lambda_handler(event, context):
"""
Lambda 関数のエントリーポイント。API Gateway からのリクエストを処理し、ユーザーのプロフィール画像を S3 にアップロード。

Args:
event (dict): API Gateway からのリクエストイベント。
context (object): Lambda 実行環境の情報。

Returns:
dict: レスポンスコードとメッセージを含む辞書。
"""
logger.info("upload profile image function")
try:
# Cognito Authorizer から user_id を取得
user_id = event["requestContext"]["authorizer"]["claims"]["sub"]
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved

# リクエストの body から画像データを取得
body = event.get("body", "")
image_data = decode_image_data(body)

# S3 パスを設定
s3_key = f"profile/image/{user_id}.png"

# S3 にアップロード
upload_to_s3(s3_key, image_data)

# 成功レスポンスを返す
return {
"statusCode": 200,
"body": f"Profile image uploaded successfully for user_id: {user_id}",
}

except ValueError as ve:
logger.error(f"Validation error: {str(ve)}")
return {"statusCode": 400, "body": f"Invalid input: {str(ve)}"}
except RuntimeError as re:
logger.error(f"Runtime error: {str(re)}")
return {"statusCode": 500, "body": f"Server error: {str(re)}"}
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return {"statusCode": 500, "body": f"Failed to upload image: {str(e)}"}
8 changes: 7 additions & 1 deletion src/backend/lib/backend-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as cdk from 'aws-cdk-lib'
import * as acm from 'aws-cdk-lib/aws-certificatemanager'
import * as s3 from 'aws-cdk-lib/aws-s3'
import type { Construct } from 'constructs'
import { Api, Auth, Bouquet, Flower, Identity, Web } from './constructs'
import { Api, Auth, Bouquet, Flower, Identity, Settings, Web } from './constructs'
import { Diary } from './constructs/diary'

interface BackendStackProps extends cdk.StackProps {}
Expand Down Expand Up @@ -71,6 +71,12 @@ export class BackendStack extends cdk.Stack {
flowerImageBucket: flower.flowerImageBucket,
})

const settings = new Settings(this, 'Settings', {
userPool: auth.userPool,
api: api.api,
cognitoAuthorizer: api.cognitoAuthorizer,
})

const web = new Web(this, 'Web', {
userPool: auth.userPool,
userPoolClient: auth.userPoolClient,
Expand Down
1 change: 1 addition & 0 deletions src/backend/lib/constructs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export * from './auth'
export * from './bouquet'
export * from './flower'
export * from './identity'
export * from './settings'
export * from './web'
43 changes: 43 additions & 0 deletions src/backend/lib/constructs/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as cdk from 'aws-cdk-lib'
import * as apigateway from 'aws-cdk-lib/aws-apigateway'
import type * as cognito from 'aws-cdk-lib/aws-cognito'
import * as lambda from 'aws-cdk-lib/aws-lambda'
import * as s3 from 'aws-cdk-lib/aws-s3'
import { Construct } from 'constructs'

export interface SettingsProps {
userPool: cognito.UserPool
api: apigateway.RestApi
cognitoAuthorizer: apigateway.CognitoUserPoolsAuthorizer
}

export class Settings extends Construct {
constructor(scope: Construct, id: string, props: SettingsProps) {
super(scope, id)

// プロフィール画像保存用のS3バケットの作成
const userSettingsBucket = new s3.Bucket(this, 'userSettingsBucket', {
mt-osho-san marked this conversation as resolved.
Show resolved Hide resolved
enforceSSL: true,
serverAccessLogsPrefix: 'log/',
})

//プロフィール画像アップロード用Lambda関数の定義
const uploadProfileImageFunction = new lambda.Function(this, 'uploadProfileImageFunction', {
runtime: lambda.Runtime.PYTHON_3_11,
handler: 'upload_profile_image.lambda_handler',
timeout: cdk.Duration.seconds(15),
code: lambda.Code.fromAsset('lambda/upload_profile_image'),
environment: {
USER_SETTINGS_BUCKET: userSettingsBucket.bucketName,
},
})
userSettingsBucket.grantPut(uploadProfileImageFunction)

// /APIの設定
const settingsApi = props.api.root.addResource('settings')

settingsApi.addMethod('POST', new apigateway.LambdaIntegration(uploadProfileImageFunction), {
authorizer: props.cognitoAuthorizer,
})
}
}
Loading
Loading