|
| 1 | +import { CfnOutput } from "@aws-cdk/core"; |
| 2 | +import * as iam from "@aws-cdk/aws-iam"; |
| 3 | +import * as cognito from "@aws-cdk/aws-cognito"; |
| 4 | +import * as sst from "@serverless-stack/resources"; |
| 5 | +import CognitoAuthRole from "./CognitoAuthRole"; |
| 6 | + |
| 7 | +export default class CognitoStack extends sst.Stack { |
| 8 | + constructor(scope, id, props) { |
| 9 | + super(scope, id, props); |
| 10 | + |
| 11 | + const { bucketArn } = props; |
| 12 | + |
| 13 | + const app = this.node.root; |
| 14 | + |
| 15 | + const userPool = new cognito.UserPool(this, "UserPool", { |
| 16 | + selfSignUpEnabled: true, // Allow users to sign up |
| 17 | + autoVerify: { email: true }, // Verify email addresses by sending a verification code |
| 18 | + signInAliases: { email: true }, // Set email as an alias |
| 19 | + }); |
| 20 | + |
| 21 | + const userPoolClient = new cognito.UserPoolClient(this, "UserPoolClient", { |
| 22 | + userPool, |
| 23 | + generateSecret: false, // Don't need to generate secret for web app running on browsers |
| 24 | + }); |
| 25 | + |
| 26 | + const identityPool = new cognito.CfnIdentityPool(this, "IdentityPool", { |
| 27 | + allowUnauthenticatedIdentities: false, // Don't allow unathenticated users |
| 28 | + cognitoIdentityProviders: [ |
| 29 | + { |
| 30 | + clientId: userPoolClient.userPoolClientId, |
| 31 | + providerName: userPool.userPoolProviderName, |
| 32 | + }, |
| 33 | + ], |
| 34 | + }); |
| 35 | + |
| 36 | + const authenticatedRole = new CognitoAuthRole(this, "CognitoAuthRole", { |
| 37 | + identityPool, |
| 38 | + }); |
| 39 | + |
| 40 | + authenticatedRole.role.addToPolicy( |
| 41 | + // IAM policy granting users permission to a specific folder in the S3 bucket |
| 42 | + new iam.PolicyStatement({ |
| 43 | + actions: ["s3:*"], |
| 44 | + effect: iam.Effect.ALLOW, |
| 45 | + resources: [ |
| 46 | + bucketArn + "/private/${cognito-identity.amazonaws.com:sub}/*", |
| 47 | + ], |
| 48 | + }) |
| 49 | + ); |
| 50 | + |
| 51 | + // Export values |
| 52 | + new CfnOutput(this, "UserPoolId", { |
| 53 | + value: userPool.userPoolId, |
| 54 | + }); |
| 55 | + new CfnOutput(this, "UserPoolClientId", { |
| 56 | + value: userPoolClient.userPoolClientId, |
| 57 | + }); |
| 58 | + new CfnOutput(this, "IdentityPoolId", { |
| 59 | + value: identityPool.ref, |
| 60 | + }); |
| 61 | + new CfnOutput(this, "AuthenticatedRoleName", { |
| 62 | + value: authenticatedRole.role.roleName, |
| 63 | + exportName: app.logicalPrefixedName("CognitoAuthRole"), |
| 64 | + }); |
| 65 | + } |
| 66 | +} |
0 commit comments