1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2024-11-25 09:21:11 +02:00
pocketbase/tools/auth/gitlab.go

70 lines
1.6 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package auth
import (
2023-03-01 23:29:45 +02:00
"context"
"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{
2023-03-01 23:29:45 +02:00
ctx: context.Background(),
2022-07-06 23:19:05 +02:00
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{
2023-01-07 22:25:56 +02:00
Id: strconv.Itoa(extracted.Id),
Name: extracted.Name,
Username: extracted.Username,
Email: extracted.Email,
AvatarUrl: extracted.AvatarUrl,
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
2022-07-06 23:19:05 +02:00
}
return user, nil
}