def get_projects_by_external_id(project_external_id, username): """ Returns the CLA projects requested by External ID. :param project_external_id: The project's External ID. :type project_external_id: string :param username: username of the user :type username: string :return: dict representation of the project object. :rtype: dict """ # Check if user has permissions on this project user_permissions = UserPermissions() try: user_permissions.load(username) except DoesNotExist as err: return {'errors': {'username': '******'}} user_permissions_json = user_permissions.to_dict() authorized_projects = user_permissions_json.get('projects') if project_external_id not in authorized_projects: return {'errors': {'username': '******'}} try: project = Project() projects = project.get_projects_by_external_id(str(project_external_id), username) except DoesNotExist as err: return {'errors': {'project_external_id': str(err)}} return [project.to_dict() for project in projects]
def check_user_authorization(auth_user: AuthUser, sfid): # Check if user has permissions on this project user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except DoesNotExist as err: return { 'valid': False, 'errors': { 'errors': { 'user does not exist': str(err) } } } user_permissions_json = user_permissions.to_dict() authorized_projects = user_permissions_json.get('projects') if sfid not in authorized_projects: return { 'valid': False, 'errors': { 'errors': { 'user is not authorized for this Salesforce ID.': str(sfid) } } } return {'valid': True}
def get_organization_by_sfid(auth_user: AuthUser, sfid): # Check if user has permissions user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except DoesNotExist as err: cla.log.warning('user {} does not exist, error: {}'.format( auth_user.username, err)) return {'errors': {'user does not exist': str(err)}} user_permissions_json = user_permissions.to_dict() authorized_projects = user_permissions_json.get('projects') if sfid not in authorized_projects: cla.log.warning( 'user {} is not authorized for this Salesforce ID: {}'.format( auth_user.username, sfid)) return { 'errors': { 'user is not authorized for this Salesforce ID.': str(sfid) } } # Get all organizations under an SFDC ID try: organizations = get_github_organization_instance( ).get_organization_by_sfid(sfid) except DoesNotExist as err: cla.log.warning('sfid {} does not exist, error: {}'.format(sfid, err)) return {'errors': {'sfid': str(err)}} return [organization.to_dict() for organization in organizations]
def add_permission(auth_user: AuthUser, username: str, project_sfdc_id: str): if auth_user.username not in admin_list: return {'error': 'unauthorized'} cla.log.info('project ({}) added for user ({}) by {}'.format( project_sfdc_id, username, auth_user.username)) user_permission = UserPermissions() try: user_permission.load(username) except Exception as err: print('user not found. creating new user: {}'.format(err)) # create new user user_permission = UserPermissions(username=username) user_permission.add_project(project_sfdc_id) user_permission.save() event_data = 'User {} given permissions to project {}'.format( username, project_sfdc_id) Event.create_event( event_data=event_data, event_summary=event_data, event_project_id=project_sfdc_id, event_type=EventType.AddPermission, contains_pii=True, )
def remove_permission(auth_user: AuthUser, username: str, project_sfdc_id: str): if auth_user.username not in admin_list: return {'error': 'unauthorized'} cla.log.info('project ({}) removed for ({}) by {}'.format( project_sfdc_id, username, auth_user.username)) user_permission = UserPermissions() try: user_permission.load(username) except Exception as err: print('Unable to update user permission: {}'.format(err)) return {'error': err} event_data = 'User {} permission removed to project {}'.format( username, project_sfdc_id) user_permission.remove_project(project_sfdc_id) user_permission.save() Event.create_event( event_type=EventType.RemovePermission, event_data=event_data, event_summary=event_data, event_project_id=project_sfdc_id, contains_pii=True, )
def add_permission(auth_user: AuthUser, username: str, project_sfdc_id: str): if auth_user.username not in admin_list: return {'error': 'unauthorized'} cla.log.info('project ({}) added for user ({}) by {}'.format( project_sfdc_id, username, auth_user.username)) user_permission = UserPermissions() try: user_permission.load(username) except Exception as err: print('user not found. creating new user: {}'.format(err)) # create new user user_permission = UserPermissions(username=username) user_permission.add_project(project_sfdc_id) user_permission.save()
def check_user_authorization(auth_user: AuthUser, sfid): cla.log.debug( f'checking user permissions for user: {auth_user.username} for sfid: {sfid}' ) # Check if user has permissions on this project user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except DoesNotExist as err: cla.log.warning( f'unable to load user record by: {auth_user.username} for sfid: {sfid}' ) return { 'valid': False, 'errors': { 'errors': { 'user does not exist': str(err) } } } user_permissions_json = user_permissions.to_dict() cla.log.debug( f'checking user permissions for user: {auth_user.username} for authorized projects...' ) authorized_projects = user_permissions_json.get('projects') if sfid not in authorized_projects: cla.log.warning( f'user: {auth_user.username} is not authorized for sfid: {sfid}') return { 'valid': False, 'errors': { 'errors': { 'user is not authorized for this Salesforce ID.': str(sfid) } } } cla.log.warning( f'user: {auth_user.username} is authorized for sfid: {sfid}') return {'valid': True}
def remove_permission(auth_user: AuthUser, username: str, project_sfdc_id: str): if auth_user.username not in admin_list: return {'error': 'unauthorized'} cla.log.info('project ({}) removed for ({}) by {}'.format( project_sfdc_id, username, auth_user.username)) user_permission = UserPermissions() try: user_permission.load(username) except Exception as err: print('Unable to update user permission: {}'.format(err)) return {'error': err} user_permission.remove_project(project_sfdc_id) user_permission.save()
def get_projects(event, context): """ Gets list of all projects from Salesforce """ # cla.log.debug('event: {}'.format(event)) # cla.log.debug(f'context: {context}') try: auth_user = cla.auth.authenticate_user(event.get('headers')) except cla.auth.AuthError as e: cla.log.error('Authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') except Exception as e: cla.log.error('Unknown authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') # import pdb; pdb.set_trace() # Get project access list for user user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except Exception as e: cla.log.error('Error invalid username: {}. error: {}'.format(auth_user.username, e)) return format_json_cors_response(400, 'Error invalid username') user_permissions = user_permissions.to_dict() authorized_projects = user_permissions.get('projects') if authorized_projects is None: cla.log.error('Error user not authorized to access projects: {}'.format(user_permissions)) return format_json_cors_response(403, 'Error user not authorized to access projects') project_list = ','.join([id for id in authorized_projects]) cla.log.info(f'User authorized_projects : {authorized_projects}') access_token, code = get_access_token() if code != HTTPStatus.OK: cla.log.error('Authentication failure') return format_json_cors_response(code, 'Authentication failure') headers = { 'Authorization': f'bearer {access_token}', 'accept': 'application/json' } query_url = f'{platform_gateway_url}/project-service/v1/projects/search?id={project_list}' cla.log.info(f'Query project service url: {query_url}') resp = requests.get(query_url, headers=headers) response = json.loads(resp.text) cla.log.info('response :%s '% resp) status_code = resp.status_code if status_code != HTTPStatus.OK: cla.log.error('Error retrieving projects: %s', response[0].get('message')) return format_json_cors_response(status_code, 'Error retrieving projects') records = response.get('Data') projects = [] for project in records: # use our S3 bucket Logos for now, if we want to switch to other logos # we'll need to update the CORS policy logo_url = None project_id = project.get('ID') if project_id: logo_url = '{}/{}.png'.format(cla_logo_url, project_id) projects.append({ 'name': project.get('Name'), 'id': project.get('ID'), 'description': project.get('Description'), 'logoUrl': logo_url # 'logoUrl': project.get('ProjectLogo') # SF Logo link }) return format_json_cors_response(status_code, projects)
def get_project(event, context): """ Given project id, gets project details from Salesforce """ cla.log.info('event: {}'.format(event)) project_id = event.get('queryStringParameters').get('id') if project_id is None: return format_json_cors_response(400, 'Missing project ID') try: auth_user = cla.auth.authenticate_user(event.get('headers')) except cla.auth.AuthError as e: cla.log.error('Authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') except Exception as e: cla.log.error('Unknown authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') # Get project access list for user user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except: cla.log.error(' Error invalid username: {}'.format(auth_user.username)) return format_json_cors_response(400, 'Error invalid username') user_permissions = user_permissions.to_dict() authorized_projects = user_permissions.get('projects') if authorized_projects is None: cla.log.error('Error user not authorized to access projects: {}'.format(user_permissions)) return format_json_cors_response(403, 'Error user not authorized to access projects') if project_id not in authorized_projects: cla.log.error('Error user not authorized') return format_json_cors_response(403, 'Error user not authorized') token, code = get_access_token() if code != HTTPStatus.OK: cla.log.error('Authentication failure') return format_json_cors_response(code, 'Authentication failure') headers = { 'Authorization': 'Bearer {}'.format(token) } url = f'{platform_gateway_url}/project-service/v1/projects/search?id={project_id}' cla.log.info('Using Project service to get project info..') resp = requests.get(url, headers=headers) response = resp.json() status_code = resp.status_code if status_code != HTTPStatus.OK: cla.log.error('Error retrieving project: %s', response[0].get('message')) return format_json_cors_response(status_code, 'Error retrieving project') result = response['Data'][0] if result: cla.log.info(f'Found project : {result} ') # use our S3 bucket Logos for now, if we want to switch to other logos # we'll need to update the CORS policy logo_url = None project_id = result.get('ID') if project_id: logo_url = '{}/{}.png'.format(cla_logo_url, project_id) project = { 'name': result.get('Name'), 'id': result.get('ID'), 'description': result.get('Description'), 'logoUrl': logo_url # 'logoUrl': result.get('ProjectLogo') # SF logo link } return format_json_cors_response(status_code, project)
def get_projects(event, context): """ Gets list of all projects from Salesforce """ cla.log.debug('event: {}'.format(event)) try: auth_user = cla.auth.authenticate_user(event.get('headers')) except cla.auth.AuthError as e: cla.log.error('Authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') except Exception as e: cla.log.error('Unknown authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') # Get project access list for user user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except Exception as e: cla.log.error('Error invalid username: {}. error: {}'.format(auth_user.username, e)) return format_json_cors_response(400, 'Error invalid username') user_permissions = user_permissions.to_dict() authorized_projects = user_permissions.get('projects') if authorized_projects is None: cla.log.error('Error user not authorized to access projects: {}'.format(user_permissions)) return format_json_cors_response(403, 'Error user not authorized to access projects') project_list = ', '.join('\'' + project_id + '\'' for project_id in authorized_projects) oauth_response = get_sf_oauth_access() if oauth_response is None: cla.log.error('Unable to acquire oauth token.') return format_json_cors_response(400, 'authentication error') token = oauth_response['access_token'] instance_url = oauth_response['instance_url'] headers = { 'Authorization': 'Bearer {}'.format(token), 'Content-Type': 'application/json', } query_url = '{}/services/data/v20.0/query/'.format(instance_url) query = {'q': 'SELECT id, Name, Description__c from Project__c WHERE id IN ({})'.format(project_list)} r = requests.get(query_url, headers=headers, params=query) response = r.json() status_code = r.status_code if status_code != HTTPStatus.OK: cla.log.error('Error retrieving projects: %s', response[0].get('message')) return format_json_cors_response(status_code, 'Error retrieving projects') records = response.get('records') projects = [] for project in records: logo_url = None project_id = project.get('Id') if project_id: logo_url = '{}/{}.png'.format(cla_logo_url, project_id) projects.append({ 'name': project.get('Name'), 'id': project_id, 'description': project.get('Description__c'), 'logoUrl': logo_url }) return format_json_cors_response(status_code, projects)
def get_project(event, context): """ Given project id, gets project details from Salesforce """ cla.log.info('event: {}'.format(event)) project_id = event.get('queryStringParameters').get('id') if project_id is None: return format_json_cors_response(400, 'Missing project ID') try: auth_user = cla.auth.authenticate_user(event.get('headers')) except cla.auth.AuthError as e: cla.log.error('Authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') except Exception as e: cla.log.error('Unknown authorization error: {}'.format(e)) return format_json_cors_response(401, 'Error parsing Bearer token') # Get project access list for user user_permissions = UserPermissions() try: user_permissions.load(auth_user.username) except: cla.log.error('Error invalid username: {}'.format(auth_user.username)) return format_json_cors_response(400, 'Error invalid username') user_permissions = user_permissions.to_dict() authorized_projects = user_permissions.get('projects') if authorized_projects is None: cla.log.error('Error user not authorized to access projects: {}'.format(user_permissions)) return format_json_cors_response(403, 'Error user not authorized to access projects') if project_id not in authorized_projects: cla.log.error('Error user not authorized') return format_json_cors_response(403, 'Error user not authorized') oauth_response = get_sf_oauth_access() token = oauth_response['access_token'] instance_url = oauth_response['instance_url'] headers = { 'Authorization': 'Bearer {}'.format(token) } url = '{}/services/data/v20.0/sobjects/Project__c/{}'.format(instance_url, project_id) cla.log.info('Calling salesforce api for project info..') r = requests.get(url, headers=headers) response = r.json() status_code = r.status_code if status_code != HTTPStatus.OK: cla.log.error('Error retrieving project: %s', response[0].get('message')) return format_json_cors_response(status_code, 'Error retrieving project') logo_url = None if response.get('id'): logo_url = '{}/{}.png'.format(cla_logo_url, response.get('id')) project = { 'name': response.get('Name'), 'id': response.get('Id'), 'description': response.get('Description__c'), 'logoUrl': logo_url } return format_json_cors_response(status_code, project)