LoginSignup
0
0

【Cognito】メール認証、電話認証をせずにユーザー認証させるように頑張ってみたお話

Posted at

結論

ユーザー登録後(ここ重要)lambdaで強制的に権限を変更する
つまり、登録からログインする前に何かしらでlambdaを起動させる必要がある

サインアップフォーム

signin.tsx
import React, { useState } from 'react';
import { CognitoUserAttribute, CognitoUserPool } from 'amazon-cognito-identity-js';
import { poolData } from '../../../../lib/cognito';


export const SignUp = () => {
  const router = useRouter()
  const [state, setState] = useState({
    password: '',
    email: '',
    error: ''
  });

  const handleChange = (event) => {
    setState({
      ...state,
      [event.target.name]: event.target.value
    });
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const { password, email } = state;

    const attributeList = [
      new CognitoUserAttribute({ Name: 'email', Value: email }),

    ];

    poolData.signUp(email, password, attributeList, null, (err, result) => {
      if (err) {
        setState({ ...state, error: err.message });
        return;
      }
      alert('登録完了しました。メールアドレスを確認してください。');
    });
  };

  const authexe = async () => {
    // fetchでapiの実行
    const url = `url`;
    let method = "POST";
    let headers = {
      "Content-Type": "application/json",
    };
    const body = JSON.stringify({ userName: state.email })
    // urlに対してPOSTリクエストを送る
    await fetch(url, { method, headers, body })
      .then((response) => {
        alert(JSON.stringify(response));
        return response;
      })

  }

  return (
    <form onSubmit={handleSubmit} className={style.signupForm}>
      <h1>Sign Up</h1>
      {state.error && <p style={{ color: 'red' }}>{state.error}</p>}

    <input
          type="text"
          name="email"
          value={state.email}
          placeholder="メールアドレス"
          onChange={handleChange}
          required={true}
        />

    <input
          type="password"
          name="password"
          value={state.password}
          placeholder="パスワード"
          onChange={handleChange}
          required={true}
        />

    <div onClick={onClick}> Sign Up </div>
    <div onClick={authexe}> 認証ボタン </div>
    </form>
  );
};

lambdaの認証強制書き換えコード

lambda
import json
import boto3

def lambda_handler(event, context):
    client = boto3.client('cognito-idp')
    user_pool_id = "自分のユーザープールID"
    user_name = event['userName']

    # ユーザー属性を更新して確認済みに設定
    client.admin_update_user_attributes(
        UserPoolId=user_pool_id,
        Username=user_name,
        UserAttributes=[
            {
                'Name': 'email_verified',
                'Value': 'true'
            },
        ]
    )

    # ユーザーの認証ステータスを更新
    client.admin_confirm_sign_up(
        UserPoolId=user_pool_id,
        Username=user_name
    )
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

詰まってたところ

PreSignUp_SignUpを利用してこのコードを実行すると「ユーザーが見つからないよ!」というエラーが出ました。
これ、実行タイミング的にユーザー追加する前に実行されるみたいなので、ここでは実行できないみたいですね

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0