-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
191 lines (149 loc) · 5.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/lestrrat-go/jwx/jwk"
"github.com/keitakn/go-cognito-lambda/domain"
"github.com/keitakn/go-cognito-lambda/infrastructure/repository"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/keitakn/go-cognito-lambda/infrastructure"
)
type RequestBody struct {
UserPoolClientId string `json:"userPoolClientId"`
Email string `json:"email"`
Password string `json:"password"`
}
type IdTokenDetail struct {
Jwt string `json:"jwt"`
Payload domain.CognitoIdToken `json:"payload"`
}
type AccessTokenDetail struct {
Jwt string `json:"jwt"`
Payload domain.CognitoAccessToken `json:"payload"`
}
type ResponseCreatedBody struct {
IdToken IdTokenDetail `json:"idToken"`
AccessToken AccessTokenDetail `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
type ResponseErrorBody struct {
Message string `json:"message"`
}
var svc *cognitoidentityprovider.CognitoIdentityProvider
var iss string
var jwkSet jwk.Set
//nolint:gochecknoinits
func init() {
sess, err := session.NewSession()
if err != nil {
// TODO ここでエラーが発生した場合、致命的な問題が起きているのでちゃんとしたログを出すように改修する
log.Fatalln(err)
}
svc = cognitoidentityprovider.New(sess, &aws.Config{
Region: aws.String(os.Getenv("REGION")),
})
iss = fmt.Sprintf(
"https://cognito-idp.%v.amazonaws.com/%v",
os.Getenv("REGION"),
os.Getenv("TARGET_USER_POOL_ID"),
)
cognitoJwkRepository := &repository.HttpCognitoJwkRepository{
Iss: iss,
}
res, err := cognitoJwkRepository.Fetch()
if err != nil {
// TODO ここでエラーが発生した場合、致命的な問題が起きているのでちゃんとしたログを出すように改修する
log.Fatalln(err)
}
jwkSet = res
}
func createApiGatewayV2Response(statusCode int, resBodyJson []byte) events.APIGatewayV2HTTPResponse {
res := events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{
"Content-Type": "application/json",
},
Body: string(resBodyJson),
IsBase64Encoded: false,
}
return res
}
// TODO リファクタリングするまでの間、一時的に関数が大きい状態を許容する
//nolint:funlen
func Handler(
ctx context.Context, req events.APIGatewayV2HTTPRequest,
) (events.APIGatewayV2HTTPResponse, error) {
var reqBody RequestBody
if err := json.Unmarshal([]byte(req.Body), &reqBody); err != nil {
resBody := &ResponseErrorBody{Message: "Bad Request"}
resBodyJson, _ := json.Marshal(resBody)
res := createApiGatewayV2Response(infrastructure.BadRequest, resBodyJson)
return res, err
}
input := &cognitoidentityprovider.InitiateAuthInput{
AuthFlow: aws.String("USER_PASSWORD_AUTH"),
AuthParameters: map[string]*string{
"USERNAME": aws.String(reqBody.Email),
"PASSWORD": aws.String(reqBody.Password),
},
ClientId: aws.String(reqBody.UserPoolClientId),
}
resp, err := svc.InitiateAuth(input)
if err != nil {
// TODO 本来はライブラリのエラーメッセージをそのまま返してはいけない、適切なエラーメッセージに変換して返す事を推奨
errorMessage := err.Error()
resBody := &ResponseErrorBody{Message: errorMessage}
resBodyJson, _ := json.Marshal(resBody)
res := createApiGatewayV2Response(infrastructure.BadRequest, resBodyJson)
return res, nil
}
cognitoJwtTokenRepository := &repository.JwxCognitoJwtTokenRepository{
Iss: iss,
Aud: reqBody.UserPoolClientId,
JwkSet: jwkSet,
}
idTokenPayload, err := cognitoJwtTokenRepository.ParseAndValidateIdToken(*resp.AuthenticationResult.IdToken)
if err != nil {
errorMessage := err.Error()
resBody := &ResponseErrorBody{Message: errorMessage}
resBodyJson, _ := json.Marshal(resBody)
res := createApiGatewayV2Response(infrastructure.BadRequest, resBodyJson)
return res, nil
}
idTokenDetail := &IdTokenDetail{
Jwt: *resp.AuthenticationResult.IdToken,
Payload: *idTokenPayload,
}
accessTokenPayload, err := cognitoJwtTokenRepository.ParseAndValidateAccessToken(
*resp.AuthenticationResult.AccessToken,
)
if err != nil {
errorMessage := err.Error()
resBody := &ResponseErrorBody{Message: errorMessage}
resBodyJson, _ := json.Marshal(resBody)
res := createApiGatewayV2Response(infrastructure.BadRequest, resBodyJson)
return res, nil
}
accessTokenDetail := &AccessTokenDetail{
Jwt: *resp.AuthenticationResult.AccessToken,
Payload: *accessTokenPayload,
}
resBody := &ResponseCreatedBody{
IdToken: *idTokenDetail,
AccessToken: *accessTokenDetail,
RefreshToken: *resp.AuthenticationResult.RefreshToken,
}
resBodyJson, _ := json.Marshal(resBody)
res := createApiGatewayV2Response(infrastructure.Created, resBodyJson)
return res, nil
}
func main() {
lambda.Start(Handler)
}