1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2024-11-28 18:11:17 +02:00
pocketbase/tools/auth/gitlab.go

67 lines
1.6 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package auth
import (
"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.
//
// 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) {
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"`
Username string `json:"username"`
2022-07-06 23:19:05 +02:00
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
2022-07-06 23:19:05 +02:00
return nil, err
}
user := &AuthUser{
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
}