def POST(request): """Add a new User.""" request.check_required_parameters(body={'user': {'email': 'string'}}) user = User(request.params_body['user']) user.set_property('googleId', request.google_id) user.set_property('authorizations', []) user.check_already_exists() user.insert() return Response(200, 'Successfully created user.', user.obj)
def DELETE(request): """Delete this Project.""" request.check_required_parameters(path={'projectId': 'string'}) project = Project.from_id(request.params_path['projectId']) project.check_exists() project.check_user_access(request.google_id, True) for topology_id in project.obj['topologyIds']: topology = Topology.from_id(topology_id) topology.delete() for portfolio_id in project.obj['portfolioIds']: portfolio = Portfolio.from_id(portfolio_id) portfolio.delete() user = User.from_google_id(request.google_id) user.obj['authorizations'] = list( filter(lambda x: x['projectId'] != project.get_id(), user.obj['authorizations'])) user.update() old_object = project.delete() return Response(200, 'Successfully deleted project.', old_object)
def POST(request): """Create a new project, and return that new project.""" request.check_required_parameters(body={'project': {'name': 'string'}}) topology = Topology({'name': 'Default topology', 'rooms': []}) topology.insert() project = Project(request.params_body['project']) project.set_property('datetimeCreated', Database.datetime_to_string(datetime.now())) project.set_property('datetimeLastEdited', Database.datetime_to_string(datetime.now())) project.set_property('topologyIds', [topology.get_id()]) project.set_property('portfolioIds', []) project.insert() topology.set_property('projectId', project.get_id()) topology.update() user = User.from_google_id(request.google_id) user.obj['authorizations'].append({ 'projectId': project.get_id(), 'authorizationLevel': 'OWN' }) user.update() return Response(200, 'Successfully created project.', project.obj)
def POST(request): """Add a new User.""" # Make sure required parameters are there try: request.check_required_parameters(body={'user': {'email': 'string'}}) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a User request.params_body['user']['googleId'] = request.google_id user = User.from_JSON(request.params_body['user']) # Make sure a User with this Google ID does not already exist if user.exists('google_id'): user = user.from_google_id(user.google_id) return Response(409, '{} already exists.'.format(user)) # Make sure this User is authorized to create this User if not request.google_id == user.google_id: return Response(403, 'Forbidden from creating this User.') # Insert the User user.insert() # Return a JSON representation of the User return Response(200, 'Successfully created {}'.format(user), user.to_JSON())
def GET(request): """Get this User.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'userId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a User and make sure they exist user = User.from_primary_key((request.params_path['userId'],)) if not user.exists(): return Response(404, '{} not found.'.format(user)) # Return this User return Response( 200, 'Successfully retrieved {}'.format(user), user.to_JSON(), )
def GET(request): """Search for a User using their email address.""" request.check_required_parameters(query={'email': 'string'}) user = User.from_email(request.params_query['email']) user.check_exists() return Response(200, 'Successfully retrieved user.', user.obj)
def GET(request): """Get this User.""" request.check_required_parameters(path={'userId': 'string'}) user = User.from_id(request.params_path['userId']) user.check_exists() return Response(200, 'Successfully retrieved user.', user.obj)
def check_user_access(self, google_id, edit_access): """Raises an error if the user with given [google_id] has insufficient access. :param google_id: The Google ID of the user. :param edit_access: True when edit access should be checked, otherwise view access. """ user = User.from_google_id(google_id) authorizations = list(filter(lambda x: str(x['projectId']) == str(self.get_id()), user.obj['authorizations'])) if len(authorizations) == 0 or (edit_access and authorizations[0]['authorizationLevel'] == 'VIEW'): raise ClientError(Response(403, "Forbidden from retrieving project."))
def google_id_has_at_least(self, google_id, authorization_level): """Return True if the User has at least the given auth level over this Authorization.""" authorization = Authorization.from_primary_key( ( User.from_google_id(google_id).id, self.simulation_id ) ) if authorization is None: return False return authorization.has_at_least(authorization_level)
def check_user_access(self, google_id): """Raises an error if the user with given [google_id] has insufficient access to view this prefab. :param google_id: The Google ID of the user. """ user = User.from_google_id(google_id) # TODO(Jacob) add special handling for OpenDC-provided prefabs #try: print(self.obj) if self.obj['authorId'] != user.get_id( ) and self.obj['visibility'] == "private": raise ClientError( Response(403, "Forbidden from retrieving prefab."))
def google_id_has_at_least(self, google_id, authorization_level): """Return True if the user has at least the given auth level over this Path.""" # Get the User id try: user_id = User.from_google_id(google_id).read().id except exceptions.RowNotFoundError: return False # Check the Authorization authorization = Authorization.from_primary_key( (user_id, self.simulation_id)) return authorization.has_at_least(authorization_level)
def PUT(request): """Update this User's given name and/ or family name.""" # Make sure the required parameters are there try: request.check_required_parameters( body={ 'user': { 'givenName': 'string', 'familyName': 'string' } }, path={ 'userId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a User and make sure they exist user = User.from_primary_key((request.params_path['userId'],)) if not user.exists(): return Response(404, '{} not found.'.format(user)) # Make sure this User is allowed to edit this User if not user.google_id_has_at_least(request.google_id, 'OWN'): return Response(403, 'Forbidden from editing {}.'.format(user)) # Update this User user.given_name = request.params_body['user']['givenName'] user.family_name = request.params_body['user']['familyName'] user.update() # Return this User return Response( 200, 'Successfully updated {}.'.format(user), user.to_JSON() )
def POST(request): """Create a new prefab, and return that new prefab.""" request.check_required_parameters(body={'prefab': {'name': 'string'}}) prefab = Prefab(request.params_body['prefab']) prefab.set_property('datetimeCreated', Database.datetime_to_string(datetime.now())) prefab.set_property('datetimeLastEdited', Database.datetime_to_string(datetime.now())) user = User.from_google_id(request.google_id) prefab.set_property('authorId', user.get_id()) prefab.insert() return Response(200, 'Successfully created prefab.', prefab.obj)
def GET(request): """Return all prefabs the user is authorized to access""" user = User.from_google_id(request.google_id) user.check_exists() own_prefabs = DB.fetch_all({'authorId': user.get_id()}, Prefab.collection_name) public_prefabs = DB.fetch_all({'visibility': 'public'}, Prefab.collection_name) authorizations = {"authorizations": []} authorizations["authorizations"].append(own_prefabs) authorizations["authorizations"].append(public_prefabs) return Response(200, 'Successfully fetched authorizations.', authorizations)
def check_user_access(self, google_id, edit_access): """Raises an error if the user with given [google_id] has insufficient access. Checks access on the parent project. :param google_id: The Google ID of the user. :param edit_access: True when edit access should be checked, otherwise view access. """ portfolio = Portfolio.from_id(self.obj['portfolioId']) user = User.from_google_id(google_id) authorizations = list( filter( lambda x: str(x['projectId']) == str(portfolio.obj[ 'projectId']), user.obj['authorizations'])) if len(authorizations) == 0 or ( edit_access and authorizations[0]['authorizationLevel'] == 'VIEW'): raise ClientError( Response(403, 'Forbidden from retrieving/editing scenario.'))
def DELETE(request): """Delete this User.""" request.check_required_parameters(path={'userId': 'string'}) user = User.from_id(request.params_path['userId']) user.check_exists() user.check_correct_user(request.google_id) for authorization in user.obj['authorizations']: if authorization['authorizationLevel'] != 'OWN': continue project = Project.from_id(authorization['projectId']) project.delete() old_object = user.delete() return Response(200, 'Successfully deleted user.', old_object)
def PUT(request): """Update this User's given name and/or family name.""" request.check_required_parameters( body={'user': { 'givenName': 'string', 'familyName': 'string' }}, path={'userId': 'string'}) user = User.from_id(request.params_path['userId']) user.check_exists() user.check_correct_user(request.google_id) user.set_property('givenName', request.params_body['user']['givenName']) user.set_property('familyName', request.params_body['user']['familyName']) user.update() return Response(200, 'Successfully updated user.', user.obj)
def DELETE(request): """Delete this user.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'userId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a User and make sure they exist user = User.from_primary_key((request.params_path['userId'],)) if not user.exists(): return Response(404, '{} not found'.format(user)) # Make sure this User is allowed to delete this User if not user.google_id_has_at_least(request.google_id, 'OWN'): return Response(403, 'Forbidden from deleting {}.'.format(user)) # Delete this User user.delete() # Return this User return Response( 200, 'Successfully deleted {}'.format(user), user.to_JSON() )
def sign_in(): """Authenticate a user with Google sign in""" try: token = request.form['idtoken'] except KeyError: return 'No idtoken provided', 401 try: idinfo = client.verify_id_token(token, os.environ['OPENDC_OAUTH_CLIENT_ID']) if idinfo['aud'] != os.environ['OPENDC_OAUTH_CLIENT_ID']: raise crypt.AppIdentityError('Unrecognized client.') if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise crypt.AppIdentityError('Wrong issuer.') except ValueError: url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}".format( token) req = urllib.request.Request(url) response = urllib.request.urlopen(url=req, timeout=30) res = response.read() idinfo = json.loads(res) except crypt.AppIdentityError as e: return 'Did not successfully authenticate' user = User.from_google_id(idinfo['sub']) data = {'isNewUser': user.obj is None} if user.obj is not None: data['userId'] = user.get_id() return jsonify(**data)
def GET(request): """Search for a User using their email address.""" # Make sure required parameters are there try: request.check_required_parameters(query={'email': 'string'}) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate and read a User from the database user = User.from_email(request.params_query['email']) # Make sure this User exists in the database if not user.exists(): return Response(404, '{} not found'.format(user)) # Return this User return Response(200, 'Successfully retrieved {}.'.format(user), user.to_JSON())
def GET(request): """Get this User's Authorizations.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'userId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a User and make sure they exist user = User.from_primary_key((request.params_path['userId'],)) if not user.exists(): return Response(404, '{} not found.'.format(user)) # Make sure this requester is allowed to retrieve this User's Authorizations if not user.google_id_has_at_least(request.google_id, 'OWN'): return Response(403, 'Forbidden from retrieving Authorizations for {}.'.format(user)) # Return this User's Authorizations authorizations = Authorization.query('user_id', request.params_path['userId']) return Response( 200, 'Successfully retrieved Authorizations for {}.'.format(user), [x.to_JSON() for x in authorizations] )
if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise crypt.AppIdentityError('Wrong issuer.') except ValueError: url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}".format( token) req = urllib2.Request(url) response = urllib2.urlopen(url=req, timeout=30) res = response.read() idinfo = json.loads(res) except crypt.AppIdentityError, e: return 'Did not successfully authenticate' user = User.from_google_id(idinfo['sub']) data = {'isNewUser': not user.exists()} if user.exists(): data['userId'] = user.id return jsonify(**data) @FLASK_CORE_APP.route('/api/<string:version>/<path:endpoint_path>', methods=['GET', 'POST', 'PUT', 'DELETE']) def api_call(version, endpoint_path): """Call an API endpoint directly over HTTP""" # Get path and parameters
def POST(request): """Add an authorization for a user's access to a simulation.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'userId': 'int', 'simulationId': 'int' }, body={'authorization': { 'authorizationLevel': 'string' }}) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate an Authorization authorization = Authorization.from_JSON({ 'userId': request.params_path['userId'], 'simulationId': request.params_path['simulationId'], 'authorizationLevel': request.params_body['authorization']['authorizationLevel'] }) # Make sure the Simulation and User exist user = User.from_primary_key((authorization.user_id, )) if not user.exists(): return Response(404, '{} not found.'.format(user)) simulation = Simulation.from_primary_key((authorization.simulation_id, )) if not simulation.exists(): return Response(404, '{} not found.'.format(simulation)) # Make sure this User is allowed to add this Authorization if not simulation.google_id_has_at_least(request.google_id, 'OWN'): return Response(403, 'Forbidden from creating {}.'.format(authorization)) # Make sure this Authorization does not already exist if authorization.exists(): return Response(409, '{} already exists.'.format(authorization)) # Try to insert this Authorization into the database try: authorization.insert() except exceptions.ForeignKeyError: return Response(400, 'Invalid authorizationLevel') # Return this Authorization return Response(200, 'Successfully added {}'.format(authorization), authorization.to_JSON())
def POST(request): """Create a new simulation, and return that new simulation.""" # Make sure required parameters are there try: request.check_required_parameters( body={'simulation': { 'name': 'string' }}) except exceptions.ParameterError as e: return Response(400, e.message) # Instantiate a Simulation simulation_data = request.params_body['simulation'] simulation_data['datetimeCreated'] = database.datetime_to_string( datetime.now()) simulation_data['datetimeLastEdited'] = database.datetime_to_string( datetime.now()) simulation = Simulation.from_JSON(simulation_data) # Insert this Simulation into the database simulation.insert() # Instantiate an Authorization and insert it into the database authorization = Authorization(user_id=User.from_google_id( request.google_id).id, simulation_id=simulation.id, authorization_level='OWN') authorization.insert() # Instantiate a Path and insert it into the database path = Path(simulation_id=simulation.id, datetime_created=database.datetime_to_string(datetime.now())) path.insert() # Instantiate a Datacenter and insert it into the database datacenter = Datacenter(starred=0, simulation_id=simulation.id) datacenter.insert() # Instantiate a Section and insert it into the database section = Section(path_id=path.id, datacenter_id=datacenter.id, start_tick=0) section.insert() # Return this Simulation return Response(200, 'Successfully created {}.'.format(simulation), simulation.to_JSON())