Skip to content
This repository has been archived by the owner on May 30, 2023. It is now read-only.

Feat/refactor sam app #170

Merged
merged 10 commits into from
Aug 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions daita-app/auth-service/CognitoClient/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
Parameters:
DomainUserPool:
Type: String
CognitoUserPool:
Type: String
StagePara:
Type: String
AuthHttpAPI:
Type: String
Resources:
GoogleCognitoUserPoolIdentityProvider:
Type: AWS::Cognito::UserPoolIdentityProvider
Properties:
ProviderName: "Google"
AttributeMapping:
email: email
ProviderDetails:
client_id: 639730110991-9t82efunb20f6m4stek56f6ut9t0kjfu.apps.googleusercontent.com
client_secret: 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
authorize_scopes: profile email openid
ProviderType: Google
UserPoolId:
Ref : CognitoUserPool
GithubCognitoUserPoolIdentityProvider:
Type: AWS::Cognito::UserPoolIdentityProvider
Properties:
UserPoolId: !Ref CognitoUserPool
ProviderName: github
ProviderDetails:
client_id: 0cec5cf3d1f070b36b63
client_secret: 5929cb027e02330533a587a8e9f5d2e0fd40e48e
attributes_request_method: POST
oidc_issuer: !Sub "https://${AuthHttpAPI}.execute-api.${AWS::Region}.amazonaws.com/${StagePara}"
authorize_scopes: "openid read:user user:email"
jwks_uri: !Sub "https://${AuthHttpAPI}.execute-api.${AWS::Region}.amazonaws.com/${StagePara}/auth/github-openid-token-wrapper"
token_url: !Sub "https://${AuthHttpAPI}.execute-api.${AWS::Region}.amazonaws.com/${StagePara}/auth/github-openid-token-wrapper"
authorize_url: !Sub "https://${AuthHttpAPI}.execute-api.${AWS::Region}.amazonaws.com/${StagePara}/auth/github-openid-userinfo-wrapper"
attributes_url: https://github.com/login/oauth/authorize
ProviderType: "OIDC"
AttributeMapping:
email: "email"
username: sub
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
DependsOn:
- GoogleCognitoUserPoolIdentityProvider
- GithubCognitoUserPoolIdentityProvider
Properties:
UserPoolId: !Ref CognitoUserPool
ClientName: user-pool-client
GenerateSecret: false
AllowedOAuthFlowsUserPoolClient: true
CallbackURLs:
- http://localhost:3000
- !Sub https://${DomainUserPool}
LogoutURLs:
- !Sub https://${AuthHttpAPI}.execute-api.${AWS::Region}.amazonaws.com/${StagePara}/auth/login_social
AllowedOAuthFlows:
- code
- implicit
AllowedOAuthScopes:
- phone
- email
- openid
- profile
- aws.cognito.signin.user.admin
SupportedIdentityProviders:
- COGNITO
- github
- Google
AccessTokenValidity: 2
RefreshTokenValidity: 24
IdTokenValidity: 2
TokenValidityUnits:
AccessToken: hours
IdToken: hours
RefreshToken: hours
AllowedOAuthFlowsUserPoolClient: true
ExplicitAuthFlows:
- ALLOW_REFRESH_TOKEN_AUTH
- ALLOW_USER_PASSWORD_AUTH
- ALLOW_USER_SRP_AUTH
PreventUserExistenceErrors: ENABLED
Outputs:
UserPoolClientId:
Value: !Ref CognitoUserPoolClient
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
openapi: "3.0.1"
info:
title:
Fn::Sub: "${StagePara}-Daita-HTTP-API"
version: "2021-04-07"
tags:
- name: "httpapi:createdBy"
x-amazon-apigateway-tag-value: "SAM"
paths:
/auth/login-social:
post:
responses:
default:
description: "Auth service transport"
x-amazon-apigateway-integration:
credentials:
Fn::GetAtt: [ApiGatewayCallLambdaRole, Arn]
uri:
Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LoginSocialFunction.Arn}/invocations
httpMethod: "POST"
type: "aws_proxy"
payloadFormatVersion: "2.0"

126 changes: 126 additions & 0 deletions daita-app/auth-service/CognitoUserPool/functions/login_social/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
from email import header
import os
import json
import logging
import time
from datetime import datetime
from http import HTTPStatus
import os
import boto3

from error_messages import *
from response import *
from config import *
from lambda_base_class import LambdaBaseClass

import base64
from urllib.parse import urlencode
ACCESS_TOKEN_EXPIRATION = 24 * 60 * 60
USERPOOLID = os.environ['COGNITO_USER_POOL']
cog_provider_client = boto3.client('cognito-idp')
cog_identity_client = boto3.client('cognito-identity')


@error_response
def lambda_handler(event, context):
param = event['queryStringParameters']
try:
code = param['code']
except Exception as e:
print(e)
if 'error_description' in param:
location = LOCATION
headers = {"Location": location,
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"}
return {
"statusCode": 302,
"headers": headers,
"body": '',
"isBase64Encoded": False
}
raise Exception(e)

if 'state' in param:
path = base64.b64decode(param['state']).decode('utf-8')
else:
path = 'http://localhost:3000/login'
mapping = {
'token': '',
'resfresh_token': '',
'access_key': '',
'session_key': '',
'id_token': '',
'credential_token_expires_in': '',
'token_expires_in': '',
'secret_key': '',
'identity_id': '',
'username': '',
'code': code
}
location = path + '?' + urlencode(mapping, doseq=True)
headers = {"Location": location,
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"}
return {
"statusCode": 302,
"headers": headers,
"body": '',
"isBase64Encoded": False
}


class LoginSocialClass(LambdaBaseClass):
def __init__(self) -> None:
super().__init__()

@LambdaBaseClass.parse_body
def parser(self, body):
self.code = body['code']

def handle(self, event, context):
param = event['queryStringParameters']
try:
self.parser(param)
except Exception as e:
if 'error_description' in param:
location = LOCATION
headers = {"Location": location,
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"}
return {
"statusCode": 302,
"headers": headers,
"body": '',
"isBase64Encoded": False
}
raise Exception(e)

if 'state' in param:
path = base64.b64decode(param['state']).decode('utf-8')
else:
path = 'http://localhost:3000/login'
mapping = {
'token': '',
'resfresh_token': '',
'access_key': '',
'session_key': '',
'id_token': '',
'credential_token_expires_in': '',
'token_expires_in': '',
'secret_key': '',
'identity_id': '',
'username': '',
'code': self.code
}
location = path + '?' + urlencode(mapping, doseq=True)
headers = {"Location": location,
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"}
return {
"statusCode": 302,
"headers": headers,
"body": '',
"isBase64Encoded": False
}


@error_response
def lambda_handler(event, context):
return LoginSocialClass.handle(event=event, context=context)
Loading