contentdb/app/blueprints/gitlab/__init__.py

76 lines
2.2 KiB
Python
Raw Normal View History

2020-01-25 01:44:46 +01:00
# ContentDB
# Copyright (C) 2020 rubenwardy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from flask import Blueprint, request
bp = Blueprint("gitlab", __name__)
from app import csrf
from app.models import Package, APIToken, Permission
from app.blueprints.api.support import error, handleCreateRelease
2020-12-06 05:54:32 +01:00
def webhook_impl():
2020-01-25 01:44:46 +01:00
json = request.json
# Get package
2020-06-03 17:41:06 +02:00
gitlab_url = json["project"]["web_url"].replace("https://", "").replace("http://", "")
package = Package.query.filter(Package.repo.ilike("%{}%".format(gitlab_url))).first()
2020-01-25 01:44:46 +01:00
if package is None:
2020-12-06 05:54:32 +01:00
return error(400,
"Could not find package, did you set the VCS repo in CDB correctly? Expected {}".format(gitlab_url))
2020-01-25 01:44:46 +01:00
# Get all tokens for package
secret = request.headers.get("X-Gitlab-Token")
if secret is None:
return error(403, "Token required")
token = APIToken.query.filter_by(access_token=secret).first()
2020-12-03 21:33:57 +01:00
if token is None:
2020-01-25 01:44:46 +01:00
return error(403, "Invalid authentication")
if not package.checkPerm(token.owner, Permission.APPROVE_RELEASE):
return error(403, "You do not have the permission to approve releases")
2020-01-25 01:44:46 +01:00
#
# Check event
#
event = json["event_name"]
if event == "push":
ref = json["after"]
title = ref[:5]
2020-01-25 02:14:01 +01:00
elif event == "tag_push":
ref = json["ref"]
title = ref.replace("refs/tags/", "")
2020-01-25 01:44:46 +01:00
else:
2020-01-25 02:14:01 +01:00
return error(400, "Unsupported event. Only 'push' and 'tag_push' are supported.")
2020-01-25 01:44:46 +01:00
#
# Perform release
#
return handleCreateRelease(token, package, title, ref)
2020-12-06 05:54:32 +01:00
@bp.route("/gitlab/webhook/", methods=["POST"])
@csrf.exempt
def webhook():
try:
return webhook_impl()
except KeyError as err:
return error(400, "Missing field: {}".format(err.args[0]))