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

 gitHTTP.py

View raw Download
text/x-script.python • 4.72 kiB
Python script, ASCII text executable
        
            
1
import uuid
2
3
from models import *
4
from app import app, gitCommand, getPermissionLevel, getVisibility, db, bcrypt
5
import os
6
import shutil
7
import config
8
import flask
9
import git
10
import subprocess
11
from flask_httpauth import HTTPBasicAuth
12
import zlib
13
import re
14
import datetime
15
16
auth = HTTPBasicAuth(realm=config.AUTH_REALM)
17
18
19
authRequired = flask.Response("Unauthorized Access", 401, {"WWW-Authenticate": 'Basic realm="Login Required"'})
20
21
22
@auth.verify_password
23
def verifyPassword(username, password):
24
user = User.query.filter_by(username=username).first()
25
26
if user and bcrypt.check_password_hash(user.passwordHashed, password):
27
flask.g.user = username
28
return True
29
30
return False
31
32
33
@app.route("/<username>/<repository>/git-upload-pack", methods=["POST"])
34
@app.route("/git/<username>/<repository>/git-upload-pack", methods=["POST"])
35
@auth.login_required(optional=True)
36
def gitUploadPack(username, repository):
37
if auth.current_user() is None and not getVisibility(username, repository):
38
return authRequired
39
if not (getVisibility(username, repository) or getPermissionLevel(flask.g.user, username, repository) is not None):
40
flask.abort(403)
41
42
serverRepoLocation = os.path.join(config.REPOS_PATH, username, repository, ".git")
43
text = gitCommand(serverRepoLocation, flask.request.data, "upload-pack", "--stateless-rpc", ".")
44
45
return flask.Response(text, content_type="application/x-git-upload-pack-result")
46
47
48
@app.route("/<username>/<repository>/git-receive-pack", methods=["POST"])
49
@app.route("/git/<username>/<repository>/git-receive-pack", methods=["POST"])
50
@auth.login_required
51
def gitReceivePack(username, repository):
52
if not getPermissionLevel(flask.g.user, username, repository):
53
flask.abort(403)
54
55
serverRepoLocation = os.path.join(config.REPOS_PATH, username, repository, ".git")
56
text = gitCommand(serverRepoLocation, flask.request.data, "receive-pack", "--stateless-rpc", ".")
57
58
sha = flask.request.data.split(b" ", 2)[1].decode()
59
info = gitCommand(serverRepoLocation, None, "show", "-s", "--format='%H%n%at%n%cn <%ce>%n%B'", sha).decode()
60
61
if re.match("^[0-9a-fA-F]{40}$", info[:40]):
62
print(info.split("\n", 3))
63
sha, time, identity, body = info.split("\n", 3)
64
login = flask.g.user
65
66
if not Commit.query.filter_by(identifier=f"/{username}/{repository}/{sha}").first():
67
user = User.query.filter_by(username=login).first()
68
repo = Repo.query.filter_by(route=f"/{username}/{repository}").first()
69
70
commit = Commit(sha, user, repo, time, body, identity)
71
72
db.session.add(commit)
73
db.session.commit()
74
75
return flask.Response(text, content_type="application/x-git-receive-pack-result")
76
77
78
@app.route("/<username>/<repository>/info/refs", methods=["GET", "POST"])
79
@app.route("/git/<username>/<repository>/info/refs", methods=["GET", "POST"])
80
@auth.login_required(optional=True)
81
def gitInfoRefs(username, repository):
82
serverRepoLocation = os.path.join(config.REPOS_PATH, username, repository, ".git")
83
84
repo = git.Repo(serverRepoLocation)
85
repoData = Repo.query.filter_by(route=f"/{username}/{repository}").first()
86
if not repoData.defaultBranch:
87
if repo.heads:
88
repoData.defaultBranch = repo.heads[0].name
89
repo.git.checkout("-f", repoData.defaultBranch)
90
91
if auth.current_user() is None and (not getVisibility(username, repository) or flask.request.args.get("service") == "git-receive-pack"):
92
return authRequired
93
try:
94
if not (getVisibility(username, repository) or getPermissionLevel(flask.g.user, username, repository) is not None):
95
flask.abort(403)
96
except AttributeError:
97
return authRequired
98
99
service = flask.request.args.get("service")
100
101
if service.startswith("git"):
102
service = service[4:]
103
else:
104
flask.abort(403)
105
106
if service == "receive-pack":
107
try:
108
if not getPermissionLevel(flask.g.user, username, repository):
109
flask.abort(403)
110
except AttributeError:
111
return authRequired
112
113
serviceLine = f"# service=git-{service}\n"
114
serviceLine = (f"{len(serviceLine) + 4:04x}" + serviceLine).encode()
115
116
if service == "upload-pack":
117
text = serviceLine + b"0000" + gitCommand(serverRepoLocation, None, "upload-pack", "--stateless-rpc", "--advertise-refs", "--http-backend-info-refs", ".")
118
elif service == "receive-pack":
119
refs = gitCommand(serverRepoLocation, None, "receive-pack", "--http-backend-info-refs", ".")
120
text = serviceLine + b"0000" + refs
121
else:
122
flask.abort(403)
123
124
response = flask.Response(text, content_type=f"application/x-git-{service}-advertisement")
125
response.headers["Cache-Control"] = "no-cache"
126
127
return response
128
129