Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
4.8 kB
8
Indexable
Never
import base64
from urllib.parse import urlencode
import http.cookies as cookies
import http.client 
from jose import jwt

cognito_user_pool_id = "us-east-1_f1oN3uxu6"
cognito_client_id = "mi6m1p1j3c7q6hdfiapmar0cb"
cognito_client_secret = "1a877rudvu15nf90hm0v0j3rst3q4e9smhjlu9a16o603t291g1q"
    
def exchange_code_for_token(request) :
    credentials = f"{cognito_client_id}:{cognito_client_secret}"
    credentials_bytes = credentials.encode('utf-8')
    credentials_base64 = base64.b64encode(credentials_bytes).decode('utf-8')

    # print(credentials_base64)

    headers = {
        'content-type': 'application/x-www-form-urlencoded',
        'authorization': 'Basic ' + credentials_base64
    }


    code = request['querystring'].split("=")[1]
    data = {
        'grant_type': 'authorization_code',
        'redirect_uri': 'https://d38tpuisuaynq.cloudfront.net/parseauth',
        'code': code
    }

    #print(code)

    url = "stylcoggoogle.auth.us-east-1.amazoncognito.com"
    conn = http.client.HTTPSConnection(url)
    conn.request("POST", "/oauth2/token", urlencode(data), headers)

    response = conn.getresponse()
    response_data = response.read().decode('utf-8')

    response_data = eval(response_data)
    
    print("RESPONSE_DATA THAT GET ID_TOKEN : ", response_data)

    my_cookie = cookies.SimpleCookie()
    my_cookie['token'] = response_data['access_token']
    my_cookie['token']['max-age'] = response_data['expires_in']
    my_cookie['token']['path'] = '/'
    my_cookie['token']['secure'] = True

    set_cookie_value = my_cookie.output(header = '')
    print("MY COOKIE VALUE : ", set_cookie_value)
    
    final_response = {
        'status': '302',
        'statusDescription': 'Found',
        'headers': {
            'location': [{
                'key': 'Location',
                'value': 'https://d38tpuisuaynq.cloudfront.net/index.html'
            }],
        'set-cookie' : [{
            'key': 'Set-Cookie',
            'value' : set_cookie_value
        }],
        'cache-control': [{ 
            'key': 'Cache-Control',
            'value': 'no-cache'
            }]
        }
    }

    print("SET COOKIES SUCCESS, RETURN FINAL_RESPONSE ", final_response)
    return final_response


def get_key(access_token):
    url = "/us-east-1_f1oN3uxu6/.well-known/jwks.json"
    host = "cognito-idp.us-east-1.amazonaws.com"
    
    conn = http.client.HTTPSConnection(host)
    conn.request("GET", url)
    
    response = conn.getresponse().read().decode('utf-8')
    # print(response)
    jwks_data = eval(response)

    header = jwt.get_unverified_header(access_token)
    header_kid = header['kid']

    for item in jwks_data['keys']:
        if (item['kid'] == header_kid) : return item


# ------------------------------- VALIDATION METHOD ------------------------------- #

def verify_jwt_token(access_token) :
    try : 
        key = get_key(access_token)
        response = jwt.decode(
            access_token, key,
            options = {
                "verify_iss": True,
                "iss" : f"https://cognito-idp.us-east-1.amazonaws.com/{cognito_user_pool_id}",
                "verify_signature": True,
                "verify_exp": True
            }
        )
        
        if (response['client_id'] == cognito_client_id) : return True
        return False 
    
    except : 
        return False
    


def lambda_handler(event, context):
    print("EVENT FROM CLOUDFRONT : ", event)
    
    request = event['Records'][0]['cf']['request']

    if (request['uri'].startswith('/parseauth')) :
        return exchange_code_for_token(request)

    cookie = None
    if 'cookie' in request['headers'] : cookie = request['headers']['cookie'][0]['value'].split("=")[1]
    
    print("COOKIE VALUE : ", cookie)

    if verify_jwt_token(cookie) : 
        print("SUCCESSFUL VALIDATION !!!")
        return request    
    
    else :
        print("FAIL VALIDATION, UNAUTHORIZE ACCESS !!!! REDIRECT TO SIGN-IN PAGE.")
        
        response = {
            'status': '302',
            'statusDescription': 'Found',
            'headers': {
                'location': [{
                    'key': 'Location',
                    'value': 'https://stylcoggoogle.auth.us-east-1.amazoncognito.com/login?client_id=mi6m1p1j3c7q6hdfiapmar0cb&response_type=code&scope=aws.cognito.signin.user.admin+email+openid&redirect_uri=https%3A%2F%2Fd38tpuisuaynq.cloudfront.net%2Fparseauth' 
                        
                }]
            }
        }

        print("REDIRECT RESPONSE TO COGNITO SIGN-IN : ", response)
        return response