python - 如何通过 git pre-receive hook 验证用户身份

标签 python git authentication githooks

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

!/usr/bin/env python

import sys
import fileinput

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

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

如何更改我的预接收代码以对提交用户进行身份验证并验证他们是否已列入白名单以推送到其尝试的分支?我必须对 git 存储库进行哪些更改(如果有)才能使代码正常运行?

最佳答案

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

tree d06734b17feff2faf22bcd7c0fac1587876e601d
parent 524bd5e2fa72e6358a22f28582e094de936c3768
author Xyz <mm@nn.com> 1466782764 +0800
committer Abc <ss@tt.com> 1466782764 +0800

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

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

#!/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

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

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

#!/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

关于python - 如何通过 git pre-receive hook 验证用户身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015205/

相关文章:

Git 与 nfs 共享的实现

git - 在 Windows 上 checkout HEAD(和变体)时奇怪的 Git 行为

asp.net - 静态文件的 IIS 500.0 AuthenticateRequest 错误

java - CAS数据库认证: custom password encoder

python - Python 中的函数求和

git - 如何锁定git repos master分支?

python - scikit 中的 pipeline 和 make_pipeline 有什么区别?

javascript - 在 PouchDB 中记住登录数据

python - 如何在 Flask 中使用 SQLAlchemy-Migrate 和 MySQL 数据库

python - 如何使用 dxfgrabber 或 ezdxf 包从 dxf 文件中查找实体的长度