Prevent multiple webhooks from being created

This commit is contained in:
rubenwardy 2020-01-25 01:53:02 +00:00
parent 62b1cae0ab
commit d5541791b6

@ -194,8 +194,21 @@ def setup_webhook():
if event != "push" and event != "create": if event != "push" and event != "create":
abort(500) abort(500)
# Create webhook if handleMakeWebhook(gh_user, gh_repo, package, \
current_user.github_access_token, event, token):
return redirect(package.getDetailsURL())
else:
return redirect(url_for("github.setup_webhook", pid=package.id))
return render_template("github/setup_webhook.html", \
form=form, package=package)
def handleMakeWebhook(gh_user, gh_repo, package, oauth, event, token):
url = "https://api.github.com/repos/{}/{}/hooks".format(gh_user, gh_repo) url = "https://api.github.com/repos/{}/{}/hooks".format(gh_user, gh_repo)
headers = {
"Authorization": "token " + oauth
}
data = { data = {
"name": "web", "name": "web",
"active": True, "active": True,
@ -207,26 +220,43 @@ def setup_webhook():
}, },
} }
headers = { # First check that the webhook doesn't already exist
"Authorization": "token " + current_user.github_access_token r = requests.get(url, headers=headers)
}
if r.status_code == 401 or r.status_code == 403:
current_user.github_access_token = None
db.session.commit()
return False
if r.status_code != 200:
flash("Failed to create webhook, received response from Github " +
str(r.status_code) + ": " +
str(r.json().get("message")), "danger")
return False
for hook in r.json():
if hook["config"]["url"] == data["config"]["url"]:
flash("Failed to create webhook, as it already exists", "danger")
return False
# Create it
r = requests.post(url, headers=headers, data=json.dumps(data)) r = requests.post(url, headers=headers, data=json.dumps(data))
if r.status_code == 201: if r.status_code == 201:
db.session.add(token) db.session.add(token)
db.session.commit() db.session.commit()
return redirect(package.getDetailsURL()) return True
elif r.status_code == 401 or r.status_code == 403: elif r.status_code == 401 or r.status_code == 403:
current_user.github_access_token = None current_user.github_access_token = None
db.session.commit() db.session.commit()
return github.authorize("write:repo_hook", \ return False
redirect_uri=url_for("github.callback_webhook", pid=pid, _external=True))
else: else:
flash("Failed to create webhook, received response from Github " + flash("Failed to create webhook, received response from Github " +
str(r.status_code) + ": " + str(r.status_code) + ": " +
str(r.json().get("message")), "danger") str(r.json().get("message")), "danger")
return False
return render_template("github/setup_webhook.html", \
form=form, package=package)