def delete(self, id, path): """Handles DELETE for devtest""" Config = config.config() if not Config.devtest: self.response.set_status(404) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='devtest', subpath=path) if not myself or check.response["code"] != 200: return paths = path.split('/') if paths[0] == 'proxy': mytwin = myself.getPeerTrustee(shorttype='myself') if mytwin: if paths[1] == 'properties': proxy = aw_proxy.aw_proxy(peer_target=mytwin) prop = proxy.deleteResource(path='/properties') self.response.set_status(proxy.last_response_code) return elif paths[0] == 'ping': self.response.set_status(204) return self.response.set_status(404)
def get(self, id, path): """Handles GET for devtest""" Config = config.config() if not Config.devtest: self.response.set_status(404) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='devtest', subpath=path) if not myself or check.response["code"] != 200: return paths = path.split('/') if paths[0] == 'proxy': mytwin = myself.getPeerTrustee(shorttype='myself') if mytwin: if paths[1] == 'properties': proxy = aw_proxy.aw_proxy(peer_target=mytwin) prop = proxy.getResource(path='/properties') if proxy.last_response_code != 200: self.response.set_status(proxy.last_response_code) return out = json.dumps(prop) self.response.write(out.encode('utf-8')) self.response.headers["Content-Type"] = "application/json" self.response.set_status(200) return elif paths[0] == 'ping': self.response.set_status(204) return self.response.set_status(404)
def put(self, id, path): """Handles PUT for devtest""" Config = config.config() if not Config.devtest: self.response.set_status(404) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='devtest', subpath=path) if not myself or check.response["code"] != 200: return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) except: params = None paths = path.split('/') if paths[0] == 'proxy': mytwin = myself.getPeerTrustee(shorttype='myself') if mytwin: if paths[1] == 'properties' and paths[2] and len(paths[2]) > 0: proxy = aw_proxy.aw_proxy(peer_target=mytwin) if params: proxy.changeResource('/properties/' + paths[2], params=params) self.response.set_status(proxy.last_response_code) return elif paths[0] == 'ping': self.response.set_status(204) return self.response.set_status(404)
def get(self): if not self.request.get('code'): self.response.set_status(400, "Bad request. No code.") return code = self.request.get('code') id = self.request.get('state') Config = config.config() self.redirect(Config.root + str(id) + '/oauth?code=' + str(code))
def get(self): if self.request.get('_method') == 'POST': self.post() return Config = config.config() if Config.ui: template_values = {} path = os.path.join(os.path.dirname(__file__), 'templates/aw-root-factory.html') self.response.write( template.render(path, template_values).encode('utf-8')) else: self.response.set_status(404)
def post(self): myself = actor.actor() Config = config.config() try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) is_json = True if 'creator' in params: creator = params['creator'] else: creator = '' if 'trustee_root' in params: trustee_root = params['trustee_root'] else: trustee_root = '' if 'passphrase' in params: passphrase = params['passphrase'] else: passphrase = '' except ValueError: is_json = False creator = self.request.get('creator') trustee_root = self.request.get('trustee_root') passphrase = self.request.get('passphrase') myself.create(url=self.request.url, creator=creator, passphrase=passphrase) if len(trustee_root) > 0: myself.setProperty('trustee_root', trustee_root) self.response.headers.add_header("Location", Config.root + myself.id) if Config.www_auth == 'oauth' and not is_json: self.redirect(Config.root + myself.id + '/www') return pair = { 'id': myself.id, 'creator': myself.creator, 'passphrase': myself.passphrase, } if len(trustee_root) > 0: pair['trustee_root'] = trustee_root if Config.ui and not is_json: path = os.path.join(os.path.dirname(__file__), 'templates/aw-root-created.html') self.response.write(template.render(path, pair).encode('utf-8')) return out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" self.response.set_status(201, 'Created')
def on_delete_resources(myself, req, auth, name): """ Called on DELETE to resources. Return struct for json out. Returning {} will give a 404 response back to requestor. """ Config = config.config() path = name.lower().split('/') if len(path) <= 1: return {} if path[0] == 'folders': folderId = path[1] boxLink = box.box(auth=auth, actorId=myself.id) boxLink.cleanupFolder(folder_id=folderId) req.response.set_status(204) return 204 return {}
def on_put_resources(myself, req, auth, name, params): """ Called on PUT to resources. Return struct for json out. Returning {} will give a 404 response back to requestor. Returning an error code after setting the response will not change the error code. """ Config = config.config() path = name.lower().split('/') if len(path) <= 1: return {} if path[0] == 'folders': folderId = path[1] if 'collaborations' not in params: req.response.set_status(405, "Mandatory parameter collaborations missing") return 405 boxLink = box.box(auth=auth, actorId=myself.id) for collab in params['collaborations']: if 'email' not in collab: continue if 'role' in collab: role = collab['role'] else: role = 'editor' if 'notify' in collab: notify = collab['notify'] else: notify = False if 'action' in collab and collab['action'] == 'delete': if not boxLink.deleteCollaboration(folder_id=folderId, email=collab['email']): logging.warn('Failed to delete collaboration user(' + collab['email'] + ') in folder(' + folderId + ')') else: if not boxLink.createCollaboration(folder_id=folderId, email=collab['email'], role=role, notify=notify): logging.warn('Failed to add collaboration user(' + collab['email'] + ') in folder(' + folderId + ')') req.response.set_status(200) return 200 return {}
def on_get_resources(myself, req, auth, name): """ Called on GET to resources. Return struct for json out. Returning {} will give a 404 response back to requestor. """ Config = config.config() path = name.lower().split('/') if len(path) <= 1: return {} if path[0] == 'folders': folderId = path[1] boxLink = box.box(auth=auth, actorId=myself.id) folder = boxLink.getFolder(folder_id=folderId) if folder: del folder['webhookId'] return folder return {}
def delete(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself or (check.response["code"] != 200 and check.response["code"] != 401): auth.add_auth_response(appreq=self, auth_obj=check) return # We allow non-approved peers to delete even if we haven't approved the relationship yet if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='DELETE', peerid=peerid, approved=False): self.response.set_status(403) return isPeer = False if check.trust and check.trust.peerid == peerid: isPeer = True else: # Use of GET param peer=true is a way of forcing no deletion of a peer # relationship even when requestor is not a peer (primarily for testing purposes) peerGet = self.request.get('peer').lower() if peerGet.lower() == "true": isPeer = True Config = config.config() relationships = myself.getTrustRelationships(relationship=relationship, peerid=peerid) if not relationships: self.response.set_status(404, 'Not found') return my_trust = relationships[0] if isPeer: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=False) else: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=True) if not deleted: self.response.set_status( 502, 'Not able to delete relationship with peer.') return self.response.set_status(204, 'Ok')
def post(self, path): """Handles POST callbacks for bots.""" Config = config.config() if not Config.bot['token'] or len(Config.bot['token']) == 0: self.response.set_status(404) return check = auth.auth(id=None) check.oauth.token = Config.bot['token'] ret = on_aw_bot.on_bot_post(req=self, auth=check, path=path) if ret and ret >= 100 and ret < 999: self.response.set_status(ret) return elif ret: self.response.set_status(204) return else: self.response.set_status(404) return
def on_bot_post(req, auth, path): """Called on POSTs to /bot. auth will be initialised with the configured bot token to do oauth-authorized API calls. However, there will not be any actor iniatialised. """ # Safety valve to make sure we don't do anything if bot is not # configured. Config = config.config() if not Config.bot['token'] or len(Config.bot['token']) == 0: return False #try: # body = json.loads(req.request.body.decode('utf-8', 'ignore')) # logging.debug('Bot callback: ' + req.request.body.decode('utf-8', 'ignore')) #except: # return 405 # # This is how actor can be initialised if the bot request # contains a value that has been stored as an actor property. # This value must be a primary key for the external oauth identity # that the actor is representing. # Here, oauthId (from oauth service) has earlier been stored as a property #myself = actor.actor() #myself.get_from_property(name='oauthId', value=<PROPERTY-VALUE>) #if myself.id: # logging.debug('Found actor(' + myself.id + ')') # # If we havent'' #if not myself.id: # myself.create(url=Config.root, creator= <EMAIL>, # passphrase=Config.newToken()) #Now store the oauthId propery # myself.setProperty('oauthId', <ID-VALUE>) # Send comfirmation message that actor has been created # return True # Do something return True
def post(self, id, path): """Handles POST for devtest""" Config = config.config() if not Config.devtest: self.response.set_status(404) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='devtest', subpath=path) if not myself or check.response["code"] != 200: return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) except: params = None paths = path.split('/') if paths[0] == 'proxy': mytwin = myself.getPeerTrustee(shorttype='myself') if mytwin: if paths[1] == 'create': proxy = aw_proxy.aw_proxy(peer_target=mytwin) meta = proxy.getResource(path='/meta') if params: proxy.createResource('/properties', params=params) out = json.dumps(meta) self.response.write(out.encode('utf-8')) self.response.headers["Content-Type"] = "application/json" self.response.headers["Location"] = mytwin.baseuri self.response.set_status(200) return elif paths[0] == 'ping': self.response.set_status(204) return self.response.set_status(404)
# import cgi import wsgiref.handlers from actingweb import actor from actingweb import auth from actingweb import config from actingweb.db import db import webapp2 import json import os from google.appengine.ext.webapp import template # Load global configurations Config = config.config() class MainPage(webapp2.RequestHandler): def get(self, id, path): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='meta', subpath=path, add_response=False) # We accept no auth here, so don't check response code if not myself: return if not check.checkAuthorisation( path='meta', subpath=path, method='GET'): self.response.set_status(403)
def on_post_resources(myself, req, auth, name, params): """ Called on POST to resources. Return struct for json out. Returning {} will give a 404 response back to requestor. Returning an error code after setting the response will not change the error code. """ Config = config.config() if name == 'folders': if 'name' in params: foldername = params['name'] else: self.response.set_status(405, 'Missing mandatory parameter') return if 'parent' in params: parent = params['parent'] else: parent = '0' boxLink = box.box(auth=auth, actorId=myself.id) folderid = boxLink.createFolder(foldername, parent) if not folderid: folder = boxLink.getFolder(name=foldername, parent=parent) pair = { 'error': { 'code': auth.oauth.last_response_code, 'message': auth.oauth.last_response_message, }, } if folder: pair['name'] = folder['name'] pair['parent'] = folder['parentId'] pair['id'] = folder['boxId'] pair['url'] = folder['url'] return pair url = boxLink.createLink(folder_id=folderid) if not url: url = '' if 'role' in params: role = params['role'] else: role = 'editor' if 'notify' in params: notify = params['notify'] else: notify = False if 'emails' in params: emails = params['emails'] boxLink.addUserAccess(folder_id=folderid, emails=emails, role=role, notify=notify) else: emails = {} boxLink.createWebhook(folder_id=folderid, callback=Config.root + myself.id + '/callbacks/box/' + folderid) req.response.headers.add_header("Location", str(Config.root + 'folders/' + folderid)) pair = { 'name': foldername, 'parent': parent, 'id': folderid, 'emails': emails, 'role': role, 'notify': notify, 'url': url, } return pair return {}
def on_post_callbacks(myself, req, auth, name): """Customizible function to handle POST /callbacks""" Config = config.config() logging.debug("Callback body: " + req.request.body.decode('utf-8', 'ignore')) try: body = json.loads(req.request.body.decode('utf-8', 'ignore')) except: return False path = name.split('/') if path[0] == 'box': trigger = '' filename = 'Not Available' foldername = 'Not Available' file_id = None folder_id = None user = '******' message = '' if 'trigger' in body: trigger = body['trigger'] if 'source' in body: if 'type' in body['source']: if body['source']['type'] == 'file' and 'name' in body[ 'source']: filename = body['source']['name'] elif body['source']['type'] == 'file' and 'id' in body[ 'source']: file_id = body['source']['id'] if body['source']['type'] == 'folder' and 'name' in body[ 'source']: foldername = body['source']['name'] elif body['source']['type'] == 'folder' and 'id' in body[ 'source']: folder_id = body['source']['id'] if body['source']['type'] == 'comment' and 'message' in body[ 'source']: message = body['source']['message'] if 'item' in body['source'] and 'type' in body['source'][ 'item']: if body['source']['item']['type'] == 'file': file_id = body['source']['item']['id'] elif body['source']['item']['type'] == 'folder': folder_id = body['source']['item']['id'] if 'created_by' in body: if 'name' in body['created_by']: user = body['created_by']['name'] boxLink = box.box(auth=auth, actorId=myself.id) if file_id and (trigger != 'FILE.TRASHED' and trigger != 'FILE.DELETED'): file = boxLink.getBoxFile(id=file_id) if file and 'name' in file: filename = file['name'] if folder_id and (trigger != 'FOLDER.TRASHED' and trigger != 'FOLDER.DELETED'): folder = boxLink.getBoxFolder(id=folder_id) if folder and 'name' in folder: foldername = folder['name'] logging.debug('Got trigger(' + trigger + ') for (file:' + filename + '/folder:' + foldername + ') by user ' + user) if trigger == 'FILE.UPLOADED': txt = user + ' uploaded a new file named: ' + filename elif trigger == 'FILE.TRASHED': txt = user + ' trashed a file named: ' + filename elif trigger == 'FILE.DELETED': txt = user + ' deleted a file named: ' + filename elif trigger == 'FILE.RESTORED': txt = user + ' restored a file named: ' + filename elif trigger == 'FILE.MOVED': txt = user + ' moved a file named: ' + filename elif trigger == 'FILE.LOCKED': txt = user + ' locked the file named: ' + filename elif trigger == 'FILE.UNLOCKED': txt = user + ' unlocked the file named: ' + filename elif trigger == 'COMMENT.CREATED': txt = user + ' commented on the file named: ' + filename + ' - ' + message elif trigger == 'COMMENT.UPDATED': txt = user + ' updated comment on the file named: ' + filename + ' - ' + message elif trigger == 'COMMENT.DELETED': txt = user + ' deleted comment on the file named: ' + filename + ' - ' + message elif trigger == 'FOLDER.CREATED': txt = user + ' created a new folder named: ' + foldername elif trigger == 'FOLDER.DELETED': txt = user + ' deleted a folder named: ' + foldername elif trigger == 'FOLDER.RESTORED': txt = user + ' restored a folder named: ' + foldername elif trigger == 'FOLDER.TRASHED': txt = user + ' trashed a folder named: ' + foldername elif trigger == 'FOLDER.MOVED': txt = user + ' moved a folder named: ' + foldername elif trigger == 'WEBHOOK.DELETED': txt = user + ' deleted the root folder named: ' + foldername params = { 'trigger': trigger, 'user': user, 'suggested_txt': txt, 'data': body, } if len(filename) > 0: params['name'] = filename elif len(foldername) > 0: params['name'] = foldername if len(message) > 0: params['message'] = message if body and 'webhook' in body and 'id' in body['webhook']: hook = boxLink.getWebhook(id=body['webhook']['id']) if hook and hook.folderId: blob = json.dumps(params) myself.registerDiffs(target='resources', subtarget='folders', resource=hook.folderId, blob=blob) req.response.set_status(204) return True req.response.set_status(404, "Callback not found.") return False