|
| 1 | +import { CognitoIdentityProviderClient, GetUserCommand } from '@aws-sdk/client-cognito-identity-provider' |
1 | 2 | import { APIGatewayProxyEventV2WithJWTAuthorizer, APIGatewayProxyResultV2 } from 'aws-lambda' |
2 | 3 | import { error, internalServerError, unAuthorized } from '../../utils/httpError' |
3 | 4 |
|
| 5 | +const cognitoClient = new CognitoIdentityProviderClient({}) |
| 6 | + |
4 | 7 | export const handler = async (event: APIGatewayProxyEventV2WithJWTAuthorizer): Promise<APIGatewayProxyResultV2> => { |
5 | 8 | try { |
6 | | - const claims = event.requestContext.authorizer?.jwt?.claims |
7 | | - if (!claims) return error(unAuthorized(), 'ERR_GET_USER_UNAUTHORIZED') |
| 9 | + const authHeader = event.headers.authorization || event.headers.Authorization |
| 10 | + if (!authHeader) return error(unAuthorized(), 'ERR_GET_USER_NO_AUTH_HEADER') |
8 | 11 |
|
9 | | - const userInfo = { |
10 | | - // username: claims['cognito:username'], |
11 | | - // email: claims.email, |
12 | | - // sub: claims.sub, |
13 | | - // email_verified: claims.email_verified, |
14 | | - ...claims, |
15 | | - } |
| 12 | + const token = authHeader.split(' ')[1] // 'Bearer xxx' |
| 13 | + if (!token) return error(unAuthorized(), 'ERR_GET_USER_NO_TOKEN') |
| 14 | + |
| 15 | + const getUserCommand = new GetUserCommand({ AccessToken: token }) |
| 16 | + const response = await cognitoClient.send(getUserCommand) |
| 17 | + |
| 18 | + const userAttributes = Object.fromEntries( |
| 19 | + (response.UserAttributes || []).map((attr) => [attr.Name, attr.Value]) |
| 20 | + ) |
16 | 21 |
|
17 | 22 | return { |
18 | 23 | statusCode: 200, |
19 | | - body: JSON.stringify(userInfo), |
| 24 | + body: JSON.stringify({ |
| 25 | + username: response.Username, |
| 26 | + ...userAttributes, |
| 27 | + }), |
20 | 28 | } |
21 | 29 | } catch (err) { |
22 | 30 | return error(internalServerError((err as Error).message), 'ERR_GET_USER_INTERNAL_SERVER_ERROR') |
|
0 commit comments