Skip to content

Instantly share code, notes, and snippets.

@yutakahashi114
Created June 28, 2021 12:46
Show Gist options
  • Save yutakahashi114/cec3b852b6abface3fcd772cd2c13985 to your computer and use it in GitHub Desktop.
Save yutakahashi114/cec3b852b6abface3fcd772cd2c13985 to your computer and use it in GitHub Desktop.
import (
"encoding/json"
"fmt"
"math/rand"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/gofrs/uuid"
)
func adminCreateUser(body []byte) ([]byte, error) {
in := cognitoidentityprovider.AdminCreateUserInput{}
err := json.Unmarshal(body, &in)
if err != nil {
return nil, err
}
var userPoolID UserPoolID
if in.UserPoolId != nil {
userPoolID = UserPoolID(*in.UserPoolId)
}
var username Username
if in.Username != nil {
username = Username(*in.Username)
}
if in.MessageAction != nil && *in.MessageAction == "RESEND" {
if _, exist := userPool.GetUser(userPoolID, username); !exist {
return nil, fmt.Errorf("user not found")
}
// TODO: パスワード変更して通知メール再送信
return json.Marshal(cognitoidentityprovider.AdminCreateUserOutput{})
}
var email string
for _, attr := range in.UserAttributes {
if attr.Name == nil || attr.Value == nil {
continue
}
if *attr.Name == "email" {
email = *attr.Value
}
}
// TODO: email_verified が true ならパスワードメール送信, false なら検証メール送信
// 常にtrueとして扱っている
if email == "" {
return nil, fmt.Errorf("invalid email")
}
id, err := uuid.NewV4()
if err != nil {
return nil, err
}
pass, err := makeRandomStr(8)
if err != nil {
return nil, err
}
idString := id.String()
user := User{
UUID: idString,
Password: pass,
Username: username,
Email: email,
EmailVerified: true,
}
err = userPool.CreateUser(userPoolID, user)
if err != nil {
return nil, err
}
return json.Marshal(cognitoidentityprovider.AdminCreateUserOutput{
User: &cognitoidentityprovider.UserType{
Attributes: []*cognitoidentityprovider.AttributeType{
{
Name: &[]string{"sub"}[0],
Value: &[]string{idString}[0],
},
},
},
})
}
func makeRandomStr(digit uint32) (string, error) {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@&%/:;,."
b := make([]byte, digit)
if _, err := rand.Read(b); err != nil {
return "", err
}
var result string
for _, v := range b {
result += string(letters[int(v)%len(letters)])
}
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment