node-git-server logonode-git-server

Authentication

Pass an authenticate function to the Git constructor to require credentials. It runs on every request before the info/push/fetch events, and receives the request context plus a next callback.

The authenticate signature

new Git(repoDir, {
    authenticate: ({ type, repo, user, headers }, next) => {
        // call next() to allow, next(error) to deny
    },
})
FieldDescription
type"fetch" or "push" — the operation being attempted
repothe repository name
usera function that resolves the basic-auth username and password
headersthe incoming request headers

Call next() to allow the request, or next(new Error("message")) to reject it with a 401.

Reading the credentials

user prompts the client for HTTP basic-auth credentials and hands them to your callback:

new Git(repoDir, {
    autoCreate: true,
    authenticate: ({ type, repo, user }, next) => {
        // only require credentials for pushes
        if (type !== "push") return next()
 
        user((username, password) => {
            if (username === "admin" && password === "s3cret") {
                next()
            } else {
                next(new Error("incorrect username or password"))
            }
        })
    },
})

If a request has no credentials, the server responds with 401 Unauthorized and the git client re-sends the request with an Authorization header.

Promise form

authenticate may return a Promise instead of using next. Resolve to allow, reject to deny:

new Git(repoDir, {
    authenticate: ({ type, repo, user }) =>
        new Promise((resolve, reject) => {
            user((username, password) => {
                if (username === "admin" && password === "s3cret") {
                    resolve()
                } else {
                    reject("incorrect username or password")
                }
            })
        }),
})

For credential checks that hit a database or another service, see Async Authentication.