Init
This commit is contained in:
commit
0029086b3f
148 changed files with 19047 additions and 0 deletions
105
packages/api/src/baseblocks/cognito/cognito-resources.yml
Normal file
105
packages/api/src/baseblocks/cognito/cognito-resources.yml
Normal file
|
@ -0,0 +1,105 @@
|
|||
Resources:
|
||||
CognitoUserPool:
|
||||
Type: AWS::Cognito::UserPool
|
||||
Properties:
|
||||
# Generate a name based on the stage
|
||||
UserPoolName: ${env:APP_NAME}-${opt:stage}-user-pool
|
||||
# Set email as an alias
|
||||
UsernameAttributes:
|
||||
- email
|
||||
AutoVerifiedAttributes:
|
||||
- email
|
||||
UsernameConfiguration:
|
||||
CaseSensitive: false
|
||||
|
||||
CognitoUserPoolClient:
|
||||
Type: AWS::Cognito::UserPoolClient
|
||||
Properties:
|
||||
# Generate an app client name based on the stage
|
||||
ClientName: ${env:APP_NAME}-${opt:stage}-user-pool-client
|
||||
UserPoolId:
|
||||
Ref: CognitoUserPool
|
||||
ExplicitAuthFlows:
|
||||
- ADMIN_NO_SRP_AUTH
|
||||
- USER_PASSWORD_AUTH
|
||||
GenerateSecret: false
|
||||
PreventUserExistenceErrors: ENABLED
|
||||
|
||||
# The federated identity for our user pool to auth with
|
||||
CognitoIdentityPool:
|
||||
Type: AWS::Cognito::IdentityPool
|
||||
Properties:
|
||||
# Generate a name based on the stage
|
||||
IdentityPoolName: ${env:APP_NAME}-${opt:stage}-identity-pool
|
||||
# Don't allow unathenticated users
|
||||
AllowUnauthenticatedIdentities: false
|
||||
# Link to our User Pool
|
||||
CognitoIdentityProviders:
|
||||
- ClientId:
|
||||
Ref: CognitoUserPoolClient
|
||||
ProviderName:
|
||||
Fn::GetAtt: ['CognitoUserPool', 'ProviderName']
|
||||
# IAM roles
|
||||
CognitoIdentityPoolRoles:
|
||||
Type: AWS::Cognito::IdentityPoolRoleAttachment
|
||||
Properties:
|
||||
IdentityPoolId:
|
||||
Ref: CognitoIdentityPool
|
||||
Roles:
|
||||
authenticated:
|
||||
Fn::GetAtt: [CognitoAuthRole, Arn]
|
||||
|
||||
# IAM role used for authenticated users
|
||||
CognitoAuthRole:
|
||||
Type: AWS::IAM::Role
|
||||
Properties:
|
||||
Path: /
|
||||
AssumeRolePolicyDocument:
|
||||
Version: '2012-10-17'
|
||||
Statement:
|
||||
- Effect: 'Allow'
|
||||
Principal:
|
||||
Federated: 'cognito-identity.amazonaws.com'
|
||||
Action:
|
||||
- 'sts:AssumeRoleWithWebIdentity'
|
||||
Condition:
|
||||
StringEquals:
|
||||
'cognito-identity.amazonaws.com:aud':
|
||||
Ref: CognitoIdentityPool
|
||||
'ForAnyValue:StringLike':
|
||||
'cognito-identity.amazonaws.com:amr': authenticated
|
||||
|
||||
# API Gateway authorizer using Cognito
|
||||
ApiGatewayAuthorizer:
|
||||
Type: AWS::ApiGateway::Authorizer
|
||||
Properties:
|
||||
Name: ${env:APP_NAME}-${opt:stage}-api-gateway-authorizer
|
||||
Type: COGNITO_USER_POOLS
|
||||
IdentitySource: method.request.header.Authorization
|
||||
RestApiId:
|
||||
Ref: ApiGatewayRestApi
|
||||
ProviderARNs:
|
||||
- Fn::GetAtt:
|
||||
- CognitoUserPool
|
||||
- Arn
|
||||
|
||||
Outputs:
|
||||
UserPoolId:
|
||||
Description: 'Cognito UserPoolId'
|
||||
Value:
|
||||
Ref: CognitoUserPool
|
||||
|
||||
UserPoolClientId:
|
||||
Description: 'Cognito UserPoolClientId'
|
||||
Value:
|
||||
Ref: CognitoUserPoolClient
|
||||
|
||||
IdentityPoolId:
|
||||
Description: 'Cognito IdentityPoolId'
|
||||
Value:
|
||||
Ref: CognitoIdentityPool
|
||||
|
||||
CognitoAuthRole:
|
||||
Description: 'Cognito CognitoAuthRole'
|
||||
Value:
|
||||
Ref: CognitoAuthRole
|
151
packages/api/src/baseblocks/cognito/cognito.service.ts
Normal file
151
packages/api/src/baseblocks/cognito/cognito.service.ts
Normal file
|
@ -0,0 +1,151 @@
|
|||
import * as AWS_CognitoIdentityServiceProvider from '@aws-sdk/client-cognito-identity-provider';
|
||||
|
||||
const { CognitoIdentityProvider: CognitoIdentityServiceProvider } =
|
||||
AWS_CognitoIdentityServiceProvider;
|
||||
|
||||
const cognito = new CognitoIdentityServiceProvider({
|
||||
region: process.env.API_REGION || 'ap-southeast-2',
|
||||
});
|
||||
|
||||
export async function getUserAttributesByEmail(userEmail: string) {
|
||||
try {
|
||||
const formattedEmail = userEmail?.toLowerCase();
|
||||
const existingResponse = await cognito.adminGetUser({
|
||||
UserPoolId: `${process.env.COGNITO_USER_POOL_ID}`,
|
||||
Username: `${formattedEmail}`,
|
||||
});
|
||||
console.log(JSON.stringify(existingResponse, null, 2));
|
||||
const attributes = existingResponse?.UserAttributes?.reduce(
|
||||
(prev, attr) => {
|
||||
if (attr?.Name) {
|
||||
prev[attr.Name] = `${attr.Value}`;
|
||||
}
|
||||
return prev;
|
||||
},
|
||||
{} as { [key: string]: string },
|
||||
);
|
||||
|
||||
return attributes;
|
||||
} catch (error) {
|
||||
console.log('No user found: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createUser(userEmail: string) {
|
||||
try {
|
||||
const formattedEmail = userEmail?.toLowerCase();
|
||||
const userAttributes = [
|
||||
{
|
||||
Name: 'email',
|
||||
Value: formattedEmail,
|
||||
},
|
||||
{
|
||||
Name: 'email_verified',
|
||||
Value: 'true',
|
||||
},
|
||||
];
|
||||
const cognitoUser = await cognito.adminCreateUser({
|
||||
UserPoolId: process.env.COGNITO_USER_POOL_ID,
|
||||
Username: formattedEmail,
|
||||
UserAttributes: userAttributes,
|
||||
DesiredDeliveryMediums: ['EMAIL'],
|
||||
});
|
||||
|
||||
console.log(JSON.stringify(cognitoUser, null, 2));
|
||||
|
||||
const attributes = cognitoUser.User?.Attributes?.reduce((prev, attr) => {
|
||||
if (attr.Name) {
|
||||
prev[attr.Name] = `${attr.Value}`;
|
||||
}
|
||||
return prev;
|
||||
}, {} as { [key: string]: string });
|
||||
|
||||
return attributes;
|
||||
} catch (error) {
|
||||
console.log('Failed to create cognito user', error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getUsers(args: {
|
||||
subFilter?: string;
|
||||
usernameFilter?: string;
|
||||
emailFilter?: string;
|
||||
phoneNumberFilter?: string;
|
||||
nameFilter?: string;
|
||||
givenNameFilter?: string;
|
||||
familyNameFilter?: string;
|
||||
pageSize?: number;
|
||||
paginationToken?: string;
|
||||
isExactMatch?: boolean;
|
||||
}): Promise<
|
||||
AWS_CognitoIdentityServiceProvider.ListUsersCommandOutput | undefined
|
||||
> {
|
||||
const {
|
||||
subFilter,
|
||||
usernameFilter,
|
||||
emailFilter,
|
||||
nameFilter,
|
||||
givenNameFilter,
|
||||
familyNameFilter,
|
||||
phoneNumberFilter,
|
||||
pageSize,
|
||||
paginationToken,
|
||||
isExactMatch,
|
||||
} = args;
|
||||
|
||||
try {
|
||||
const requestArgs = {
|
||||
UserPoolId: process.env.COGNITO_USER_POOL_ID,
|
||||
Limit: pageSize || 50,
|
||||
PaginationToken: paginationToken,
|
||||
} as AWS_CognitoIdentityServiceProvider.ListUsersCommandInput;
|
||||
|
||||
let field = '';
|
||||
let value = '';
|
||||
const comparison = `${isExactMatch ? '' : '^'}=`;
|
||||
|
||||
if (subFilter) {
|
||||
field = 'sub';
|
||||
value = subFilter;
|
||||
}
|
||||
|
||||
if (usernameFilter) {
|
||||
field = 'username';
|
||||
value = usernameFilter;
|
||||
}
|
||||
|
||||
if (emailFilter) {
|
||||
field = 'email';
|
||||
value = emailFilter;
|
||||
}
|
||||
|
||||
if (phoneNumberFilter) {
|
||||
field = 'phone_number';
|
||||
value = phoneNumberFilter;
|
||||
}
|
||||
|
||||
if (nameFilter) {
|
||||
field = 'name';
|
||||
value = nameFilter;
|
||||
}
|
||||
|
||||
if (givenNameFilter) {
|
||||
field = 'given_name';
|
||||
value = givenNameFilter;
|
||||
}
|
||||
|
||||
if (familyNameFilter) {
|
||||
field = 'family_name';
|
||||
value = familyNameFilter;
|
||||
}
|
||||
|
||||
if (field) {
|
||||
requestArgs.Filter = `${field} ${comparison} "${value}"`;
|
||||
}
|
||||
|
||||
const response = await cognito.listUsers(requestArgs);
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.log('No users found: ', error);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue