def main(event, context): # prepare the key to search in dynamodb recipe table key = {"recipeId": event["pathParameters"]["id"]} # Execute get item in dynamodb try: result = dynamodb.call(tableRegion, tableName, "get_item", Key=key) # Return 500 and status failed in case of error except: return response.failure(json.dumps({"status": "false"})) else: # Return 200 and the retrieved item if result is not None: return response.success( json.dumps(result["Item"], cls=DecimalEncoder)) # Return "item not found" and 500 with status failed when no item was found else: return response.failure( json.dumps({ "status": "false", "error": "Item not found." }))
def post(self): self.response.headers['Content-Type'] = 'application/json' member = validate_user_is_member_and_can_edit(self, "Member") if member: params = json.loads(self.request.body) memberData = params['data'] if get_member_by_email(memberData['email']): self.response.out.write(json.dumps(response.failure("500", "Email already in use"))) elif not mail.is_email_valid(memberData['email']): self.response.out.write(json.dumps(response.failure("500", "Invalid email address"))) else: newMember = Member() newMember.populate(**memberData) newMember.put() token = get_new_token(newMember.email) url = "%(host)s/validate?t=%(token)s" % {"host" : self.request.host_url, "token" : token.token} sender_address = member.email subject = "Confirm your membership" body = """ Thank you for creating an account! Please confirm your email address by clicking on the link below: %s """ % url mail.send_mail(sender_address, newMember.email, subject, body) self.response.write(json.dumps(response.success("success", {"email" : newMember.email})))
def validate_user_is_member_and_can_edit(self, oprn): user = validate_user(self) if user: member = get_member_by_email(user.email()) if member: if permission.check_permission(member, oprn): return member else: self.response.out.write(json.dumps(response.failure("401", "No Permission"))) else: self.response.out.write(json.dumps(response.failure("401", "Not a Member"))) return None
def apig_list(event, context): log.info("event={}".format(event)) log.info("context={}".format(str(context))) profile = "" if 'profile' in event.keys(): profile = event["profile"] ddb = ScriptletDynamoDB(app_name, profile) data = event["queryStringParameters"] user_id = data["user_id"] # user_id = data["requestContext"]["identity"]["cognitoIdentityId"] table_name = "portfolio" key = "user_id" value = user_id returned = ddb.query(table_name, key, value) log.info("returned['Count']={}".format(returned['Count'])) for item in returned['Items']: log.info("item={}".format(item)) if returned['Count'] > 0: response = success(returned['Items']) else: response = failure(returned['Items']) log.info("response={}".format(response)) return response
def apig_get(event, context): log.info("event={}".format(event)) log.info("context={}".format(str(context))) profile = "" if 'profile' in event.keys(): profile = event["profile"] ddb = ScriptletDynamoDB(app_name, profile) data = event["queryStringParameters"] user_id = data["user_id"] note_id = data["note_id"] table_name = "portfolio" key = {"user_id": {"S": user_id}, "note_id": {"S": note_id}} returned = ddb.get_item(table_name, key) item = returned["Item"]["content"] log.info("returned={}".format(item)) if len(returned.keys()) > 0: response = success(item) else: response = failure(item) log.info("response={}".format(response)) return response
def apig_update(event, context): log.info("event={}".format(event)) log.info("context={}".format(str(context))) profile = "" if 'profile' in event.keys(): profile = event["profile"] ddb = ScriptletDynamoDB(app_name, profile) data = json.loads(event["body"]) user_id = data["user_id"] note_id = data["note_id"] content = data["content"] table_name = "portfolio" key = { "user_id": {"S": user_id}, "note_id": {"S": note_id} } # should really wrap this is a try/catch block and then use the success/failure methods returned = ddb.update(table_name, key, content) log.info("returned={}".format(returned)) if returned["ResponseMetadata"]["HTTPStatusCode"] == 200: response = success(returned["Attributes"]) else: response = failure(returned["Attributes"]) log.info("response={}".format(response)) return response
def validate_user_is_member(self): user = validate_user(self) if user: member = get_member_by_email(user.email()) if member: return member else: self.response.out.write(json.dumps(response.failure("401", "Not a Member"))) return None
def get_post_perm(self): perm = Permission.query_model({ "oprn" : oprn }) if oprn == "Module" or oprn == "ModuleData": params = json.loads(self.request.body) if "modId" in params: modId = params['modId'] else: modId = 0 self.canEdit = ModulePermission.can_edit_module(self.member, modId) or (perm and self.member.permission >= perm.permission) or (self.member.permission >= LEADER_PERMISSION) #handle challenges properly if self.canEdit or (oprn == "ModuleData" and ((params['modType'] == "member-list" and params['data']['user_id'] == self.member.user_id) or (params['modType'] == "challenge"))): func(self) else: self.response.out.write(json.dumps(response.failure("401", "No permission to edit %s related data" % oprn))) elif (perm and self.member.permission >= perm.permission) or (self.member.permission >= LEADER_PERMISSION): func(self) else: self.response.out.write(json.dumps(response.failure("401", "No permission to edit %s related data" % oprn)))
def get(self): self.response.headers['Content-Type'] = 'application/json' if self.member: moduleDataObj = moduleTypeToClassMap[self.request.get("modType")].query_model({ "id" : self.request.get("id") }) if self.canEdit or moduleDataObj.email == self.member.email: moduleTypeToClassMap[self.request.get("modType")].delete_model({ "id" : self.request.get("id") }) Module.moduleData_deleted({ "id" : self.request.get("modId") }, moduleDataObj) self.response.out.write(json.dumps(response.success("success", {}))) else: self.response.out.write(json.dumps(response.failure("401", "No permission to edit Module Data related data")))
def get_post_perm(self): perm = Permission.query_model({ "oprn" : oprn }) if oprn == "Module" or oprn == "ModuleData": modId = self.request.get("modId") self.canEdit = ModulePermission.can_edit_module(self.member, modId) or (perm and self.member.permission >= perm.permission) or (self.member.permission >= LEADER_PERMISSION) if self.canEdit or (oprn == "ModuleData" and self.request.get("modType") == "member-list"): func(self) elif (perm and self.member.permission >= perm.permission) or (self.member.permission >= LEADER_PERMISSION): func(self) else: self.response.out.write(json.dumps(response.failure("401", "No permission to edit %s related data" % oprn)))
def main(event, context): # Execute scan in dynamodb try: result = dynamodb.call(tableRegion, tableName, "scan") # Return 500 and status failed in case of error except: return response.failure(json.dumps({ "status": "false" })) # Return 200 and items in case of success else: return response.success(json.dumps(result["Items"], cls=DecimalEncoder))
def get(self): self.response.headers['Content-Type'] = 'application/json' if self.member: channelObj = ChannelId.query_model({ "user_id" : self.member.user_id, "extra_param" : self.request.get("extra_param") }) if not channelObj: try: channelObj = ChannelId.create_model({ "user_id" : self.member.user_id, "extra_param" : int(self.request.get("extra_param")) }) self.response.out.write(json.dumps(response.success("success", { "token" : channelObj.token }))) except apiproxy_errors.OverQuotaError, message: self.response.out.write(json.dumps(response.failure("500", message))) else: self.response.out.write(json.dumps(response.success("success", { "token" : channelObj.token })))
def email(event,context): try: body=json.loads(event['body']) text="" for i in body.keys(): text+=i+": "+body[i]+"\n" print(text) send_email(recipient="*****@*****.**",body=text,name=body['fullName']) return success({"message":"E-mail has been sent"}) except Exception as e: print("Error here :",e) return failure(repr(e))
def post(self): self.response.headers['Content-Type'] = 'application/json' if self.member: params = json.loads(self.request.body) params['data']['user_id'] = self.member.user_id params['data']['extra_param'] = int(params['data']['extra_param']) channelObj = ChannelId.query_model(params['data']) if channelObj: channelObj.key.delete() try: channelObj = ChannelId.create_model(params['data']) self.response.out.write(json.dumps(response.success("success", { "token" : channelObj.token }))) except apiproxy_errors.OverQuotaError, message: self.response.out.write(json.dumps(response.failure("500", message)))
def main(event, context): # prepare the key to delete in dynamodb recipe table key = {"recipeId": event["pathParameters"]["id"]} # Execute delete item in dynamodb try: dynamodb.call(tableRegion, tableName, "delete_item", Key=key) # Return 500 and status failed in case of error except: return response.failure(json.dumps({"status": "false"})) # Return 200 in case of success else: return response.success(json.dumps({"status": "true"}))
def main(event, context): # Prepare item to put in db with event data data = json.loads(event["body"]) item = { "recipeId": str(uuid.uuid4()), "content": data["content"], "picture": data["picture"], "createdAt": str(datetime.datetime.now()) } # Execute put item in dynamodb try: dynamodb.call(tableRegion, tableName, "put_item", Item=item) # Return 500 and status failed in case of error except: return response.failure(json.dumps({ "status": "false" })) # Return 200 and added item in case of success else: return response.success(json.dumps(item))
def main(event, context): # Prepare item to update in db with event data data = json.loads(event["body"]) if data.get("picture") is not None and data.get("content") is not None: updateExpression = "SET content = :content, picture = :picture, updatedAt = :updatedAt" expressionAttributeValues = { ":picture": data["picture"], ":content": data["content"], ":updatedAt": str(datetime.datetime.now()), } elif data.get("content") is not None: updateExpression = "SET content = :content, updatedAt = :updatedAt" expressionAttributeValues = { ":content": data["content"], ":updatedAt": str(datetime.datetime.now()), } else: updateExpression = "SET picture = :picture" expressionAttributeValues = { ":picture": data["picture"] } # Execute update item in dynamodb try: dynamodb.call(tableRegion, tableName, "update_item", Key={ "recipeId": event["pathParameters"]["id"] }, UpdateExpression=updateExpression, ExpressionAttributeValues=expressionAttributeValues, ReturnValues="UPDATED_NEW" ) # Return 500 and status failed in case of error except: return response.failure(json.dumps({ "status": "false" })) # Return 200 in case of success else: return response.success(json.dumps({ "status": "true" }))