通过 API 使用 Ruby 访问 GitLab

Accessing GitLab via API with Ruby

第一次尝试通过 API 访问我大学的 GitLab(我是存储库所有者,但无法访问控制台,也无法编辑配置文件或重新启动服务器),我似乎缺乏一些强制性的基础知识。尝试将 Ruby(没有 rails)与 Narkoz API 包装器一起使用。不幸的是,没有可用的教程来解释第一步:

如何连接到服务器并使用 UID+passwd 进行身份验证?

任何人都可以用人类可读的说明解释这个过程吗? GitLab Manual 对我没有帮助。

我希望我能弄清楚如何将 GitLab 用户添加到我的存储库。不想使用网络界面添加 100 个用户。

您链接的手动条目用于通过第三方 OAuth 提供商登录 GitLab,这听起来不像您想要做的。听起来你想做的是 request an OAuth token 然后你可以用它来访问 GitLab 的 API.

来自文档:

In this flow, a token is requested in exchange for the resource owner credentials (username and password). The credentials should only be used when there is a high degree of trust between the resource owner and the client (e.g. the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).

这听起来像你想要做的。

文档中的一件重要事项:

Deprecation notice: Starting in GitLab 8.11, the Resource Owner Password Credentials has been disabled for users with two-factor authentication turned on. These users can access the API using personal access tokens instead.

如果您属于这种情况,以下方法将不起作用,您需要生成一个访问令牌。

1. Requesting access token

POST request to /oauth/token with parameters:

{
  "grant_type"    : "password",
  "username"      : "user@example.com",
  "password"      : "secret"
}

Then, you'll receive the access token back in the response:

{
  "access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
  "token_type": "bearer",
  "expires_in": 7200
}

然后您可以将此令牌指定为您的 GitLab.private_token

为了记录 -- 最小可行的例子会帮助更快 -- 特别是因为 API 文档包含已知的和未修复的错误。

host = myGitlabServer

require 'oauth2'
client = OAuth2::Client.new(clientIdFromGitLab, clientSecretFromGitLab, :site => host)
accessToken = client.password.get_token(myGitLabUid, myGitLabPassword)

require 'httparty'
# get own user data
response = HTTParty.get(host + '/api/v4/user?access_token=' + accessToken.token)
puts response.parsed_response

# get user data by user name
response = HTTParty.get(host + '/api/v4/users?username=' + username + '&access_token=' + access_token.token)
puts response.parsed_response[0]

# add user as reporter to project
response = HTTParty.post(host + '/api/v4/projects/' + projectId + '/members/?user_id=' + newUID + '&access_level=20&access_token=' + access_token.token)
puts response.parsed_response

或者,你可以使用优秀的 gitlab gem.