├── .gitignore ├── README.md ├── amplify ├── .config │ └── project-config.json └── backend │ ├── auth │ └── cognito98e49332 │ │ ├── cognito98e49332-cloudformation-template.yml │ │ └── parameters.json │ └── backend-config.json ├── authscreens.jpg ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── src ├── App.css ├── App.js ├── App.test.js ├── AppwithAuth.js ├── Buttons.js ├── Form.js ├── Header.js ├── Main.js ├── amplifyorange.png ├── amplifywhite.png ├── aws-exports.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | 25 | #amplify 26 | amplify/\#current-cloud-backend 27 | amplify/.config/local-* 28 | amplify/backend/amplify-meta.json 29 | amplify/backend/awscloudformation 30 | build/ 31 | dist/ 32 | node_modules/ 33 | awsconfiguration.json -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS Amplify Auth Example 2 | 3 | ![](authscreens.jpg) 4 | 5 | ### The Complete Guide to Authentication with the Amplify Framework 6 | 7 | This repo goes along with the Dev.to blog post [The Complete Guide to User Authentication with the Amplify Framework](https://dev.to/dabit3/the-complete-guide-to-user-authentication-with-the-amplify-framework-2inh) & the demo at [amplifyauth.dev](https://www.amplifyauth.dev/). 8 | 9 | ### Methods used to authenticate in this app: 10 | 11 | ```js 12 | // launch Hosted UI (Buttons.js) 13 | Auth.federatedSignIn() 14 | 15 | // specify OAuth provider (Buttons.js) 16 | Auth.federatedSignIn({provider: 'Facebook'}) 17 | Auth.federatedSignIn({provider: 'Google'}) 18 | 19 | // Manually sign up & sign in users (Form.js) 20 | Auth.signUp({ 21 | username, password, attributes: { email } 22 | }) 23 | Auth.confirmSignUp(username, confirmationCode) 24 | Auth.signIn(username, password) 25 | ``` 26 | 27 | To learn how to build this app, check out [the post](https://dev.to/dabit3/the-complete-guide-to-user-authentication-with-the-amplify-framework-2inh) or view [the documentation](https://aws-amplify.github.io/docs/js/authentication). -------------------------------------------------------------------------------- /amplify/.config/project-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "amplify-auth-web", 3 | "version": "2.0", 4 | "frontend": "javascript", 5 | "javascript": { 6 | "framework": "react", 7 | "config": { 8 | "SourceDir": "src", 9 | "DistributionDir": "build", 10 | "BuildCommand": "npm run-script build", 11 | "StartCommand": "npm run-script start" 12 | } 13 | }, 14 | "providers": [ 15 | "awscloudformation" 16 | ] 17 | } -------------------------------------------------------------------------------- /amplify/backend/auth/cognito98e49332/cognito98e49332-cloudformation-template.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | 3 | Parameters: 4 | env: 5 | Type: String 6 | authRoleName: 7 | Type: String 8 | unauthRoleName: 9 | Type: String 10 | authRoleArn: 11 | Type: String 12 | unauthRoleArn: 13 | Type: String 14 | 15 | 16 | identityPoolName: 17 | Type: String 18 | 19 | allowUnauthenticatedIdentities: 20 | Type: String 21 | 22 | lambdaLogPolicy: 23 | Type: String 24 | 25 | openIdLambdaRoleName: 26 | Type: String 27 | 28 | openIdRolePolicy: 29 | Type: String 30 | 31 | openIdLambdaIAMPolicy: 32 | Type: String 33 | 34 | openIdLogPolicy: 35 | Type: String 36 | 37 | userPoolName: 38 | Type: String 39 | 40 | autoVerifiedAttributes: 41 | Type: CommaDelimitedList 42 | 43 | mfaConfiguration: 44 | Type: String 45 | 46 | mfaTypes: 47 | Type: CommaDelimitedList 48 | 49 | roleName: 50 | Type: String 51 | 52 | roleExternalId: 53 | Type: String 54 | 55 | policyName: 56 | Type: String 57 | 58 | smsAuthenticationMessage: 59 | Type: String 60 | 61 | smsVerificationMessage: 62 | Type: String 63 | 64 | emailVerificationSubject: 65 | Type: String 66 | 67 | emailVerificationMessage: 68 | Type: String 69 | 70 | defaultPasswordPolicy: 71 | Type: String 72 | 73 | passwordPolicyMinLength: 74 | Type: Number 75 | 76 | passwordPolicyCharacters: 77 | Type: CommaDelimitedList 78 | 79 | requiredAttributes: 80 | Type: CommaDelimitedList 81 | 82 | userpoolClientName: 83 | Type: String 84 | 85 | userpoolClientGenerateSecret: 86 | Type: String 87 | 88 | userpoolClientRefreshTokenValidity: 89 | Type: Number 90 | 91 | userpoolClientWriteAttributes: 92 | Type: CommaDelimitedList 93 | 94 | userpoolClientReadAttributes: 95 | Type: CommaDelimitedList 96 | 97 | mfaLambdaRole: 98 | Type: String 99 | 100 | mfaLambdaLogPolicy: 101 | Type: String 102 | 103 | mfaPassRolePolicy: 104 | Type: String 105 | 106 | mfaLambdaIAMPolicy: 107 | Type: String 108 | 109 | userpoolClientLambdaRole: 110 | Type: String 111 | 112 | userpoolClientLogPolicy: 113 | Type: String 114 | 115 | userpoolClientLambdaPolicy: 116 | Type: String 117 | 118 | userpoolClientSetAttributes: 119 | Type: String 120 | 121 | resourceName: 122 | Type: String 123 | 124 | authSelections: 125 | Type: String 126 | 127 | useDefault: 128 | Type: String 129 | 130 | hostedUI: 131 | Type: String 132 | 133 | hostedUIDomainName: 134 | Type: String 135 | 136 | authProvidersUserPool: 137 | Type: CommaDelimitedList 138 | 139 | hostedUIProviderMeta: 140 | Type: String 141 | 142 | hostedUIProviderCreds: 143 | Type: String 144 | 145 | oAuthMetadata: 146 | Type: String 147 | 148 | Conditions: 149 | ShouldNotCreateEnvResources: !Equals [ !Ref env, NONE ] 150 | 151 | Resources: 152 | 153 | # BEGIN SNS ROLE RESOURCE 154 | SNSRole: 155 | # Created to allow the UserPool SMS Config to publish via the Simple Notification Service during MFA Process 156 | Type: AWS::IAM::Role 157 | Properties: 158 | RoleName: !If [ShouldNotCreateEnvResources, !Ref roleName, !Join ['',[!Ref roleName, '-', !Ref env]]] 159 | AssumeRolePolicyDocument: 160 | Version: "2012-10-17" 161 | Statement: 162 | - Sid: "" 163 | Effect: "Allow" 164 | Principal: 165 | Service: "cognito-idp.amazonaws.com" 166 | Action: 167 | - "sts:AssumeRole" 168 | Condition: 169 | StringEquals: 170 | sts:ExternalId: !Ref roleExternalId 171 | Policies: 172 | - 173 | PolicyName: !Ref policyName 174 | PolicyDocument: 175 | Version: "2012-10-17" 176 | Statement: 177 | - 178 | Effect: "Allow" 179 | Action: 180 | - "sns:Publish" 181 | Resource: "*" 182 | # BEGIN USER POOL RESOURCES 183 | UserPool: 184 | # Created upon user selection 185 | # Depends on SNS Role for Arn if MFA is enabled 186 | Type: AWS::Cognito::UserPool 187 | UpdateReplacePolicy: Retain 188 | Properties: 189 | UserPoolName: !If [ShouldNotCreateEnvResources, !Ref userPoolName, !Join ['',[!Ref userPoolName, '-', !Ref env]]] 190 | 191 | Schema: 192 | 193 | - 194 | Name: email 195 | Required: true 196 | Mutable: true 197 | 198 | 199 | 200 | AutoVerifiedAttributes: !Ref autoVerifiedAttributes 201 | 202 | 203 | EmailVerificationMessage: !Ref emailVerificationMessage 204 | EmailVerificationSubject: !Ref emailVerificationSubject 205 | 206 | Policies: 207 | PasswordPolicy: 208 | MinimumLength: !Ref passwordPolicyMinLength 209 | RequireLowercase: true 210 | RequireNumbers: true 211 | RequireSymbols: true 212 | RequireUppercase: true 213 | 214 | MfaConfiguration: !Ref mfaConfiguration 215 | SmsVerificationMessage: !Ref smsVerificationMessage 216 | SmsConfiguration: 217 | SnsCallerArn: !GetAtt SNSRole.Arn 218 | ExternalId: !Ref roleExternalId 219 | 220 | UserPoolClientWeb: 221 | # Created provide application access to user pool 222 | # Depends on UserPool for ID reference 223 | Type: "AWS::Cognito::UserPoolClient" 224 | Properties: 225 | ClientName: cognito98e49332_app_clientWeb 226 | 227 | RefreshTokenValidity: !Ref userpoolClientRefreshTokenValidity 228 | UserPoolId: !Ref UserPool 229 | DependsOn: UserPool 230 | UserPoolClient: 231 | # Created provide application access to user pool 232 | # Depends on UserPool for ID reference 233 | Type: "AWS::Cognito::UserPoolClient" 234 | Properties: 235 | ClientName: !Ref userpoolClientName 236 | 237 | GenerateSecret: !Ref userpoolClientGenerateSecret 238 | RefreshTokenValidity: !Ref userpoolClientRefreshTokenValidity 239 | UserPoolId: !Ref UserPool 240 | DependsOn: UserPool 241 | # BEGIN USER POOL LAMBDA RESOURCES 242 | UserPoolClientRole: 243 | # Created to execute Lambda which gets userpool app client config values 244 | Type: 'AWS::IAM::Role' 245 | Properties: 246 | RoleName: !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 247 | AssumeRolePolicyDocument: 248 | Version: '2012-10-17' 249 | Statement: 250 | - Effect: Allow 251 | Principal: 252 | Service: 253 | - lambda.amazonaws.com 254 | Action: 255 | - 'sts:AssumeRole' 256 | DependsOn: UserPoolClient 257 | UserPoolClientLambda: 258 | # Lambda which gets userpool app client config values 259 | # Depends on UserPool for id 260 | # Depends on UserPoolClientRole for role ARN 261 | Type: 'AWS::Lambda::Function' 262 | Properties: 263 | Code: 264 | ZipFile: !Join 265 | - |+ 266 | - - 'const response = require(''cfn-response'');' 267 | - 'const aws = require(''aws-sdk'');' 268 | - 'const identity = new aws.CognitoIdentityServiceProvider();' 269 | - 'exports.handler = (event, context, callback) => {' 270 | - ' if (event.RequestType == ''Delete'') { ' 271 | - ' response.send(event, context, response.SUCCESS, {})' 272 | - ' }' 273 | - ' if (event.RequestType == ''Update'' || event.RequestType == ''Create'') {' 274 | - ' const params = {' 275 | - ' ClientId: event.ResourceProperties.clientId,' 276 | - ' UserPoolId: event.ResourceProperties.userpoolId' 277 | - ' };' 278 | - ' identity.describeUserPoolClient(params).promise()' 279 | - ' .then((res) => {' 280 | - ' response.send(event, context, response.SUCCESS, {''appSecret'': res.UserPoolClient.ClientSecret});' 281 | - ' })' 282 | - ' .catch((err) => {' 283 | - ' response.send(event, context, response.FAILED, {err});' 284 | - ' });' 285 | - ' }' 286 | - '};' 287 | Handler: index.handler 288 | Runtime: nodejs8.10 289 | Timeout: '300' 290 | Role: !GetAtt 291 | - UserPoolClientRole 292 | - Arn 293 | DependsOn: UserPoolClientRole 294 | UserPoolClientLambdaPolicy: 295 | # Sets userpool policy for the role that executes the Userpool Client Lambda 296 | # Depends on UserPool for Arn 297 | # Marked as depending on UserPoolClientRole for easier to understand CFN sequencing 298 | Type: 'AWS::IAM::Policy' 299 | Properties: 300 | PolicyName: !Ref userpoolClientLambdaPolicy 301 | Roles: 302 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 303 | PolicyDocument: 304 | Version: '2012-10-17' 305 | Statement: 306 | - Effect: Allow 307 | Action: 308 | - 'cognito-idp:DescribeUserPoolClient' 309 | Resource: !GetAtt UserPool.Arn 310 | DependsOn: UserPoolClientLambda 311 | UserPoolClientLogPolicy: 312 | # Sets log policy for the role that executes the Userpool Client Lambda 313 | # Depends on UserPool for Arn 314 | # Marked as depending on UserPoolClientLambdaPolicy for easier to understand CFN sequencing 315 | Type: 'AWS::IAM::Policy' 316 | Properties: 317 | PolicyName: !Ref userpoolClientLogPolicy 318 | Roles: 319 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 320 | PolicyDocument: 321 | Version: 2012-10-17 322 | Statement: 323 | - Effect: Allow 324 | Action: 325 | - 'logs:CreateLogGroup' 326 | - 'logs:CreateLogStream' 327 | - 'logs:PutLogEvents' 328 | Resource: !Sub 329 | - arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:* 330 | - { region: !Ref "AWS::Region", account: !Ref "AWS::AccountId", lambda: !Ref UserPoolClientLambda} 331 | DependsOn: UserPoolClientLambdaPolicy 332 | UserPoolClientInputs: 333 | # Values passed to Userpool client Lambda 334 | # Depends on UserPool for Id 335 | # Depends on UserPoolClient for Id 336 | # Marked as depending on UserPoolClientLambdaPolicy for easier to understand CFN sequencing 337 | Type: 'Custom::LambdaCallout' 338 | Properties: 339 | ServiceToken: !GetAtt UserPoolClientLambda.Arn 340 | clientId: !Ref UserPoolClient 341 | userpoolId: !Ref UserPool 342 | DependsOn: UserPoolClientLogPolicy 343 | 344 | HostedUICustomResource: 345 | Type: 'AWS::Lambda::Function' 346 | Properties: 347 | Code: 348 | ZipFile: !Join 349 | - |+ 350 | - - 'const response = require(''cfn-response'');' 351 | - 'const aws = require(''aws-sdk'');' 352 | - 'const identity = new aws.CognitoIdentityServiceProvider();' 353 | - 'exports.handler = (event, context, callback) => {' 354 | - ' const userPoolId = event.ResourceProperties.userPoolId;' 355 | - ' const inputDomainName = event.ResourceProperties.hostedUIDomainName;' 356 | - ' let deleteUserPoolDomain = (domainName) => {' 357 | - ' let params = { Domain: domainName, UserPoolId: userPoolId };' 358 | - ' return identity.deleteUserPoolDomain(params).promise();' 359 | - ' };' 360 | - ' if (event.RequestType == ''Delete'') {' 361 | - ' deleteUserPoolDomain(inputDomainName)' 362 | - ' .then(() => {response.send(event, context, response.SUCCESS, {})})' 363 | - ' .catch((err) => { console.log(err); response.send(event, context, response.FAILED, {err}) });' 364 | - ' }' 365 | - ' if (event.RequestType == ''Update'' || event.RequestType == ''Create'') {' 366 | - ' let checkDomainAvailability = (domainName) => {' 367 | - ' let params = { Domain: domainName };' 368 | - ' return identity.describeUserPoolDomain(params).promise().then((res) => {' 369 | - ' if (res.DomainDescription && res.DomainDescription.UserPool) {' 370 | - ' return false;' 371 | - ' }' 372 | - ' return true;' 373 | - ' }).catch((err) => { return false; });' 374 | - ' };' 375 | - ' let createUserPoolDomain = (domainName) => {' 376 | - ' let params = { Domain: domainName, UserPoolId: userPoolId };' 377 | - ' return identity.createUserPoolDomain(params).promise();' 378 | - ' };' 379 | - ' identity.describeUserPool({UserPoolId: userPoolId }).promise().then((result) => {' 380 | - ' if (inputDomainName) {' 381 | - ' if (result.UserPool.Domain === inputDomainName) {' 382 | - ' return;' 383 | - ' } else {' 384 | - ' if (!result.UserPool.Domain) {' 385 | - ' return checkDomainAvailability(inputDomainName).then((isDomainAvailable) => {' 386 | - ' if (isDomainAvailable) {' 387 | - ' return createUserPoolDomain(inputDomainName);' 388 | - ' } else {' 389 | - ' throw new Error(''Domain not available'');' 390 | - ' }' 391 | - ' });' 392 | - ' } else {' 393 | - ' return checkDomainAvailability(inputDomainName).then((isDomainAvailable) => {' 394 | - ' if (isDomainAvailable) {' 395 | - ' return deleteUserPoolDomain(result.UserPool.Domain).then(() => createUserPoolDomain(inputDomainName));' 396 | - ' } else {' 397 | - ' throw new Error(''Domain not available'');' 398 | - ' }' 399 | - ' });' 400 | - ' }' 401 | - ' }' 402 | - ' } else {' 403 | - ' if (result.UserPool.Domain) {' 404 | - ' return deleteUserPoolDomain(result.UserPool.Domain);' 405 | - ' }' 406 | - ' }' 407 | - ' }).then(() => {response.send(event, context, response.SUCCESS, {})}).catch((err) => {' 408 | - ' console.log(err); response.send(event, context, response.FAILED, {err});' 409 | - ' });' 410 | - '}}' 411 | 412 | 413 | Handler: index.handler 414 | Runtime: nodejs8.10 415 | Timeout: '300' 416 | Role: !GetAtt 417 | - UserPoolClientRole 418 | - Arn 419 | DependsOn: UserPoolClientRole 420 | 421 | HostedUICustomResourcePolicy: 422 | Type: 'AWS::IAM::Policy' 423 | Properties: 424 | PolicyName: !Join ['-',[!Ref UserPool, 'hostedUI']] 425 | Roles: 426 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 427 | PolicyDocument: 428 | Version: '2012-10-17' 429 | Statement: 430 | - Effect: Allow 431 | Action: 432 | - 'cognito-idp:CreateUserPoolDomain' 433 | - 'cognito-idp:DescribeUserPool' 434 | - 'cognito-idp:DeleteUserPoolDomain' 435 | Resource: !GetAtt UserPool.Arn 436 | - Effect: Allow 437 | Action: 438 | - 'cognito-idp:DescribeUserPoolDomain' 439 | Resource: '*' 440 | DependsOn: HostedUICustomResource 441 | HostedUICustomResourceLogPolicy: 442 | Type: 'AWS::IAM::Policy' 443 | Properties: 444 | PolicyName: !Join ['-',[!Ref UserPool, 'hostedUILogPolicy']] 445 | Roles: 446 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 447 | PolicyDocument: 448 | Version: 2012-10-17 449 | Statement: 450 | - Effect: Allow 451 | Action: 452 | - 'logs:CreateLogGroup' 453 | - 'logs:CreateLogStream' 454 | - 'logs:PutLogEvents' 455 | Resource: !Sub 456 | - arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:* 457 | - { region: !Ref "AWS::Region", account: !Ref "AWS::AccountId", lambda: !Ref HostedUICustomResource} 458 | DependsOn: HostedUICustomResourcePolicy 459 | HostedUICustomResourceInputs: 460 | Type: 'Custom::LambdaCallout' 461 | Properties: 462 | ServiceToken: !GetAtt HostedUICustomResource.Arn 463 | userPoolId: !Ref UserPool 464 | hostedUIDomainName: !If [ShouldNotCreateEnvResources, !Ref hostedUIDomainName, !Join ['-',[!Ref hostedUIDomainName, !Ref env]]] 465 | DependsOn: HostedUICustomResourceLogPolicy 466 | 467 | 468 | 469 | HostedUIProvidersCustomResource: 470 | Type: 'AWS::Lambda::Function' 471 | Properties: 472 | Code: 473 | ZipFile: !Join 474 | - |+ 475 | - - 'const response = require(''cfn-response'');' 476 | - 'const aws = require(''aws-sdk'');' 477 | - 'const identity = new aws.CognitoIdentityServiceProvider();' 478 | - 'exports.handler = (event, context, callback) => {' 479 | - 'try{' 480 | - ' const userPoolId = event.ResourceProperties.userPoolId;' 481 | - ' let hostedUIProviderMeta = JSON.parse(event.ResourceProperties.hostedUIProviderMeta);' 482 | - ' let hostedUIProviderCreds = JSON.parse(event.ResourceProperties.hostedUIProviderCreds);' 483 | - ' if (event.RequestType == ''Delete'') {' 484 | - ' response.send(event, context, response.SUCCESS, {});' 485 | - ' }' 486 | - ' if (event.RequestType == ''Update'' || event.RequestType == ''Create'') {' 487 | - ' let getRequestParams = (providerName) => {' 488 | - ' let providerMetaIndex = hostedUIProviderMeta.findIndex((provider) => provider.ProviderName === providerName);' 489 | - ' let providerMeta = hostedUIProviderMeta[providerMetaIndex];' 490 | - ' let providerCredsIndex = hostedUIProviderCreds.findIndex((provider) => provider.ProviderName === providerName);' 491 | - ' let providerCreds = hostedUIProviderCreds[providerCredsIndex];' 492 | - ' let requestParams = {' 493 | - ' ProviderDetails: {' 494 | - ' ''client_id'': providerCreds.client_id,' 495 | - ' ''client_secret'': providerCreds.client_secret,' 496 | - ' ''authorize_scopes'': providerMeta.authorize_scopes' 497 | - ' },' 498 | - ' ProviderName: providerMeta.ProviderName,' 499 | - ' UserPoolId: userPoolId,' 500 | - ' AttributeMapping: providerMeta.AttributeMapping' 501 | - ' };' 502 | - ' return requestParams;' 503 | - ' };' 504 | - ' let createIdentityProvider = (providerName) => {' 505 | - ' let requestParams = getRequestParams(providerName);' 506 | - ' requestParams.ProviderType = requestParams.ProviderName;' 507 | - ' return identity.createIdentityProvider(requestParams).promise();' 508 | - ' };' 509 | - ' let updateIdentityProvider = (providerName) => {' 510 | - ' let requestParams = getRequestParams(providerName);' 511 | - ' return identity.updateIdentityProvider(requestParams).promise();' 512 | - ' };' 513 | - ' let deleteIdentityProvider = (providerName) => {' 514 | - ' let params = {ProviderName: providerName, UserPoolId: userPoolId};' 515 | - ' return identity.deleteIdentityProvider(params).promise();' 516 | - ' };' 517 | - ' let providerPromises = [];' 518 | - ' identity.listIdentityProviders({UserPoolId: userPoolId, MaxResults: 60}).promise()' 519 | - ' .then((result) => {' 520 | - ' let providerList = result.Providers.map(provider => provider.ProviderName);' 521 | - ' let providerListInParameters = hostedUIProviderMeta.map(provider => provider.ProviderName);' 522 | - ' hostedUIProviderMeta.forEach((providerMetadata) => {' 523 | - ' if(providerList.indexOf(providerMetadata.ProviderName) > -1) {' 524 | - ' providerPromises.push(updateIdentityProvider(providerMetadata.ProviderName));' 525 | - ' } else {' 526 | - ' providerPromises.push(createIdentityProvider(providerMetadata.ProviderName));' 527 | - ' }' 528 | - ' });' 529 | - ' providerList.forEach((provider) => {' 530 | - ' if(providerListInParameters.indexOf(provider) < 0) {' 531 | - ' providerPromises.push(deleteIdentityProvider(provider));' 532 | - ' }' 533 | - ' });' 534 | - ' return Promise.all(providerPromises);' 535 | - ' }).then(() => {response.send(event, context, response.SUCCESS, {})}).catch((err) => {' 536 | - ' console.log(err.stack); response.send(event, context, response.FAILED, {err})' 537 | - ' });' 538 | - ' } ' 539 | - ' } catch(err) { console.log(err.stack); response.send(event, context, response.FAILED, {err});};' 540 | - '} ' 541 | 542 | Handler: index.handler 543 | Runtime: nodejs8.10 544 | Timeout: '300' 545 | Role: !GetAtt 546 | - UserPoolClientRole 547 | - Arn 548 | DependsOn: UserPoolClientRole 549 | 550 | HostedUIProvidersCustomResourcePolicy: 551 | Type: 'AWS::IAM::Policy' 552 | Properties: 553 | PolicyName: !Join ['-',[!Ref UserPool, 'hostedUIProvider']] 554 | Roles: 555 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 556 | PolicyDocument: 557 | Version: '2012-10-17' 558 | Statement: 559 | - Effect: Allow 560 | Action: 561 | - 'cognito-idp:CreateIdentityProvider' 562 | - 'cognito-idp:UpdateIdentityProvider' 563 | - 'cognito-idp:ListIdentityProviders' 564 | - 'cognito-idp:DeleteIdentityProvider' 565 | Resource: !GetAtt UserPool.Arn 566 | DependsOn: HostedUIProvidersCustomResource 567 | 568 | HostedUIProvidersCustomResourceLogPolicy: 569 | Type: 'AWS::IAM::Policy' 570 | Properties: 571 | PolicyName: !Join ['-',[!Ref UserPool, 'hostedUIProviderLogPolicy']] 572 | Roles: 573 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 574 | PolicyDocument: 575 | Version: 2012-10-17 576 | Statement: 577 | - Effect: Allow 578 | Action: 579 | - 'logs:CreateLogGroup' 580 | - 'logs:CreateLogStream' 581 | - 'logs:PutLogEvents' 582 | Resource: !Sub 583 | - arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:* 584 | - { region: !Ref "AWS::Region", account: !Ref "AWS::AccountId", lambda: !Ref HostedUIProvidersCustomResource} 585 | DependsOn: HostedUIProvidersCustomResourcePolicy 586 | 587 | HostedUIProvidersCustomResourceInputs: 588 | Type: 'Custom::LambdaCallout' 589 | Properties: 590 | ServiceToken: !GetAtt HostedUIProvidersCustomResource.Arn 591 | userPoolId: !Ref UserPool 592 | hostedUIProviderMeta: !Ref hostedUIProviderMeta 593 | hostedUIProviderCreds: !Ref hostedUIProviderCreds 594 | DependsOn: HostedUIProvidersCustomResourceLogPolicy 595 | 596 | 597 | OAuthCustomResource: 598 | Type: 'AWS::Lambda::Function' 599 | Properties: 600 | Code: 601 | ZipFile: !Join 602 | - |+ 603 | - - 'const response = require(''cfn-response'');' 604 | - 'const aws = require(''aws-sdk'');' 605 | - 'const identity = new aws.CognitoIdentityServiceProvider();' 606 | - 'exports.handler = (event, context, callback) => {' 607 | - 'try{' 608 | - ' const userPoolId = event.ResourceProperties.userPoolId;' 609 | - ' let webClientId = event.ResourceProperties.webClientId;' 610 | - ' let nativeClientId = event.ResourceProperties.nativeClientId;' 611 | - ' let hostedUIProviderMeta = JSON.parse(event.ResourceProperties.hostedUIProviderMeta);' 612 | - ' let oAuthMetadata = JSON.parse(event.ResourceProperties.oAuthMetadata);' 613 | - ' let providerList = hostedUIProviderMeta.map(provider => provider.ProviderName);' 614 | - ' providerList.push(''COGNITO'');' 615 | - ' if (event.RequestType == ''Delete'') {' 616 | - ' response.send(event, context, response.SUCCESS, {});' 617 | - ' }' 618 | - ' if (event.RequestType == ''Update'' || event.RequestType == ''Create'') {' 619 | - ' let params = {' 620 | - ' UserPoolId: userPoolId,' 621 | - ' AllowedOAuthFlows: oAuthMetadata.AllowedOAuthFlows,' 622 | - ' AllowedOAuthFlowsUserPoolClient: true,' 623 | - ' AllowedOAuthScopes: oAuthMetadata.AllowedOAuthScopes,' 624 | - ' CallbackURLs: oAuthMetadata.CallbackURLs,' 625 | - ' LogoutURLs: oAuthMetadata.LogoutURLs,' 626 | - ' SupportedIdentityProviders: providerList' 627 | - ' };' 628 | - ' let updateUserPoolClientPromises = [];' 629 | - ' params.ClientId = webClientId;' 630 | - ' updateUserPoolClientPromises.push(identity.updateUserPoolClient(params).promise());' 631 | - ' params.ClientId = nativeClientId;' 632 | - ' updateUserPoolClientPromises.push(identity.updateUserPoolClient(params).promise());' 633 | - ' Promise.all(updateUserPoolClientPromises)' 634 | - ' .then(() => {response.send(event, context, response.SUCCESS, {})}).catch((err) => {' 635 | - ' console.log(err.stack); response.send(event, context, response.FAILED, {err});' 636 | - ' });' 637 | - ' }' 638 | - '} catch(err) { console.log(err.stack); response.send(event, context, response.FAILED, {err});};' 639 | - '}' 640 | 641 | Handler: index.handler 642 | Runtime: nodejs8.10 643 | Timeout: '300' 644 | Role: !GetAtt 645 | - UserPoolClientRole 646 | - Arn 647 | DependsOn: HostedUIProvidersCustomResourceInputs 648 | 649 | OAuthCustomResourcePolicy: 650 | Type: 'AWS::IAM::Policy' 651 | Properties: 652 | PolicyName: !Join ['-',[!Ref UserPool, 'OAuth']] 653 | Roles: 654 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 655 | PolicyDocument: 656 | Version: '2012-10-17' 657 | Statement: 658 | - Effect: Allow 659 | Action: 660 | - 'cognito-idp:UpdateUserPoolClient' 661 | Resource: !GetAtt UserPool.Arn 662 | DependsOn: OAuthCustomResource 663 | 664 | OAuthCustomResourceLogPolicy: 665 | Type: 'AWS::IAM::Policy' 666 | Properties: 667 | PolicyName: !Join ['-',[!Ref UserPool, 'OAuthLogPolicy']] 668 | Roles: 669 | - !If [ShouldNotCreateEnvResources, !Ref userpoolClientLambdaRole, !Join ['',[!Ref userpoolClientLambdaRole, '-', !Ref env]]] 670 | PolicyDocument: 671 | Version: 2012-10-17 672 | Statement: 673 | - Effect: Allow 674 | Action: 675 | - 'logs:CreateLogGroup' 676 | - 'logs:CreateLogStream' 677 | - 'logs:PutLogEvents' 678 | Resource: !Sub 679 | - arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:* 680 | - { region: !Ref "AWS::Region", account: !Ref "AWS::AccountId", lambda: !Ref OAuthCustomResource} 681 | DependsOn: OAuthCustomResourcePolicy 682 | 683 | OAuthCustomResourceInputs: 684 | Type: 'Custom::LambdaCallout' 685 | Properties: 686 | ServiceToken: !GetAtt OAuthCustomResource.Arn 687 | userPoolId: !Ref UserPool 688 | hostedUIProviderMeta: !Ref hostedUIProviderMeta 689 | oAuthMetadata: !Ref oAuthMetadata 690 | webClientId: !Ref 'UserPoolClientWeb' 691 | nativeClientId: !Ref 'UserPoolClient' 692 | DependsOn: OAuthCustomResourceLogPolicy 693 | 694 | 695 | 696 | 697 | # BEGIN IDENTITY POOL RESOURCES 698 | 699 | 700 | IdentityPool: 701 | # Always created 702 | Type: AWS::Cognito::IdentityPool 703 | Properties: 704 | IdentityPoolName: !If [ShouldNotCreateEnvResources, 'cognito98e49332_identitypool_98e49332', !Join ['',['cognito98e49332_identitypool_98e49332', '__', !Ref env]]] 705 | 706 | CognitoIdentityProviders: 707 | - ClientId: !Ref UserPoolClient 708 | ProviderName: !Sub 709 | - cognito-idp.${region}.amazonaws.com/${client} 710 | - { region: !Ref "AWS::Region", client: !Ref UserPool} 711 | - ClientId: !Ref UserPoolClientWeb 712 | ProviderName: !Sub 713 | - cognito-idp.${region}.amazonaws.com/${client} 714 | - { region: !Ref "AWS::Region", client: !Ref UserPool} 715 | 716 | AllowUnauthenticatedIdentities: !Ref allowUnauthenticatedIdentities 717 | 718 | 719 | DependsOn: UserPoolClientInputs 720 | 721 | 722 | IdentityPoolRoleMap: 723 | # Created to map Auth and Unauth roles to the identity pool 724 | # Depends on Identity Pool for ID ref 725 | Type: AWS::Cognito::IdentityPoolRoleAttachment 726 | Properties: 727 | IdentityPoolId: !Ref IdentityPool 728 | Roles: 729 | unauthenticated: !Ref unauthRoleArn 730 | authenticated: !Ref authRoleArn 731 | DependsOn: IdentityPool 732 | 733 | 734 | Outputs : 735 | 736 | IdentityPoolId: 737 | Value: !Ref 'IdentityPool' 738 | Description: Id for the identity pool 739 | IdentityPoolName: 740 | Value: !GetAtt IdentityPool.Name 741 | 742 | 743 | HostedUIDomain: 744 | Value: !If [ShouldNotCreateEnvResources, !Ref hostedUIDomainName, !Join ['-',[!Ref hostedUIDomainName, !Ref env]]] 745 | 746 | 747 | OAuthMetadata: 748 | Value: !Ref oAuthMetadata 749 | 750 | 751 | UserPoolId: 752 | Value: !Ref 'UserPool' 753 | Description: Id for the user pool 754 | UserPoolName: 755 | Value: !Ref userPoolName 756 | AppClientIDWeb: 757 | Value: !Ref 'UserPoolClientWeb' 758 | Description: The user pool app client id for web 759 | AppClientID: 760 | Value: !Ref 'UserPoolClient' 761 | Description: The user pool app client id 762 | AppClientSecret: 763 | Value: !GetAtt UserPoolClientInputs.appSecret 764 | 765 | 766 | 767 | 768 | 769 | 770 | -------------------------------------------------------------------------------- /amplify/backend/auth/cognito98e49332/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "identityPoolName": "cognito98e49332_identitypool_98e49332", 3 | "allowUnauthenticatedIdentities": false, 4 | "lambdaLogPolicy": "cognito98e49332_lambda_log_policy", 5 | "openIdLambdaRoleName": "cognito98e49332_openid_lambda_role", 6 | "openIdRolePolicy": "cognito98e49332_openid_pass_role_policy", 7 | "openIdLambdaIAMPolicy": "cognito98e49332_openid_lambda_iam_policy", 8 | "openIdLogPolicy": "cognito98e49332_openid_lambda_log_policy", 9 | "userPoolName": "cognito98e49332_userpool_98e49332", 10 | "autoVerifiedAttributes": [ 11 | "email" 12 | ], 13 | "mfaConfiguration": "OFF", 14 | "mfaTypes": [ 15 | "SMS Text Message" 16 | ], 17 | "roleName": "cognito98e49332_sns-role", 18 | "roleExternalId": "cognito98e49332_role_external_id", 19 | "policyName": "cognito98e49332-sns-policy", 20 | "smsAuthenticationMessage": "Your authentication code is {####}", 21 | "smsVerificationMessage": "Your verification code is {####}", 22 | "emailVerificationSubject": "Your verification code", 23 | "emailVerificationMessage": "Your verification code is {####}", 24 | "defaultPasswordPolicy": false, 25 | "passwordPolicyMinLength": 8, 26 | "passwordPolicyCharacters": [ 27 | "Requires Lowercase", 28 | "Requires Uppercase", 29 | "Requires Numbers", 30 | "Requires Symbols" 31 | ], 32 | "requiredAttributes": [ 33 | "email" 34 | ], 35 | "userpoolClientName": "cognito98e49332_app_client", 36 | "userpoolClientGenerateSecret": true, 37 | "userpoolClientRefreshTokenValidity": 30, 38 | "userpoolClientWriteAttributes": [ 39 | "email" 40 | ], 41 | "userpoolClientReadAttributes": [ 42 | "email" 43 | ], 44 | "mfaLambdaRole": "cognito98e49332_totp_lambda_role", 45 | "mfaLambdaLogPolicy": "cognito98e49332_totp_lambda_log_policy", 46 | "mfaPassRolePolicy": "cognito98e49332_totp_pass_role_policy", 47 | "mfaLambdaIAMPolicy": "cognito98e49332_totp_lambda_iam_policy", 48 | "userpoolClientLambdaRole": "cognito98e49332_userpoolclient_lambda_role", 49 | "userpoolClientLogPolicy": "cognito98e49332_userpoolclient_lambda_log_policy", 50 | "userpoolClientLambdaPolicy": "cognito98e49332_userpoolclient_lambda_iam_policy", 51 | "userpoolClientSetAttributes": false, 52 | "resourceName": "cognito98e49332", 53 | "authSelections": "identityPoolAndUserPool", 54 | "authRoleName": { 55 | "Ref": "AuthRoleName" 56 | }, 57 | "unauthRoleName": { 58 | "Ref": "UnauthRoleName" 59 | }, 60 | "authRoleArn": { 61 | "Fn::GetAtt": [ 62 | "AuthRole", 63 | "Arn" 64 | ] 65 | }, 66 | "unauthRoleArn": { 67 | "Fn::GetAtt": [ 68 | "UnauthRole", 69 | "Arn" 70 | ] 71 | }, 72 | "useDefault": "defaultSocial", 73 | "hostedUI": true, 74 | "hostedUIDomainName": "amplifyauthweb", 75 | "authProvidersUserPool": [ 76 | "Facebook", 77 | "Google" 78 | ], 79 | "hostedUIProviderMeta": "[{\"ProviderName\":\"Facebook\",\"authorize_scopes\":\"email\",\"AttributeMapping\":{\"email\":\"email\",\"username\":\"id\"}},{\"ProviderName\":\"Google\",\"authorize_scopes\":\"openid email profile\",\"AttributeMapping\":{\"email\":\"email\",\"username\":\"sub\"}}]", 80 | "oAuthMetadata": "{\"AllowedOAuthFlows\":[\"code\"],\"AllowedOAuthScopes\":[\"phone\",\"email\",\"openid\",\"profile\",\"aws.cognito.signin.user.admin\"],\"CallbackURLs\":[\"http://localhost:3000/\",\"https://www.amplifyauth.dev/\",\"https://master.d234hqv4cc8d2c.amplifyapp.com/\"],\"LogoutURLs\":[\"http://localhost:3000/\",\"https://www.amplifyauth.dev/\",\"https://master.d234hqv4cc8d2c.amplifyapp.com/\"]}" 81 | } -------------------------------------------------------------------------------- /amplify/backend/backend-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "auth": { 3 | "cognito98e49332": { 4 | "service": "Cognito", 5 | "providerPlugin": "awscloudformation" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /authscreens.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/amplify-auth-demo/bf80d84e6f08b293dca744820a3ca53d9b052fe2/authscreens.jpg -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "amplify-auth", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "aws-amplify": "^1.1.26", 7 | "aws-amplify-react": "^2.3.6", 8 | "glamor": "^2.20.40", 9 | "react": "^16.8.6", 10 | "react-dom": "^16.8.6", 11 | "react-icons": "^3.6.1", 12 | "react-scripts": "3.0.0" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": "react-app" 22 | }, 23 | "browserslist": { 24 | "production": [ 25 | ">0.2%", 26 | "not dead", 27 | "not op_mini all" 28 | ], 29 | "development": [ 30 | "last 1 chrome version", 31 | "last 1 firefox version", 32 | "last 1 safari version" 33 | ] 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/amplify-auth-demo/bf80d84e6f08b293dca744820a3ca53d9b052fe2/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 22 | AWS Amplify Authentication Demo 23 | 24 | 25 | 26 |
27 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | pointer-events: none; 9 | } 10 | 11 | .App-header { 12 | background-color: #282c34; 13 | min-height: 100vh; 14 | display: flex; 15 | flex-direction: column; 16 | align-items: center; 17 | justify-content: center; 18 | font-size: calc(10px + 2vmin); 19 | color: white; 20 | } 21 | 22 | .App-link { 23 | color: #61dafb; 24 | } 25 | 26 | @keyframes App-logo-spin { 27 | from { 28 | transform: rotate(0deg); 29 | } 30 | to { 31 | transform: rotate(360deg); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useReducer, useEffect, useState } from 'react'; 2 | import './App.css' 3 | import Header from './Header' 4 | import Buttons from './Buttons' 5 | import Form from './Form' 6 | 7 | import { Hub, Auth } from 'aws-amplify' 8 | import { FaSignOutAlt } from 'react-icons/fa' 9 | 10 | const initialUserState = { user: null, loading: true } 11 | 12 | function App() { 13 | const [userState, dispatch] = useReducer(reducer, initialUserState) 14 | const [formState, updateFormState] = useState('base') 15 | 16 | useEffect(() => { 17 | // set listener for auth events 18 | Hub.listen('auth', (data) => { 19 | const { payload } = data 20 | if (payload.event === 'signIn') { 21 | setImmediate(() => dispatch({ type: 'setUser', user: payload.data })) 22 | setImmediate(() => window.history.pushState({}, null, 'https://www.amplifyauth.dev/')) 23 | updateFormState('base') 24 | } 25 | // this listener is needed for form sign ups since the OAuth will redirect & reload 26 | if (payload.event === 'signOut') { 27 | setTimeout(() => dispatch({ type: 'setUser', user: null }), 350) 28 | } 29 | }) 30 | // we check for the current user unless there is a redirect to ?signedIn=true 31 | if (!window.location.search.includes('?signedin=true')) { 32 | checkUser(dispatch) 33 | } 34 | }, []) 35 | 36 | // This renders the custom form 37 | if (formState === 'email') { 38 | return ( 39 |
40 |
41 |
42 |
43 | ) 44 | } 45 | 46 | return ( 47 |
48 |
49 | { 50 | userState.loading && ( 51 |
52 |

Loading...

53 |
54 | ) 55 | } 56 | { 57 | !userState.user && !userState.loading && ( 58 | 61 | ) 62 | } 63 | { 64 | userState.user && userState.user.signInUserSession && ( 65 |
66 |

67 | Welcome {userState.user.signInUserSession.idToken.payload.email} 68 |

69 | 76 |
77 | ) 78 | } 79 |
81 | ) 82 | } 83 | 84 | function reducer (state, action) { 85 | switch(action.type) { 86 | case 'setUser': 87 | return { ...state, user: action.user, loading: false } 88 | case 'loaded': 89 | return { ...state, loading: false } 90 | default: 91 | return state 92 | } 93 | } 94 | 95 | async function checkUser(dispatch) { 96 | try { 97 | const user = await Auth.currentAuthenticatedUser() 98 | console.log('user: ', user) 99 | dispatch({ type: 'setUser', user }) 100 | } catch (err) { 101 | console.log('err: ', err) 102 | dispatch({ type: 'loaded' }) 103 | } 104 | } 105 | 106 | function signOut() { 107 | Auth.signOut() 108 | .then(data => { 109 | console.log('signed out: ', data) 110 | }) 111 | .catch(err => console.log(err)); 112 | } 113 | 114 | function Footer () { 115 | return ( 116 |
117 |

To view the code for this app, click here. To learn more about AWS Amplify, click here.

122 |
123 | ) 124 | } 125 | 126 | const styles = { 127 | appContainer: { 128 | paddingTop: 85, 129 | }, 130 | loading: { 131 | 132 | }, 133 | button: { 134 | marginTop: 15, 135 | width: '100%', 136 | maxWidth: 250, 137 | marginBottom: 10, 138 | display: 'flex', 139 | justifyContent: 'flex-start', 140 | alignItems: 'center', 141 | padding: '0px 16px', 142 | borderRadius: 2, 143 | boxShadow: '0px 1px 3px rgba(0, 0, 0, .3)', 144 | cursor: 'pointer', 145 | outline: 'none', 146 | border: 'none', 147 | minHeight: 40 148 | }, 149 | text: { 150 | color: 'white', 151 | fontSize: 14, 152 | marginLeft: 10, 153 | fontWeight: 'bold' 154 | }, 155 | signOut: { 156 | backgroundColor: 'black' 157 | }, 158 | footer: { 159 | fontWeight: '600', 160 | padding: '0px 25px', 161 | textAlign: 'right', 162 | color: 'rgba(0, 0, 0, 0.6)' 163 | }, 164 | anchor: { 165 | color: 'rgb(255, 153, 0)', 166 | textDecoration: 'none' 167 | }, 168 | body: { 169 | padding: '0px 30px', 170 | height: '78vh' 171 | } 172 | } 173 | 174 | export default App 175 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/AppwithAuth.js: -------------------------------------------------------------------------------- 1 | import { withAuthenticator } from 'aws-amplify-react' 2 | import App from './App' 3 | 4 | export default withAuthenticator(App) 5 | -------------------------------------------------------------------------------- /src/Buttons.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './App.css' 3 | 4 | import { Auth } from 'aws-amplify' 5 | import { FaFacebook, FaGoogle, FaEnvelope } from 'react-icons/fa' 6 | import AmplifyOrange from './amplifyorange.png' 7 | 8 | function Buttons(props) { 9 | return ( 10 |
11 |
12 | 19 | 26 | 27 | 38 | 45 |
46 |
47 | ); 48 | } 49 | 50 | const styles = { 51 | container: { 52 | height: '80vh', 53 | width: '100vw', 54 | display: 'flex', 55 | justifyContent: 'center', 56 | alignItems: 'center', 57 | flexDirection: 'column' 58 | }, 59 | button: { 60 | width: '100%', 61 | maxWidth: 250, 62 | marginBottom: 10, 63 | display: 'flex', 64 | justifyContent: 'flex-start', 65 | alignItems: 'center', 66 | padding: '0px 16px', 67 | borderRadius: 2, 68 | boxShadow: '0px 1px 3px rgba(0, 0, 0, .3)', 69 | cursor: 'pointer', 70 | outline: 'none', 71 | border: 'none', 72 | minHeight: 40 73 | }, 74 | facebook: { 75 | backgroundColor: "#3b5998" 76 | }, 77 | email: { 78 | backgroundColor: '#db4437' 79 | }, 80 | checkAuth: { 81 | backgroundColor: '#02bd7e' 82 | }, 83 | hostedUI: { 84 | backgroundColor: 'rgba(0, 0, 0, .6)' 85 | }, 86 | signOut: { 87 | backgroundColor: 'black' 88 | }, 89 | withAuthenticator: { 90 | backgroundColor: '#FF9900' 91 | }, 92 | icon: { 93 | height: 16, 94 | marginLeft: -1 95 | }, 96 | text: { 97 | color: 'white', 98 | fontSize: 14, 99 | marginLeft: 10, 100 | fontWeight: 'bold' 101 | }, 102 | blackText: { 103 | color: 'black' 104 | }, 105 | grayText: { 106 | color: 'rgba(0, 0, 0, .75)' 107 | }, 108 | orangeText: { 109 | color: '#FF9900' 110 | } 111 | } 112 | 113 | export default Buttons 114 | -------------------------------------------------------------------------------- /src/Form.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useReducer } from 'react' 2 | 3 | import { Auth } from 'aws-amplify' 4 | 5 | const initialFormState = { 6 | username: '', password: '', email: '', confirmationCode: '' 7 | } 8 | 9 | function reducer(state, action) { 10 | switch(action.type) { 11 | case 'updateFormState': 12 | return { 13 | ...state, [action.e.target.name]: action.e.target.value 14 | } 15 | default: 16 | return state 17 | } 18 | } 19 | 20 | async function signUp({ username, password, email }, updateFormType) { 21 | try { 22 | await Auth.signUp({ 23 | username, password, attributes: { email } 24 | }) 25 | console.log('sign up success!') 26 | updateFormType('confirmSignUp') 27 | } catch (err) { 28 | console.log('error signing up..', err) 29 | } 30 | } 31 | 32 | async function confirmSignUp({ username, confirmationCode }, updateFormType) { 33 | try { 34 | await Auth.confirmSignUp(username, confirmationCode) 35 | console.log('confirm sign up success!') 36 | updateFormType('signIn') 37 | } catch (err) { 38 | console.log('error signing up..', err) 39 | } 40 | } 41 | 42 | async function signIn({ username, password }) { 43 | try { 44 | await Auth.signIn(username, password) 45 | console.log('sign in success!') 46 | } catch (err) { 47 | console.log('error signing up..', err) 48 | } 49 | } 50 | 51 | export default function Form() { 52 | const [formType, updateFormType] = useState('signUp') 53 | const [formState, updateFormState] = useReducer(reducer, initialFormState) 54 | function renderForm() { 55 | switch(formType) { 56 | case 'signUp': 57 | return ( 58 | signUp(formState, updateFormType)} 60 | updateFormState={e => updateFormState({ type: 'updateFormState', e })} 61 | /> 62 | ) 63 | case 'confirmSignUp': 64 | return ( 65 | confirmSignUp(formState, updateFormType)} 67 | updateFormState={e => updateFormState({ type: 'updateFormState', e })} 68 | /> 69 | ) 70 | case 'signIn': 71 | return ( 72 | signIn(formState)} 74 | updateFormState={e => updateFormState({ type: 'updateFormState', e })} 75 | /> 76 | ) 77 | default: 78 | return null 79 | } 80 | } 81 | 82 | 83 | return ( 84 |
85 |
86 | {renderForm(formState)} 87 |
88 | { 89 | formType === 'signUp' && ( 90 |

91 | Already have an account? updateFormType('signIn')} 94 | >Sign In 95 |

96 | ) 97 | } 98 | { 99 | formType === 'signIn' && ( 100 |

101 | Need an account? updateFormType('signUp')} 104 | >Sign Up 105 |

106 | ) 107 | } 108 |
109 | ) 110 | } 111 | 112 | function SignUp(props) { 113 | return ( 114 |
115 | {e.persist();props.updateFormState(e)}} 118 | style={styles.input} 119 | placeholder='username' 120 | /> 121 | {e.persist();props.updateFormState(e)}} 125 | style={styles.input} 126 | placeholder='password' 127 | /> 128 | {e.persist();props.updateFormState(e)}} 131 | style={styles.input} 132 | placeholder='email' 133 | /> 134 | 137 |
138 | ) 139 | } 140 | 141 | function SignIn(props) { 142 | return ( 143 |
144 | {e.persist();props.updateFormState(e)}} 147 | style={styles.input} 148 | placeholder='username' 149 | /> 150 | {e.persist();props.updateFormState(e)}} 154 | style={styles.input} 155 | placeholder='password' 156 | /> 157 | 160 |
161 | ) 162 | } 163 | 164 | function ConfirmSignUp(props) { 165 | return ( 166 |
167 | {e.persist();props.updateFormState(e)}} 171 | style={styles.input} 172 | /> 173 | 176 |
177 | ) 178 | } 179 | 180 | const styles = { 181 | container: { 182 | display: 'flex', 183 | flexDirection: 'column', 184 | marginTop: 150, 185 | justifyContent: 'center', 186 | alignItems: 'center' 187 | }, 188 | input: { 189 | height: 45, 190 | marginTop: 8, 191 | width: 300, 192 | maxWidth: 300, 193 | padding: '0px 8px', 194 | fontSize: 16, 195 | outline: 'none', 196 | border: 'none', 197 | borderBottom: '2px solid rgba(0, 0, 0, .3)' 198 | }, 199 | button: { 200 | backgroundColor: '#006bfc', 201 | color: 'white', 202 | width: 316, 203 | height: 45, 204 | marginTop: 10, 205 | fontWeight: '600', 206 | fontSize: 14, 207 | cursor: 'pointer', 208 | border:'none', 209 | outline: 'none', 210 | borderRadius: 3, 211 | boxShadow: '0px 1px 3px rgba(0, 0, 0, .3)', 212 | }, 213 | footer: { 214 | fontWeight: '600', 215 | padding: '0px 25px', 216 | textAlign: 'center', 217 | color: 'rgba(0, 0, 0, 0.6)' 218 | }, 219 | anchor: { 220 | color: '#006bfc', 221 | cursor: 'pointer' 222 | } 223 | } -------------------------------------------------------------------------------- /src/Header.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import AmplifyLogo from './amplifyorange.png' 3 | 4 | export default function Header(props) { 5 | return ( 6 |
7 |
props.updateFormState('base')}> 8 | Amplify 13 |

Amplify Auth Demo

14 |
15 |
16 | ) 17 | } 18 | 19 | const styles = { 20 | container: { 21 | padding: 20, 22 | position: 'fixed', 23 | top: 0, 24 | left: 0, 25 | right: 0, 26 | maxHeight: 65, 27 | boxShadow: '0px 2px 2px rgba(0, 0, 0, .1)' 28 | }, 29 | header: { 30 | margin: 0, 31 | fontSize: 24, 32 | marginLeft: 9, 33 | fontWeight: '300', 34 | marginTop: -3, 35 | color: 'rgb(255, 153, 0)', 36 | cursor: 'pointer', 37 | }, 38 | headerContent: { 39 | cursor: 'pointer', 40 | display: 'flex' 41 | }, 42 | image: { 43 | height: 22, 44 | cursor: 'pointer', 45 | } 46 | } -------------------------------------------------------------------------------- /src/Main.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/amplify-auth-demo/bf80d84e6f08b293dca744820a3ca53d9b052fe2/src/Main.js -------------------------------------------------------------------------------- /src/amplifyorange.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/amplify-auth-demo/bf80d84e6f08b293dca744820a3ca53d9b052fe2/src/amplifyorange.png -------------------------------------------------------------------------------- /src/amplifywhite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabit3/amplify-auth-demo/bf80d84e6f08b293dca744820a3ca53d9b052fe2/src/amplifywhite.png -------------------------------------------------------------------------------- /src/aws-exports.js: -------------------------------------------------------------------------------- 1 | // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten. 2 | 3 | const awsmobile = { 4 | "aws_project_region": "us-east-2", 5 | "aws_cognito_identity_pool_id": "us-east-2:cec55e7d-2e27-4e4d-800a-8924b3d36eb8", 6 | "aws_cognito_region": "us-east-2", 7 | "aws_user_pools_id": "us-east-2_hIDtJZZok", 8 | "aws_user_pools_web_client_id": "4219m8pdpbuqef2kt905gbuos4", 9 | "oauth": { 10 | "domain": "amplifyauthweb-local.auth.us-east-2.amazoncognito.com", 11 | "scope": [ 12 | "phone", 13 | "email", 14 | "openid", 15 | "profile", 16 | "aws.cognito.signin.user.admin" 17 | ], 18 | "redirectSignIn": "https://www.amplifyauth.dev?signedin=true", 19 | "redirectSignOut": "https://www.amplifyauth.dev/", 20 | "responseType": "code" 21 | }, 22 | "federationTarget": "COGNITO_USER_POOLS" 23 | }; 24 | 25 | 26 | export default awsmobile; 27 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | import Amplify from 'aws-amplify' 8 | import config from './aws-exports' 9 | Amplify.configure(config) 10 | 11 | ReactDOM.render(, document.getElementById('root')); 12 | 13 | // If you want your app to work offline and load faster, you can change 14 | // unregister() to register() below. Note this comes with some pitfalls. 15 | // Learn more about service workers: https://bit.ly/CRA-PWA 16 | serviceWorker.unregister(); 17 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------