api.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
  2. # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
  3. # Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as
  6. # published by the Free Software Foundation, either version 3 of the
  7. # License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. from django.conf import settings
  17. from ipware.ip import get_ip
  18. from taiga.base.utils import json
  19. from taiga.projects.models import Project
  20. from taiga.hooks.api import BaseWebhookApiViewSet
  21. from . import event_hooks
  22. class GitLabViewSet(BaseWebhookApiViewSet):
  23. event_hook_classes = {
  24. "push": event_hooks.PushEventHook,
  25. "issue": event_hooks.IssuesEventHook,
  26. "note": event_hooks.IssueCommentEventHook,
  27. }
  28. def _validate_signature(self, project, request):
  29. secret_key = request.GET.get("key", None)
  30. if secret_key is None:
  31. return False
  32. if not hasattr(project, "modules_config"):
  33. return False
  34. if project.modules_config.config is None:
  35. return False
  36. project_secret = project.modules_config.config.get("gitlab", {}).get("secret", "")
  37. if not project_secret:
  38. return False
  39. gitlab_config = project.modules_config.config.get("gitlab", {})
  40. valid_origin_ips = gitlab_config.get("valid_origin_ips", settings.GITLAB_VALID_ORIGIN_IPS)
  41. origin_ip = get_ip(request)
  42. if valid_origin_ips and (not origin_ip or origin_ip not in valid_origin_ips):
  43. return False
  44. return project_secret == secret_key
  45. def _get_project(self, request):
  46. project_id = request.GET.get("project", None)
  47. try:
  48. project = Project.objects.get(id=project_id)
  49. return project
  50. except Project.DoesNotExist:
  51. return None
  52. def _get_event_name(self, request):
  53. payload = json.loads(request.body.decode("utf-8"))
  54. return payload.get('object_kind', 'push')