【バックエンド】ユーザー登録機能【Heroku+Nest.js】
Nest.jsとAWS CognitoでSignup APIを作成する手順について説明します。以下は大まかな手順です:
まず、Nest.jsプロジェクトをセットアップします:
nest new cognito-signup-api
cd cognito-signup-api次に、必要なパッケージをインストールします:
npm install @nestjs/config @aws-sdk/client-cognito-identity-providerAWS Cognitoの設定が済んでいることを前提に、Nest.jsでのSignup APIの実装を行います。
auth.service.tsファイルを作成し、以下のようなコードを実装します:
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CognitoIdentityProviderClient, SignUpCommand } from '@aws-sdk/client-cognito-identity-provider';
@Injectable()
export class AuthService {
private cognitoClient: CognitoIdentityProviderClient;
constructor(private configService: ConfigService) {
this.cognitoClient = new CognitoIdentityProviderClient({
region: this.configService.get('AWS_REGION'),
});
}
async signUp(email: string, username: string, password: string): Promise<SignUpCommandOutput> {
const clientId = this.configService.get<string>('COGNITO_CLIENT_ID');
const clientSecret = this.configService.get<string>('COGNITO_CLIENT_SECRET');
const command = new SignUpCommand({
ClientId: this.configService.get('COGNITO_CLIENT_ID'),
SecretHash: this.calculateSecretHash(username, clientId, clientSecret),
Username: username,
Password: password,
UserAttributes: [
{
Name: 'email',
Value: email,
}
],
});
try {
const response = await this.cognitoClient.send(command);
return response;
} catch (error) {
console.error('Signup failed:', error);
throw new Error('Signup failed');
}
}
}auth.controller.tsファイルを作成し、以下のようなコードを実装します:
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('signin')
async login(@Body() loginDto: { username: string; password: string }) {
return this.authService.login(loginDto.username, loginDto.password);
}
@Post('confirmSignin')
async confirmSignIn(@Body() signUpDto: { username: string; confirmationCode: string }) {
return this.authService.confirmSignIn(signUpDto.username, signUpDto.confirmationCode);
}
@Post('signup')
async signUp(@Body() signUpDto: { email: string; username: string; password: string }) {
return this.authService.signUp(signUpDto.email, signUpDto.username, signUpDto.password);
}
@Post('resendCode')
async resendConfirmationCode(@Body() signUpDto: { email: string}) {
return this.authService.resendConfirmationCode(signUpDto.email);
}
}最後に、app.module.tsファイルを更新して、AuthModuleを含めます:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
AuthModule,
],
})
export class AppModule {}これらの手順に従うことで、Nest.jsとAWS Cognitoを使用したSignup APIを作成できます。環境変数の設定やエラーハンドリングなど、実際の実装ではさらに詳細な設定が必要になる場合があります。
写真撮るの疲れたので横着します