Exemple #1
0
def social_signup(event, context):
    logger.debug('event: {}'.format(event))

    if os.environ['SIGNUP_ORIGIN_URL'] is not "*":    # "*" means accept any origin
        # Check if the request is originating from a valid URI
        origin = event['headers']['origin']
        valid_origin_uri = urlparse(os.environ['SIGNUP_ORIGIN_URL'])
        request_uri = urlparse(origin)

        if request_uri.netloc not in valid_origin_uri.netloc:
            logger.error("Request origin domain: {REQ_DOM}, "
                         "Valid origin domain: {VALID_DOM}".format(REQ_DOM=request_uri.netloc,
                                                                   VALID_DOM=valid_origin_uri.netloc))
            return {
                'statusCode': 401,
                'body': json.dumps({
                    'error': 'Unauthorized. Request originating from invalid domain'
                })
            }

    try:
        body = get_body(event)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': json.dumps({
                'error': 'Bad parameter(s) in request'
            })
        }

    if 'authorization_code' not in body or not body['authorization_code']:
        return {
            'statusCode': 400,
            'body': json.dumps({
                'error': 'Missing authorization_code in request body'
            })
        }

    authorization_code = body['authorization_code']

    # get access token
    resp = requests.post(
        url=os.environ['AUTH0_DOMAIN'] + '/oauth/token',
        data={
            'grant_type': 'authorization_code',
            'client_id': os.environ['AUTH0_CLIENT_ID'],
            'client_secret': os.environ['AUTH0_CLIENT_SECRET'],
            'code': authorization_code,
            'redirect_uri': 'https://localhost:8080/callback'
        },
        headers={
            'content-type': "application/x-www-form-urlencoded"
        }
    )

    body = resp.json()

    if all(k in body for k in [
        'access_token',
        'id_token',
        'expires_in',
        'token_type'
    ]):
        pass    # to the next section of code
    elif 'error_description' in body:
        return {
            'statusCode': 400,
            'body': json.dumps({
                'error': body['error_description']
            })
        }
    else:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'error': 'Unknown Error happened'
            })
        }

    # extract payload for jwt token
    if 'id_token' in body:
        _id_token = body['id_token']
        payload = jwt_decode(_id_token, AUTH0_CLIENT_PUBLIC_KEY)
    else:
        if 'error_description' in body:
            return {
                'statusCode': 400,
                'body': json.dumps({
                    'error': body['error_description']
                })
            }
        else:
            return {
                'statusCode': 500,
                'body': json.dumps({
                    'error': 'Unknown Error happened'
                })
            }

    if all(k in payload for k in [
        'email',
        'sub'
    ]):
        # extract user id, social user id format: social-type|user_id
        user_id = payload['sub']
        email = payload['email']

        # Make a repo object
        sys.path.append('data_dynamodb')
        sys.path.append('data_common')
        from data_dynamodb.dynamodb_repository import DynamoRepository

        # While developing, dynamodb local is used. So if `DYANMODB_LOCAL_ENDPOINT` is present in env vars
        # dynamodb boto client is patched to use local db
        try:
            repo = DynamoRepository(
                region_name=os.environ['REGION'],
                user_id=user_id,
                email=email,
                dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT']
            )

        except KeyError:
            repo = DynamoRepository(
                region_name=os.environ['REGION'],
                user_id=user_id,
                email=email
            )
        # create new user in `brewoptix-users` table
        user_obj = repo.get_or_create_profile()

        if 'name' in payload:
            user_obj['name'] = payload['name']
        if 'picture' in payload:
            user_obj['picture'] = payload['picture']
        if 'nickname' in payload:
            user_obj['nickname'] = payload['nickname']
        if 'email_verified' in payload:
            user_obj['email_verified'] = payload['email_verified']
        if 'blocked' in payload:
            user_obj['blocked'] = payload['blocked']

        user_obj = repo.update_profile(user_obj)
        return {
            'statusCode': 200,
            'body': json.dumps(body)
        }
    elif 'message' in body:
        return {
            'statusCode': body.get('statusCode', 400),
            'body': json.dumps({
                'error': body['message']
            })
        }
    else:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'error': 'Unknown Error happened'
            })
        }
Exemple #2
0
def signup(event, context):
    event_log = deepcopy(event)
    try:
        event_log["body"].pop("password")
    except KeyError:
        pass
    logger.debug('event: {}'.format(event_log))

    if os.environ[
            'SIGNUP_ORIGIN_URL'] is not "*":  # "*" means accept any origin
        # Check if the request is originating from a valid URI
        origin = event['headers']['origin']
        valid_origin_uri = urlparse(os.environ['SIGNUP_ORIGIN_URL'])
        request_uri = urlparse(origin)

        if request_uri.netloc not in valid_origin_uri.netloc:
            logger.error("Request origin domain: {REQ_DOM}, "
                         "Valid origin domain: {VALID_DOM}".format(
                             REQ_DOM=request_uri.netloc,
                             VALID_DOM=valid_origin_uri.netloc))
            return {
                'statusCode':
                401,
                'body':
                json.dumps({
                    'error':
                    'Unauthorized. Request originating from invalid domain'
                })
            }

    try:
        body = get_body(event)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': json.dumps({'error': 'Bad parameter(s) in request'})
        }

    if 'email' not in body or not body[
            'email'] or 'password' not in body or not body['password']:
        return {
            'statusCode':
            400,
            'body':
            json.dumps({
                'error':
                'Missing required key-value pair(s) in request body'
            })
        }

    email = body['email']
    password = body['password']
    name = body.get('name', '')
    company_name = body.get('company_name', '')
    is_distributor = body.get('is_distributor', False)
    website = body.get('website', '')

    # get Machine-to-machine access token
    resp = requests.post(os.environ['AUTH0_DOMAIN'] + '/oauth/token',
                         json={
                             'grant_type':
                             'client_credentials',
                             'client_id':
                             os.environ['AUTH0_MANAGEMENT_API_CLIENT_ID'],
                             'client_secret':
                             os.environ['AUTH0_MANAGEMENT_API_CLIENT_SECRET'],
                             'audience':
                             os.environ['AUTH0_AUDIENCE'],
                             'scope':
                             'create:users'
                         },
                         headers={'content-type': "application/json"})

    body = resp.json()

    if all(k in body
           for k in ['access_token', 'scope', 'expires_in', 'token_type']):
        pass  # to the next section of code
    elif 'error_description' in body:
        return {
            'statusCode': 400,
            'body': json.dumps({'error': body['error_description']})
        }
    else:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Unknown Error happened'})
        }

    access_token = body['access_token']

    payload = {
        'email': email,
        'password': password,
        'email_verified': True,
        'blocked': False,
        'connection': os.environ['AUTH0_CONNECTION'],
    }

    if name:
        payload['name'] = name

    resp = requests.post(os.environ['AUTH0_DOMAIN'] + "/api/v2/users",
                         json=payload,
                         headers={
                             'Authorization':
                             'Bearer {TOKEN}'.format(TOKEN=access_token),
                             'content-type':
                             "application/json"
                         })

    body = resp.json()
    print(body)

    if all(k in body for k in ['user_id', 'email']):
        user_id = body['user_id'][6:]
        email = body['email']

        # Make a repo object
        sys.path.append('data_dynamodb')
        sys.path.append('data_common')
        from data_dynamodb.dynamodb_repository import DynamoRepository

        # While developing, dynamodb local is used. So if `DYANMODB_LOCAL_ENDPOINT` is present in env vars
        # dynamodb boto client is patched to use local db
        try:
            repo = DynamoRepository(
                region_name=os.environ['REGION'],
                user_id=user_id,
                email=email,
                dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT'])

        except KeyError:
            repo = DynamoRepository(region_name=os.environ['REGION'],
                                    user_id=user_id,
                                    email=email)
        # create new user in `brewoptix-users` table
        user_obj = repo.get_or_create_profile()

        if 'name' in body:
            user_obj['name'] = body['name']
        if 'picture' in body:
            user_obj['picture'] = body['picture']
        if 'nickname' in body:
            user_obj['nickname'] = body['nickname']
        if 'email_verified' in body:
            user_obj['email_verified'] = body['email_verified']
        if 'blocked' in body:
            user_obj['blocked'] = body['blocked']

        user_obj = repo.update_profile(user_obj)

        # check if "company_name" in request body and create supplier
        if company_name:
            if not is_distributor:
                supplier = {"name": company_name, "website": website}

                supplier_obj = repo.save_supplier(supplier)

                # add user to distributors's users list
                supplier_id = supplier_obj["entity_id"]
                user_info = {
                    "email": email,
                    "role": "admin",
                    "name": user_obj.get("name", "")
                }
                try:
                    repo.upsert_user_in_supplier(supplier_id, user_info)
                except Auth0UnknownError as ex:
                    return {
                        'statusCode':
                        400,
                        'body':
                        json.dumps({
                            'error':
                            "User created. Auth0 error: {ERROR}".format(
                                ERROR=str(ex))
                        })
                    }
                except Auth0UnableToAccess:
                    return {
                        'statusCode':
                        400,
                        'body':
                        json.dumps({
                            'error':
                            "User created. But app_metadata update failed, Unable to access Auth0"
                        })
                    }
            else:
                distributor = {"name": company_name, "website": website}

                distributor_obj = repo.save_distributor(distributor)

                # add user to distributors's users list
                distributor_id = distributor_obj["entity_id"]
                user_info = {
                    "email": email,
                    "role": "admin",
                    "name": user_obj.get("name", "")
                }
                try:
                    repo.upsert_user_in_distributor(distributor_id, user_info)
                except Auth0UnknownError as ex:
                    return {
                        'statusCode':
                        400,
                        'body':
                        json.dumps({
                            'error':
                            "User created. Auth0 error: {ERROR}".format(
                                ERROR=str(ex))
                        })
                    }
                except Auth0UnableToAccess:
                    return {
                        'statusCode':
                        400,
                        'body':
                        json.dumps({
                            'error':
                            "User created. But app_metadata update failed, Unable to access Auth0"
                        })
                    }

        email_data = {
            'email': email,
            'name': name,
            'website': website,
            'company_name': company_name
        }
        if is_distributor:
            email_data['brewery_distributor'] = "Distributor"
        else:
            email_data['brewery_distributor'] = "Brewery"

        to_list = NEW_USER_NOTIFICATION_LIST.split(',')
        to_email_list = []
        for item in to_list:
            to_email_list.append(item.strip())

        # Send the SQS message
        sqs = boto3.resource('sqs')
        queue = sqs.get_queue_by_name(QueueName=SQS_EMAIL_TRANSMITTER)
        try:
            message_body = {
                "template": USER_REGISTER_EMAIL_TEMPLATE,
                "to": to_email_list,
                "data": email_data
            }
            print(message_body)
            response = queue.send_message(MessageBody=json.dumps(message_body))
            logger.debug('response: {}'.format(response))
        except ClientError as e:
            logger.debug('error: {}'.format(e))

        return {'statusCode': 200, 'body': json.dumps(user_obj)}
    elif 'message' in body:
        return {
            'statusCode': body.get('statusCode', 400),
            'body': json.dumps({'error': body['message']})
        }
    else:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Unknown Error happened'})
        }
Exemple #3
0
def signup(event, context):
    event_log = deepcopy(event)
    try:
        event_log["body"].pop("password")
    except KeyError:
        pass
    logger.debug('event: {}'.format(event_log))

    if os.environ[
            'SIGNUP_ORIGIN_URL'] is not "*":  # "*" means accept any origin
        # Check if the request is originating from a valid URI
        origin = event['headers']['origin']
        valid_origin_uri = urlparse(os.environ['SIGNUP_ORIGIN_URL'])
        request_uri = urlparse(origin)

        if request_uri.netloc not in valid_origin_uri.netloc:
            logger.error("Request origin domain: {REQ_DOM}, "
                         "Valid origin domain: {VALID_DOM}".format(
                             REQ_DOM=request_uri.netloc,
                             VALID_DOM=valid_origin_uri.netloc))
            return {
                'statusCode':
                401,
                'body':
                json.dumps({
                    'error':
                    'Unauthorized. Request originating from invalid domain'
                })
            }

    try:
        body = get_body(event)
    except json.JSONDecodeError:
        logger.error("bad JSON payload")
        return {
            'statusCode': 400,
            'body': json.dumps({'error': 'Bad parameter(s) in request'})
        }
    except:
        logger.log_uncaught_exception()

    if 'email' not in body or not body[
            'email'] or 'password' not in body or not body['password']:
        logger.error("username, and/or password is missing in JSON")
        return {
            'statusCode':
            400,
            'body':
            json.dumps({
                'error':
                'Missing required key-value pair(s) in request body'
            })
        }

    email = body['email']
    password = body['password']
    name = body.get('name', '')

    # get Machine-to-machine access token
    resp = requests.post(os.environ['AUTH0_DOMAIN'] + '/oauth/token',
                         json={
                             'grant_type':
                             'client_credentials',
                             'client_id':
                             os.environ['AUTH0_MANAGEMENT_API_CLIENT_ID'],
                             'client_secret':
                             os.environ['AUTH0_MANAGEMENT_API_CLIENT_SECRET'],
                             'audience':
                             os.environ['AUTH0_AUDIENCE'],
                             'scope':
                             'create:users'
                         },
                         headers={'content-type': "application/json"})

    body = resp.json()

    if all(k in body
           for k in ['access_token', 'scope', 'expires_in', 'token_type']):
        pass  # to the next section of code
    elif 'error_description' in body:
        logger.error(
            "POST /oauth/token did not return all of 'access_token, id_token, scope, expires_in, token_type'"
        )
        logger.error(body['error_description'])
        return {
            'statusCode': 400,
            'body': json.dumps({'error': body['error_description']})
        }
    else:
        logger.error(
            "POST /oauth/token did not return all of 'access_token, id_token, scope, expires_in, token_type'"
        )
        logger.error("No error message returned from Auth0")
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Unknown Error happened'})
        }

    access_token = body['access_token']

    payload = {
        'email': email,
        'password': password,
        'email_verified': True,
        'blocked': False,
        'connection': os.environ['AUTH0_CONNECTION'],
    }

    if name:
        payload['name'] = name

    resp = requests.post(os.environ['AUTH0_DOMAIN'] + "/api/v2/users",
                         json=payload,
                         headers={
                             'Authorization':
                             'Bearer {TOKEN}'.format(TOKEN=access_token),
                             'content-type':
                             "application/json"
                         })

    body = resp.json()

    if all(k in body for k in ['user_id', 'email']):
        user_id = body['user_id'][6:]
        email = body['email']

        # Make a repo object
        sys.path.append('data_dynamodb')
        sys.path.append('data_common')
        from data_dynamodb.dynamodb_repository import DynamoRepository

        # While developing, dynamodb local is used. So if `DYANMODB_LOCAL_ENDPOINT` is present in env vars
        # dynamodb boto client is patched to use local db
        try:
            repo = DynamoRepository(
                region_name=os.environ['REGION'],
                table='sp-{STAGE}'.format(STAGE=os.environ['STAGE']),
                user_id=user_id,
                email=email,
                dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT'])

        except KeyError:
            repo = DynamoRepository(
                region_name=os.environ['REGION'],
                table='sp-{STAGE}'.format(STAGE=os.environ['STAGE']),
                user_id=user_id,
                email=email)
        # create new user in `'sp-' + os.environ['STAGE'] + 'user'` table
        user_obj = repo.get_or_create_profile()

        if 'name' in body:
            user_obj['name'] = body['name']
        if 'picture' in body:
            user_obj['avatar_url'] = body['picture']
        if 'nickname' in body:
            user_obj['nickname'] = body['nickname']
        if 'email_verified' in body:
            user_obj['email_verified'] = body['email_verified']
        if 'blocked' in body:
            user_obj['blocked'] = body['blocked']

        user_obj = repo.update_profile(user_obj)

        return {'statusCode': 200, 'body': json.dumps(user_obj)}
    elif 'message' in body:
        logger.error(
            "Failed: POST %AUTH0_DOMAIN%/api/v2/users for AUTH0_DOMAIN={AUTH0_DOMAIN}"
            .format(AUTH0_DOMAIN=os.environ['AUTH0_DOMAIN']))
        logger.error(body['message'])
        return {
            'statusCode': body.get('statusCode', 400),
            'body': json.dumps({'error': body['message']})
        }
    else:
        logger.error(
            "Failed: POST %AUTH0_DOMAIN%/api/v2/users for AUTH0_DOMAIN={AUTH0_DOMAIN}"
            .format(AUTH0_DOMAIN=os.environ['AUTH0_DOMAIN']))
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Unknown Error happened'})
        }