def webhook_delivered(request, webhook_id): print("In webhook_delivered") """ Webhook function to notify user about update in component """ urllib.parse.unquote(request.body.decode("utf-8")) params_dict = urllib.parse.parse_qsl(request.body) params = dict(params_dict) #Extracting necessary data recipient = params[b'recipient'].decode('utf-8') # Fetching yellowant object try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Mail delivered to " + str(recipient) attachment = MessageAttachmentsClass() attachment.title = "Mail Stats upto last 1 month" button_get_components = MessageButtonsClass() button_get_components.name = "1" button_get_components.value = "1" button_get_components.text = "Get all stats" button_get_components.command = { "service_application": service_application, "function_name": 'get_stats', "data": {} } attachment.attach_button(button_get_components) webhook_message.data = {"recipient_email_id": recipient} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="notify_delivered", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def update_incident(request,webhook_id): print("In update_incident") """ Webhook function to notify user about update in incident """ # Extracting necessary data data = (request.body.decode('utf-8')) response_json = json.loads(data) page_id = response_json['page']['id'] unsubscribe = response_json['meta']['unsubscribe'] incident_id = response_json['incident']['id'] name = response_json['incident']['name'] try: # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Updates in incident with Id : " + str(incident_id) + "\nName : " + str(name) attachment = MessageAttachmentsClass() attachment.title = "Incident operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'all_incidents', "data": { 'page_id': page_id } } attachment.attach_button(button_get_incidents) webhook_message.data = {"page_id": page_id} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="incident_updates_webhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def responsewebhook(request, hash_str=""): """Whenever a new response is completed the user gets notified""" try: ya_obj = YellowUserToken.objects.get(webhook_id=hash_str) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403) try: data_obj = json.loads(request.body) print(data_obj) notification_type = data_obj['event_type'] if notification_type == "response_completed": message = MessageClass() message.message_text = "New survey response completed" message.data = data_obj yauser_integration_object = YellowAnt( access_token=ya_obj.yellowant_token) send_message = yauser_integration_object.create_webhook_message(\ requester_application=ya_obj.yellowant_intergration_id, \ webhook_name="response_completed", **message.get_dict()) return HttpResponse("webhook_receiver/webhook_receiver/") except Exception as e: print(str(e)) return HttpResponse("Empty body")
def yellowantRedirecturl(request): print("In yellowantRedirecturl") ''' Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. ''' # Oauth2 code from YA, passed as GET params in the url code = request.GET.get('code') # The unique string to identify the user for which we will create an integration state = request.GET.get("state") # Fetch user with help of state from database yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user # Initialize the YA SDK client with your application credentials y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) # Getting the acccess token access_token_dict = y.get_access_token(code) print(access_token_dict) access_token = access_token_dict['access_token'] # Getting YA user details yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() # Creating a new user integration for the application user_integration = yellowant_user.create_user_integration() hash_str = str(uuid.uuid4()).replace("-", "")[:25] ut = YellowUserToken.objects.create(user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration\ ["user_invoke_name"], yellowant_integration_id=user_integration\ ['user_application'], webhook_id=hash_str) state = str(uuid.uuid4()) AppRedirectState.objects.create(user_integration=ut, state=state) url = "https://www.dropbox.com/oauth2/authorize/" params = { 'response_type': 'code','client_id': settings.DROPBOX_CLIENT_ID, 'redirect_uri': settings.DROPBOX_REDIRECT_URL, 'state': state} url += '?' + urllib.parse.urlencode(params) return HttpResponseRedirect(url)
def add_new_pipeline(request, webhook_id): """ Webhook function to notify user about newly added pipeline """ data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json["current"]['name'] add_time = data_json["current"]['add_time'] url_tile = data_json["current"]['url_title'] order = data_json["current"]['order_nr'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New pipeline created." + "\n" + "The pipeline name : " + str( name) attachment = MessageAttachmentsClass() button_get_pipeline = MessageButtonsClass() button_get_pipeline.name = "1" button_get_pipeline.value = "1" button_get_pipeline.text = "Get all pipelines" button_get_pipeline.command = { "service_application": service_application, "function_name": 'list_pipelines', "data": { 'data': "test", } } attachment.attach_button(button_get_pipeline) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Add Time": add_time, "Url title": url_tile, "Name": name, "Order": order, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_pipeline", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def run(self): """Method which runs when the thread is started""" global GROUP_NAME, VM_NAME, USERNAME, PASSWORD message = MessageClass() credentials, subscription_id = get_credentials(self.user_integration) compute_client = ComputeManagementClient(credentials, subscription_id) network_client = NetworkManagementClient(credentials, subscription_id) GROUP_NAME = self.args.get("Resource-Group") VM_NAME = self.args.get("VM-Name") NIC_NAME = self.args.get("nic_name") IP_CONFIG_NAME = self.args.get("ipconfig_name") USERNAME = self.args.get("username") PASSWORD = self.args.get("password") VNET_NAME = self.args.get("vnet_name") SUBNET_NAME = self.args.get("subnet_name") LOCATION = self.args.get("location") try: # Create a NIC nic = create_nic(network_client, VNET_NAME, SUBNET_NAME, IP_CONFIG_NAME, NIC_NAME) ############# # VM Sample # ############# # Create Linux VM print('\nCreating Linux Virtual Machine') vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE['linux'], VM_NAME, USERNAME, PASSWORD, LOCATION) async_vm_creation = compute_client.virtual_machines.create_or_update( GROUP_NAME, VM_NAME, vm_parameters) # async_vm_creation.wait() message.message_text = "You are Virtual Machine is being created" except CloudError: print('A VM operation failed:', traceback.format_exc(), sep='\n') message.message_text = "There was an error.Please try again" else: webhook_message = MessageClass() webhook_message.message_text = "VM created successfully" attachment = MessageAttachmentsClass() attachment.title = VM_NAME webhook_message.attach(attachment) yellowant_user_integration_object = YellowAnt( access_token=self.user_integration.yellowant_integration_token) yellowant_user_integration_object.create_webhook_message( requester_application=self.user_integration. yellowant_integration_id, webhook_name="start_vm_webhook", **webhook_message.get_dict()) print('All example operations completed successfully!')
def yellowantRedirectUrl(request): code = request.GET.get("code", False) # code = "64HDykUcK2SQPJd0VLansK9tLHvEvJ" if code is False: return HttpResponse("Invalid Response") else: y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) print(y) access_token_dict = y.get_access_token(code) print(access_token_dict) access_token = access_token_dict['access_token'] print(access_token) user_yellowant_object = YellowAnt(access_token=access_token) profile = user_yellowant_object.get_user_profile() yellowant_user = YellowAnt(access_token=access_token) user_integration = yellowant_user.create_user_integration() # print(user) print(user_integration) ut = UserToken.objects.create( yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_id=user_integration['user_application']) return HttpResponse("User Authenticated")
def incident_resolved(request, webhook_id): # data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json['display_name'] entity_id = data_json['entity_id'] incident_number = data_json['incident_number'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Incident Resolved\n The entity ID : " + str(entity_id) \ + "\nThe Incident Number : " + str(incident_number) attachment = MessageAttachmentsClass() attachment.title = "Incident Operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'list_incidents', "data": { 'data': "test", } } attachment.attach_button(button_get_incidents) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Display Name": name, "Entity ID": entity_id, "Incident Number": incident_number, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_incident_resolved", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def accept(args,user_integration): """ Function to accept the invitation from another player. """ opponent_user_integration = args.get("user_int") state = str(uuid.uuid4()) opponent_object = UserIntegration.objects.get(yellowant_integration_id=opponent_user_integration) opponent_object.playing_state = state player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id) player_object.playing_state = state player_object.opponent_integration_id = opponent_object.yellowant_integration_id opponent_object.opponent_integration_id = player_object.yellowant_integration_id player_object.board_state = INITIAL_BOARD + INITIAL_BOARD_REST opponent_object.board_state = INITIAL_BOARD + INITIAL_BOARD_REST player_object.save() opponent_object.save() webhook_message = MessageClass() webhook_message.message_text = "Chess Invite" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Your Chess Invite has been accepted by" field1.value = player_object.yellowant_team_subdomain button = MessageButtonsClass() button.text = "Start Game" button.value = "Start Game" button.name = "Start Game" button.command = { "service_application" : str(opponent_object.yellowant_integration_id), "function_name" : "startgameplayer", "data" : {"user_int": player_object.yellowant_integration_id}, "inputs" : ["Color"] } attachment.attach_button(button) attachment.attach_field(field1) webhook_message.attach(attachment) access_token = opponent_object.yellowant_integration_token yellowant_user_integration_object = YellowAnt(access_token=access_token) send_message = yellowant_user_integration_object.create_webhook_message( requester_application=opponent_object.yellowant_integration_id, webhook_name="webhook", **webhook_message.get_dict()) m = MessageClass() return m
def add_new_invoice(request, id): """ Webhook function to notify user about newly created invoice """ print(request.body) invoice_id = request.POST['ID'] contact_email = request.POST['Email'] total = request.POST['Total'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id # service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New invoice added" attachment = MessageAttachmentsClass() field = AttachmentFieldsClass() field.title = "Invoice ID" field.value = invoice_id attachment.attach_field(field) field1 = AttachmentFieldsClass() field1.title = "Total" field1.value = total attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Contact Email" field2.value = contact_email attachment.attach_field(field2) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Invoice ID": invoice_id, "Total": total, "Contact Email": contact_email, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_invoice", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def delete_integration(request, id=None): """Function to delete an integration.""" print("In delete_integration") #print(id) access_token_dict = UserIntegration.objects.get(id=id) access_token = access_token_dict.yellowant_integration_token user_integration_id = access_token_dict.yellowant_integration_id #print(user_integration_id) #"https://api.yellowant.com/api/user/integration/%s" % (user_integration_id) yellowant_user = YellowAnt(access_token=access_token) yellowant_user.delete_user_integration(id=user_integration_id) UserIntegration.objects.get(yellowant_integration_token=access_token).delete() #print(response_json) return HttpResponse("successResponse", status=200)
def view_integration(request, id=None): """ Function to View an integration when it is clicked. """ print("In view_integration") #print(id) access_token_dict = UserIntegration.objects.get(id=id) access_token = access_token_dict.yellowant_integration_token user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % (user_integration_id) yellowant_user = YellowAnt(access_token=access_token) yellowant_user.delete_user_integration(id=user_integration_id) #print(response_json) return HttpResponse("successResponse", status=200)
def delete_integration(request, id=None): # Function for deleting an integration by taking the id as input. print(id) access_token_dict = UserIntegration.objects.get(id=id) user_id = access_token_dict.user if user_id == request.user.id: access_token = access_token_dict.yellowant_integration_token user_integration_id = access_token_dict.yellowant_integration_id url = "https://api.yellowant.com/api/user/integration/%s" % (user_integration_id) yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.delete_user_integration(id=user_integration_id) response_json = UserIntegration.objects.get(yellowant_integration_token=access_token).delete() return HttpResponse("successResponse", status=204) else: return HttpResponse("Not Authenticated", status=403)
def employee_created(request, id): print('Inside employee created') name = request.POST['name'] contact_id = request.POST['id'] last_name = request.POST['last_name'] email = request.POST['email'] yellow_obj = UserIntegration.objects.get(webhook_id=id) access_token = yellow_obj.yellowant_integration_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New Employee added" attachment = MessageAttachmentsClass() field = AttachmentFieldsClass() field.title = "Name" field.value = name + " " + last_name attachment.attach_field(field) field1 = AttachmentFieldsClass() field1.title = "Email ID" field1.value = email attachment.attach_field(field1) # print(integration_id) webhook_message.data = { "Name": name, "ID": contact_id, "Email": email, "LastName": last_name } webhook_message.attach(attachment) # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=service_application, webhook_name="createemployeewebhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def user_detail_update_delete_view(request, id=None): print("In user_detail_update_delete_view") """ delete_integration function deletes the particular integration """ print("In user_detail_update_delete_view") print(id) user_integration_id = id # # if request.method == "GET": # pass # return HttpResponse(json.dumps({"ok" : True,"is_valid" : False})) if request.method == "DELETE": print("Deleting integration") access_token_dict = YellowUserToken.objects.get(id=id) user_id = access_token_dict.user if user_id == request.user.id: access_token = access_token_dict.yellowant_token print(access_token) user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % ( user_integration_id) yellowant_user = YellowAnt(access_token=access_token) print(yellowant_user) yellowant_user.delete_user_integration(id=user_integration_id) response = YellowUserToken.objects.get( yellowant_token=access_token).delete() print(response) return HttpResponse("successResponse", status=200) else: return HttpResponse("Not Authenticated", status=403) elif request.method == "POST": print("In submitting data") data = json.loads(request.body.decode("utf-8")) print(data) user_integration = data['user_integration'] qut_object = QuickbookUserToken.objects.get( user_integration_id=user_integration) qut_object.login_update_flag = True qut_object.save() return HttpResponse(json.dumps({"ok": True, "is_valid": True}))
def redirect_url(request): #YellowAnt redirects to this view with code and state values code = request.GET.get("code", False) #state = request.GET.get("state", False) #Exchange code with permanent token y = YellowAnt(app_key=settings.YA_CLIENT_ID, app_secret=settings.YA_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) access_token_dict = y.get_access_token(code) access_token = access_token_dict['access_token'] #List of emails of users allowed access to this application users_allowed_emails = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] #Using token to fetch user details x = YellowAnt(access_token=access_token) profile = x.get_user_profile() if profile['email'] in users_allowed_emails: q = x.create_user_integration() user_application = q['user_application'] ti = AdminUsers.objects.create( yellowant_user_id=profile['id'], yellowant_integration_id=user_application, yellowant_integration_user_invoke_name=q['user_invoke_name'], yellowant_user_token=access_token) return HttpResponse("You are now authenticated!") else: return HttpResponse("You are not allowed to access this application!")
def yellowantredirecturl(request): # The code is extracted from request URL and it is used to get access token json. # The YA_REDIRECT_URL point to this function only code = request.GET.get('code') state = request.GET.get("state") yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user print(settings.YA_REDIRECT_URL) y = YellowAnt(app_key=settings.YA_CLIENT_ID, app_secret=settings.YA_CLIENT_SECRET, access_token=None, redirect_uri=settings.YA_REDIRECT_URL) access_token_dict = y.get_access_token(code) print(access_token_dict) access_token = access_token_dict['access_token'] yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() user_integration = yellowant_user.create_user_integration() ut = YellowUserToken.objects.create( user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration["user_invoke_name"], yellowant_integration_id=user_integration['user_application']) return HttpResponseRedirect(settings.SITE_PROTOCOL + f"{yellowant_redirect_state.subdomain}." + settings.SITE_DOMAIN_URL + settings.BASE_HREF + f"integrate_app?id={ut.id}")
def yellowant_oauth_redirect(request): """Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. """ # oauth2 code from YA, passed as GET params in the url code = request.GET.get("code") # the unique string to identify the user for which we will create an integration state = request.GET.get("state") # fetch user with the help of state yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user # initialize the YA SDK client with your application credentials ya_client = YellowAnt(app_key=settings.YA_CLIENT_ID, app_secret=settings.YA_CLIENT_SECRET, access_token=None, redirect_uri=settings.YA_REDIRECT_URL) # get the access token for a user integration from YA against the code access_token_dict = ya_client.get_access_token(code) access_token = access_token_dict["access_token"] # reinitialize the YA SDK client with the user integration access token ya_client = YellowAnt(access_token=access_token) # get YA user details ya_user = ya_client.get_user_profile() # create a new user integration for your application user_integration = ya_client.create_user_integration() # save the YA user integration details in your database ut = UserIntegration.objects.create( user=user, yellowant_user_id=ya_user["id"], yellowant_team_subdomain=ya_user["team"]["domain_name"], yellowant_integration_id=user_integration["user_application"], yellowant_integration_invoke_name=user_integration["user_invoke_name"], yellowant_integration_token=access_token) aws.objects.create(id=ut, AWS_APIAccessKey="", AWS_APISecretAccess="") # A new YA user integration has been created and the details have been successfully # saved in your application's database. However, we have only created an integration on YA. # As a developer, you need to begin an authentication process for the actual application, # whose API this application is connecting to. Once, the authentication process # for the actual application is completed with the user, you need to create a db # entry which relates the YA user integration, we just created, with the actual application # authentication details of the user. This application will then be able to identify # the actual application accounts corresponding to each YA user integration. # return HttpResponseRedirect("to the actual application authentication URL") # return HttpResponseRedirect(reverse("accounts/"), kwargs={"id":ut}) return HttpResponseRedirect("/")
def webhooks(request, id=None): #print(request.post.data) # print(type(request)) # print((request.body)) try: body = json.loads(json.dumps((request.body.decode("utf-8")))) # print("Body is") # print(body) # print(json.loads(body)) body = json.loads(body) except: return HttpResponse("Failed", status=404) # print(body['sys_id']) User = UserIntegration.objects.get(webhook_id=id) service_application = str(User.yellowant_integration_id) access_token = User.yellowant_integration_token ####### STARTING WEB HOOK PART webhook_message = MessageClass() webhook_message.message_text = "Incident" + " " + body['state'] attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Name" field1.value = body['number'] attachment.attach_field(field1) webhook_message.attach(attachment) attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Description" field1.value = body['description'] attachment.attach_field(field1) webhook_message.attach(attachment) # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=User.yellowant_integration_id, webhook_name="webhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def yellowantRedirectUrl(request): code = request.GET.get("code", False) if code is False: return HttpResponse("Invalid Response") else: y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) access_token_dict = y.get_access_token(code) access_token = access_token_dict['access_token'] yellowant_user = YellowAnt(access_token=access_token) user_integration = yellowant_user.create_user_integration() profile = yellowant_user.get_user_profile() print(request.user) global screen_name ut = UserToken.objects.create( screen_name=screen_name, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_id=user_integration['user_application']) return HttpResponse("User is authenticated!!!")
def delete_integration(request, integrationId=None): print("In delete_integration") print(integrationId) access_token_dict = YellowUserToken.objects.get(id=integrationId) access_token = access_token_dict.yellowant_token user_integration_id = access_token_dict.yellowant_intergration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % ( user_integration_id) yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.delete_user_integration(id=user_integration_id) response_json = YellowUserToken.objects.get( yellowant_token=access_token).delete() print(response_json) return HttpResponse("successResponse", status=204)
def yellowantRedirecturl(request): print("In yellowantRedirecturl") ''' Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. ''' # Oauth2 code from YA, passed as GET params in the url code = request.GET.get('code') # The unique string to identify the user for which we will create an integration state = request.GET.get("state") # Fetch user with help of state from database yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user # Initialize the YA SDK client with your application credentials y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) # Getting the acccess token access_token_dict = y.get_access_token(code) print(access_token_dict) access_token = access_token_dict['access_token'] # Getting YA user details yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() # Creating a new user integration for the application user_integration = yellowant_user.create_user_integration() hash_str = str(uuid.uuid4()).replace("-", "")[:25] ut = YellowUserToken.objects.create(user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration\ ["user_invoke_name"], yellowant_integration_id=user_integration\ ['user_application'], webhook_id=hash_str) state = str(uuid.uuid4()) AppRedirectState.objects.create(user_integration=ut, state=state) url = "https://www.dropbox.com/oauth2/authorize/" params = { 'response_type': 'code', 'client_id': settings.DROPBOX_CLIENT_ID, 'redirect_uri': settings.DROPBOX_REDIRECT_URL, 'state': state } url += '?' + urllib.parse.urlencode(params) return HttpResponseRedirect(url)
def yellowant_redirecturl(request): """Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. """ print("In yellowant_redirecturl") code = request.GET.get('code') state = request.GET.get("state") yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) print(code) print(yellowant_redirect_state) user = yellowant_redirect_state.user print(settings.YELLOWANT_REDIRECT_URL) # initialize the YA SDK client with your application credentials print(user) ya_client = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) access_token_dict = ya_client.get_access_token(code) print(access_token_dict) access_token = access_token_dict['access_token'] yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() user_integration = yellowant_user.create_user_integration() hash_str = str(uuid.uuid4()).replace("-", "")[:25] # save the YA user integration details in your database ut = YellowUserToken.objects.create( user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration["user_invoke_name"], yellowant_integration_id=user_integration['user_application'], webhook_id=hash_str) """A new YA user integration has been created and the details have been successfully saved in your application's database. However, we have only created an integration on YA. As a developer, you need to begin an authentication process for the actual application, whose API this application is connecting to. Once, the authentication process for the actual application is completed with the user, you need to create a db entry which relates the YA user integration, we just created, with the actual application authentication details of the user. This application will then be able to identify the actual application accounts corresponding\ to each YA user integration.""" #pylint: disable=pointless-string-statement print("exiting yellowant_redirecturl") return HttpResponseRedirect(settings.SITE_PROTOCOL + f"{yellowant_redirect_state.subdomain}." + settings.SITE_DOMAIN_URL + settings.BASE_HREF + f"integrate_app?id={ut.id}")
def yellowantRedirecturl(request): ''' Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. ''' # Oauth2 code from YA, passed as GET params in the url code = request.GET.get('code') # The unique string to identify the user for which we will create an integration state = request.GET.get("state") # Fetch user with help of state from database yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user # Initialize the YA SDK client with your application credentials y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) print(settings.YELLOWANT_REDIRECT_URL) # Getting the acccess token access_token_dict = y.get_access_token(code) access_token = access_token_dict['access_token'] # Getting YA user details yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() # Creating a new user integration for the application user_integration = yellowant_user.create_user_integration() hash_str = str(uuid.uuid4()).replace("-", "")[:25] ut = YellowUserToken.objects.create(user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration\ ["user_invoke_name"], yellowant_integration_id=user_integration\ ['user_application'], webhook_id=hash_str) state = str(uuid.uuid4()) AppRedirectState.objects.create(user_integration=ut, state=state) sp_token = "" # "11649b9b-ea84-47fa-aecb-9faf3ab447bd" page_id = "" sut = StatuspageUserToken.objects.create(user_integration=ut, statuspage_access_token=sp_token, webhook_id=hash_str) #print("------------------") #print(sut.user_integration_id) ''' No need to create a page detail object here ''' #page_detail_object = PageDetail.objects.create(user_integration_id=sut.user_integration_id, page_id=page_id) #print(page_detail_object) # Redirecting to home page return HttpResponseRedirect("/")
def delete_integration(request, integrationId=None): print("In delete_integration") print(integrationId) access_token_dict = YellowUserToken.objects.get(id=integrationId) user_id = access_token_dict.user if user_id == request.user.id: access_token = access_token_dict.yellowant_token user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) yellowant_user = YellowAnt(access_token=access_token) yellowant_user.delete_user_integration(id=user_integration_id) response_json = YellowUserToken.objects.get( yellowant_token=access_token).delete() print(response_json) return HttpResponse("successResponse", status=204) else: return HttpResponse("Not Authenticated", status=403)
def yellowantRedirecturl(request): ''' Receive the oauth2 code from YA to generate a new user integration This method calls utilizes the YA Python SDK to create a new user integration on YA. This method only provides the code for creating a new user integration on YA. Beyond that, you might need to authenticate the user on the actual application (whose APIs this application will be calling) and store a relation between these user auth details and the YA user integration. ''' # Oauth2 code from YA, passed as GET params in the url code = request.GET.get('code') # The unique string to identify the user for which we will create an integration state = request.GET.get("state") # Fetch user with help of state from database yellowant_redirect_state = YellowAntRedirectState.objects.get(state=state) user = yellowant_redirect_state.user # Initialize the YA SDK client with your application credentials y = YellowAnt(app_key=settings.YELLOWANT_CLIENT_ID, app_secret=settings.YELLOWANT_CLIENT_SECRET, access_token=None, redirect_uri=settings.YELLOWANT_REDIRECT_URL) print(settings.YELLOWANT_REDIRECT_URL) # Getting the acccess token access_token_dict = y.get_access_token(code) access_token = access_token_dict['access_token'] # Getting YA user details yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.get_user_profile() # Creating a new user integration for the application user_integration = yellowant_user.create_user_integration() hash_str = str(uuid.uuid4()).replace("-", "")[:25] ut = YellowUserToken.objects.create(user=user, yellowant_token=access_token, yellowant_id=profile['id'], yellowant_integration_invoke_name=user_integration\ ["user_invoke_name"], yellowant_integration_id=user_integration\ ['user_application'], webhook_id=hash_str) ## Initially the mailgun object contians no access token so kept empty ## On submiting API key it is updated mail_gun_token = "" mail_object = MailGunUserToken.objects.create(user_integration=ut, accessToken=mail_gun_token, webhook_id=hash_str) url = settings.BASE_URL + "/webhook/" + ut.webhook_id + "/" print(url) return HttpResponseRedirect("/")
def playAgainst(args,user_integration): """ Function which sends the invite to other players to play chess. """ opponent_id = args.get("yellowant_user_id") opponent_object = UserIntegration.objects.get(yellowant_integration_id=opponent_id) player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id) webhook_message = MessageClass() webhook_message.message_text = "Chess Invite" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "You have been invited to play chess with " field1.value = player_object.yellowant_team_subdomain button = MessageButtonsClass() button.text = "Accept Invitation" button.value = "Accept Invitation" button.name = "Accept Invitation" button.command = { "service_application": str(opponent_object.yellowant_integration_id), "function_name": "accept", "data": {"user_int": player_object.yellowant_integration_id } } attachment.attach_button(button) attachment.attach_field(field1) webhook_message.attach(attachment) access_token = opponent_object.yellowant_integration_token yellowant_user_integration_object = YellowAnt(access_token=access_token) print("Printing webhook") send_message = yellowant_user_integration_object.create_webhook_message( requester_application=opponent_object.yellowant_integration_id, webhook_name="webhook", **webhook_message.get_dict()) m = MessageClass() m.message_text = "Waiting for response from opponent" return m
def delete_integration(request, id=None): print("In delete_integration") print(id) print("user is ", request.user.id) access_token_dict = UserIntegration.objects.get(id=id) user_id = access_token_dict.user if user_id == request.user.id: access_token = access_token_dict.yellowant_integration_token user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % ( user_integration_id) yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.delete_user_integration( id=user_integration_id) response_json = UserIntegration.objects.get( yellowant_integration_token=access_token).delete() print(response_json) return HttpResponse("successResponse", status=204) else: return HttpResponse("Not Authenticated", status=403)
def user_detail_update_delete_view(request, id=None): """ delete_integration function deletes the particular integration """ #print("In user_detail_update_delete_view") #print(id) user_integration_id = id if request.method == "GET": pass # return user data # smut = DropBoxUserToken.objects.get(user_integration=user_integration_id) # return HttpResponse(json.dumps({ # "is_valid": True # })) elif request.method == "DELETE": print("Deleting integration") access_token_dict = YellowUserToken.objects.get(id=id) user_id = access_token_dict.user if user_id == request.user.id: access_token = access_token_dict.yellowant_token print(access_token) user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % (user_integration_id) yellowant_user = YellowAnt(access_token=access_token) print(yellowant_user) yellowant_user.delete_user_integration(id=user_integration_id) response = YellowUserToken.objects.get(yellowant_token=access_token).delete() print(response) return HttpResponse("successResponse", status=200) else: return HttpResponse("Not Authenticated", status=403) elif request.method == "PUT": pass
def delete_integration(request, id=None): """ Function for deleting an integration by taking the id as input.""" # print(request.user.id) # access_token_dict = UserIntegration.objects.get(id=id) # access_token = access_token_dict.yellowant_integration_token # user_integration_id = access_token_dict.yellowant_integration_id # print(user_integration_id) # url = "https://api.yellowant.com/api/user/integration/%s" % (user_integration_id) # yellowant_user = YellowAnt(access_token=access_token) # # # deletes all the data related to that integration # yellowant_user.delete_user_integration(id=user_integration_id) # response_json = UserIntegration.objects.get(yellowant_integration_token=access_token).delete() # return HttpResponse("successResponse", status=200) print("In delete_integration") print(id) print("user is ", request.user.id) access_token_dict = UserIntegration.objects.get(id=id) #print(access_token_dict.user_id) user_id = access_token_dict.user_id print(request.user.id) print(user_id) if user_id == request.user.id: print("asdfghjk") access_token = access_token_dict.yellowant_integration_token user_integration_id = access_token_dict.yellowant_integration_id # print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % ( user_integration_id) yellowant_user = YellowAnt(access_token=access_token) profile = yellowant_user.delete_user_integration( id=user_integration_id) response_json = UserIntegration.objects.get( yellowant_integration_token=access_token).delete() # print(response_json) return HttpResponse("successResponse", status=204) else: return HttpResponse("Not Authenticated", status=403)
def user_detail_update_delete_view(request, id=None): """ This function handles the updating, deleting and viewing user details """ print("In user_detail_update_delete_view") print(id) user_integration_id = id # if request.method == "GET": # # return user data # print("in get") # pdut = ZohoInvoiceUserToken.objects.get(user_integration=user_integration_id) # return HttpResponse(json.dumps({ # "is_valid": pdut.apikey_login_update_flag # })) if request.method == "DELETE": # deletes the integration print("In delete_integration") # print(id)this is a test subject # print("user is ", request.user.id) access_token_dict = YellowUserToken.objects.get(id=id) user_id = access_token_dict.user # print("id is ", user_id) if user_id == request.user.id: access_token = access_token_dict.yellowant_token user_integration_id = access_token_dict.yellowant_integration_id print(user_integration_id) url = "https://api.yellowant.com/api/user/integration/%s" % ( user_integration_id) yellowant_user = YellowAnt(access_token=access_token) yellowant_user.delete_user_integration(id=user_integration_id) response_json = YellowUserToken.objects.get( yellowant_token=access_token).delete() print(response_json) return HttpResponse("successResponse", status=204) else: return HttpResponse("Not Authenticated", status=403)
def webhook(request, hash_str=""): '''Respond to the webhook verification (GET request) by echoing back the challenge parameter.''' print("Inside webhook") if request.method == "GET": print("Inside webhook validation") challenge = request.GET.get('challenge',None) if challenge != None: return HttpResponse(challenge,status=200) else: return HttpResponse(status=400) else: print("In notifications") webhook_id = hash_str data = (request.body.decode('utf-8')) response_json = json.loads(data) print(response_json) data = { "users": [], "accounts": [] } try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "File/Folder updated !" attachment = MessageAttachmentsClass() attachment.title = "Updated file/folder details :" for i in range(0,len(response_json['list_folder']['accounts'])): field1 = AttachmentFieldsClass() field1.title = "Id : " field1.value = response_json['list_folder']['accounts'][i] data["accounts"].append(response_json['list_folder']['accounts'][i]) attachment.attach_field(field1) attachment2 = MessageAttachmentsClass() attachment2.title = "User update details :" for i in range(0, len(response_json['delta']['users'])): field2 = AttachmentFieldsClass() field2.title = "Id : " field2.value = response_json['delta']['users'][i] data["users"].append(response_json['delta']['users'][i]) attachment2.attach_field(field2) button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get all files and folders " button.command = { "service_application": service_application, "function_name": 'get_all_folders', "data" : {"path": "", "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} } attachment.attach_button(button) webhook_message.attach(attachment) webhook_message.attach(attachment2) #print(integration_id) print("-----------") print(data) print("------------") webhook_message.data = data # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="files_folders_update", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)