2022-07-06 23:19:05 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2022-11-30 15:16:09 +02:00
|
|
|
"encoding/json"
|
2022-07-06 23:19:05 +02:00
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ Provider = (*Gitlab)(nil)
|
|
|
|
|
|
|
|
// NameGitlab is the unique name of the Gitlab provider.
|
|
|
|
const NameGitlab string = "gitlab"
|
|
|
|
|
|
|
|
// Gitlab allows authentication via Gitlab OAuth2.
|
|
|
|
type Gitlab struct {
|
|
|
|
*baseProvider
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGitlabProvider creates new Gitlab provider instance with some defaults.
|
|
|
|
func NewGitlabProvider() *Gitlab {
|
|
|
|
return &Gitlab{&baseProvider{
|
|
|
|
scopes: []string{"read_user"},
|
|
|
|
authUrl: "https://gitlab.com/oauth/authorize",
|
|
|
|
tokenUrl: "https://gitlab.com/oauth/token",
|
|
|
|
userApiUrl: "https://gitlab.com/api/v4/user",
|
|
|
|
}}
|
|
|
|
}
|
|
|
|
|
|
|
|
// FetchAuthUser returns an AuthUser instance based the Gitlab's user api.
|
2022-11-30 15:16:09 +02:00
|
|
|
//
|
|
|
|
// API reference: https://docs.gitlab.com/ee/api/users.html#for-admin
|
2022-07-06 23:19:05 +02:00
|
|
|
func (p *Gitlab) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
|
2022-11-30 15:16:09 +02:00
|
|
|
data, err := p.FetchRawUserData(token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
rawUser := map[string]any{}
|
|
|
|
if err := json.Unmarshal(data, &rawUser); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
extracted := struct {
|
2022-07-06 23:19:05 +02:00
|
|
|
Id int `json:"id"`
|
|
|
|
Name string `json:"name"`
|
2022-09-05 15:15:27 +02:00
|
|
|
Username string `json:"username"`
|
2022-07-06 23:19:05 +02:00
|
|
|
Email string `json:"email"`
|
|
|
|
AvatarUrl string `json:"avatar_url"`
|
|
|
|
}{}
|
2022-11-30 15:16:09 +02:00
|
|
|
if err := json.Unmarshal(data, &extracted); err != nil {
|
2022-07-06 23:19:05 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
user := &AuthUser{
|
2022-11-30 15:16:09 +02:00
|
|
|
Id: strconv.Itoa(extracted.Id),
|
|
|
|
Name: extracted.Name,
|
|
|
|
Username: extracted.Username,
|
|
|
|
Email: extracted.Email,
|
|
|
|
AvatarUrl: extracted.AvatarUrl,
|
|
|
|
RawUser: rawUser,
|
|
|
|
AccessToken: token.AccessToken,
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|