By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 git_http.py

View raw Download
text/x-script.python • 6.61 kiB
Python script, ASCII text executable
        
            
1
import uuid
2
from models import *
3
from app import app, db, bcrypt
4
from misc_utils import *
5
from common import git_command
6
import os
7
import shutil
8
import config
9
import flask
10
import git
11
import subprocess
12
from flask_httpauth import HTTPBasicAuth
13
import zlib
14
import re
15
import datetime
16
17
auth = HTTPBasicAuth(realm=config.AUTH_REALM)
18
19
auth_required = flask.Response("Unauthorized Access", 401,
20
{"WWW-Authenticate": 'Basic realm="Login Required"'})
21
22
23
@auth.verify_password
24
def verify_password(username, password):
25
user = User.query.filter_by(username=username).first()
26
27
if user and bcrypt.check_password_hash(user.password_hashed, password):
28
flask.g.user = username
29
return True
30
31
return False
32
33
34
def get_commit_identity(identity, logged_in_user):
35
email = identity.rpartition("<")[2].rpartition(">")[0].strip()
36
email_users = db.query(User).filter_by(email=email).all()
37
38
39
@app.route("/<username>/<repository>/git-upload-pack", methods=["POST"])
40
@app.route("/git/<username>/<repository>/git-upload-pack", methods=["POST"])
41
@auth.login_required(optional=True)
42
def git_upload_pack(username, repository):
43
if auth.current_user() is None and not get_visibility(username, repository):
44
return auth_required
45
if not (get_visibility(username, repository) or get_permission_level(flask.g.user, username,
46
repository) is not None):
47
flask.abort(403)
48
49
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
50
text = git_command(server_repo_location, flask.request.data, "upload-pack",
51
"--stateless-rpc", ".")
52
53
return flask.Response(text, content_type="application/x-git-upload-pack-result")
54
55
56
@app.route("/<username>/<repository>/git-receive-pack", methods=["POST"])
57
@app.route("/git/<username>/<repository>/git-receive-pack", methods=["POST"])
58
@auth.login_required
59
def git_receive_pack(username, repository):
60
if not get_permission_level(flask.g.user, username, repository):
61
flask.abort(403)
62
63
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
64
text = git_command(server_repo_location, flask.request.data, "receive-pack",
65
"--stateless-rpc", ".")
66
67
if flask.request.data == b"0000":
68
return flask.Response("", content_type="application/x-git-receive-pack-result")
69
70
push_info = flask.request.data.split(b"\x00")[0].decode()
71
if not push_info:
72
return flask.Response(text, content_type="application/x-git-receive-pack-result")
73
74
old_sha, new_sha, ref = push_info[4:].split() # discard first 4 characters, used for line length which we don't need
75
76
if old_sha == "0" * 40:
77
commits_list = subprocess.check_output(["git", "rev-list", new_sha],
78
cwd=server_repo_location).decode().strip().split("\n")
79
else:
80
commits_list = subprocess.check_output(["git", "rev-list", f"{old_sha}..{new_sha}"],
81
cwd=server_repo_location).decode().strip().split("\n")
82
83
for sha in reversed(commits_list):
84
info = git_command(server_repo_location, None, "show", "-s",
85
"--format='%H%n%at%n%cn <%ce>%n%B'", sha).decode()
86
87
sha, time, identity, body = info.split("\n", 3)
88
login = flask.g.user
89
90
if not Commit.query.filter_by(identifier=f"/{username}/{repository}/{sha}").first():
91
user = User.query.filter_by(username=login).first()
92
repo = Repo.query.filter_by(route=f"/{username}/{repository}").first()
93
94
commit = Commit(sha, user, repo, time, body, identity)
95
96
db.session.add(commit)
97
db.session.commit()
98
99
if ref.startswith("refs/heads/"): # if the push is to a branch
100
ref = ref.rpartition("/")[2] # get the branch name only
101
repo_data = db.session.get(Repo, f"/{username}/{repository}")
102
if ref == repo_data.site_branch:
103
# Update the site
104
from celery_tasks import copy_site
105
copy_site.delay(repo_data.route)
106
107
return flask.Response(text, content_type="application/x-git-receive-pack-result")
108
109
110
@app.route("/<username>/<repository>/info/refs", methods=["GET", "POST"])
111
@app.route("/git/<username>/<repository>/info/refs", methods=["GET", "POST"])
112
@auth.login_required(optional=True)
113
def git_info_refs(username, repository):
114
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
115
116
repo = git.Repo(server_repo_location)
117
repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first()
118
if not repo_data.default_branch:
119
if repo.heads:
120
repo_data.default_branch = repo.heads[0].name
121
repo.git.checkout("-f", repo_data.default_branch)
122
123
if auth.current_user() is None and (
124
not get_visibility(username, repository) or flask.request.args.get(
125
"service") == "git-receive-pack"):
126
return auth_required
127
try:
128
if not (get_visibility(username, repository) or get_permission_level(flask.g.user,
129
username,
130
repository) is not None):
131
flask.abort(403)
132
except AttributeError:
133
return auth_required
134
135
service = flask.request.args.get("service")
136
137
if service.startswith("git"):
138
service = service[4:]
139
else:
140
flask.abort(403)
141
142
if service == "receive-pack":
143
try:
144
if not get_permission_level(flask.g.user, username, repository):
145
flask.abort(403)
146
except AttributeError:
147
return auth_required
148
149
service_line = f"# service=git-{service}\n"
150
service_line = (f"{len(service_line) + 4:04x}" + service_line).encode()
151
152
if service == "upload-pack":
153
text = service_line + b"0000" + git_command(server_repo_location, None, "upload-pack",
154
"--stateless-rpc",
155
"--advertise-refs",
156
"--http-backend-info-refs", ".")
157
elif service == "receive-pack":
158
refs = git_command(server_repo_location, None, "receive-pack",
159
"--http-backend-info-refs", ".")
160
text = service_line + b"0000" + refs
161
else:
162
flask.abort(403)
163
164
response = flask.Response(text, content_type=f"application/x-git-{service}-advertisement")
165
response.headers["Cache-Control"] = "no-cache"
166
167
return response
168