如何通过 git pre-receive hook 对用户进行身份验证

Con*_*ure 2 python git authentication githooks

我正在寻找pre-receive用 Python编写一个githook。我的理解是没有参数传递到pre-receive脚本中,而是使用标准输入在单独的行中传递每个引用。我已经能够通过以下方式阅读参考更改:

!/usr/bin/env python

import sys
import fileinput

for line in fileinput.input():
    print "pre-receive: Trying to push ref: %s" % line
Run Code Online (Sandbox Code Playgroud)

然而,对于这个钩子,我主要关心的是确保用户推送代码具有正确的权限来推送到他们想要的分支。通过我的研究,我一直无法找到寻找提交者用户凭据的方法。我的目标是将他们的信用与白名单进行比较以授予访问权限。

如何更改我的pre-receive代码以验证提交用户的身份并验证他们是否已列入白名单以推送到他们尝试的分支?如果有的话,我必须对 git 存储库进行哪些更改才能使代码起作用?

Elp*_*Kay 6

从标准输入,我们可以得到<old-value> SP <new-value> SP <ref-name> LF. 使用git cat-file -p $new-valuegit cat-file -p $ref-name在钩子中,我们可以得到这样的信息

tree d06734b17feff2faf22bcd7c0fac1587876e601d
parent 524bd5e2fa72e6358a22f28582e094de936c3768
author Xyz <mm@nn.com> 1466782764 +0800
committer Abc <ss@tt.com> 1466782764 +0800
Run Code Online (Sandbox Code Playgroud)

或者以更直接的方式,我们可以使用git log -1 --pretty=%an $ref-name获取作者,并git log -1 --pretty=%cn $ref-name获取提交者。

所以 bash 中钩子的一部分可能是这样的:

#!/bin/bash

read old new ref
author=$(git log -1 $ref --pretty=%an)
committer=$(git log -1 $ref --pretty=%cn)
echo author:$author
echo committer:$committer
Run Code Online (Sandbox Code Playgroud)

左边的部分是检查作者或提交者是否有权做某事。

我在 python 中实现钩子的版本是

#!/usr/bin/env python

import sys
import fileinput
import commands

for line in fileinput.input():
    print "pre-receive: Trying to push ref: %s" % line
    values = line.split()
    old = values[0]
    new = values[1]
    ref = values[2]
    author = ''
    committer = ''
    status,output = commands.getstatusoutput('git log -1 --pretty=%an {0}'.format(ref))
    if status == 0:
        author = output
    status,output = commands.getstatusoutput('git log -1 --pretty=%cn {0}'.format(ref))
    if status == 0:
        committer = output
Run Code Online (Sandbox Code Playgroud)