1

Is it possible to deny users to push commits to repo with a non corporate email?

for example only *@mycompany.com allowed

DAVID _
  • 617
  • 1
  • 7
  • 16
  • This isn't exactly your question (I'm not going to VTC) but it might help you https://stackoverflow.com/questions/56069549/how-to-reject-git-push-based-on-some-rule – mousetail Jul 26 '22 at 09:39
  • 1
    Note that Git alone can't really help you—anyone can put *anything* in as their email address—but GitHub can, by letting you control who gets to add commits to your repository via GitHub's "protected branches" add-on to Git. – torek Jul 26 '22 at 22:46
  • https://gist.github.com/tripleee/16767aa4137706fd896c is a simple wrapper which I'm using to prevent this. – tripleee Aug 29 '22 at 08:26
  • @tripleee it helpful for local env only but I can't guarantee that every developer will install it correctly. So CI check in this case looks more convenient – DAVID _ Aug 29 '22 at 15:23

1 Answers1

2

I solved it using a custom Github Actions job:

# .github/workflows/check_email.yml
jobs:
  validate_email:
    name: Validate email
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Extract author email
        id: author
        run: |
          git log -2
          echo "::set-output name=EMAIL::$(git show -s --format='%ae' HEAD~0)"
      # TODO: Fail the workflow in future instead of adding comment
      - name: Validate author email
        if: ${{ !endsWith(steps.author.outputs.EMAIL, '@mycompany.com')  }}
        uses: actions/github-script@v6
        env:
          EMAIL: ${{ steps.author.outputs.EMAIL }}
        with:
          script: |
            const { EMAIL } = process.env
            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `⚠️ We detect that you are using a non-corporate email \`${EMAIL}\` address to contribute to the repo. :(
            Please update your repo config \`.git/config\`:
            \`\`\`
              [user]
                name = Your Name
                email = my_email@mycompany.com
            \`\`\`
            > You may see \`<id>+<name>@users.noreply.github.com\` email, then you need to turn off [Keep my email addresses private](https://github.com/settings/emails) setting in your account.
            `})
DAVID _
  • 617
  • 1
  • 7
  • 16
  • 1
    This looks like a decent solution. You might also want to look at creating a git commit hook. This will allow you to catch the error closer to the source. – Code-Apprentice Aug 29 '22 at 06:22