mirror of
https://github.com/pocketbase/pocketbase.git
synced 2025-01-10 00:43:36 +02:00
01e33c07fe
Co-authored-by: thisni1s <nils@jn2p.de>
76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
var _ Provider = (*Mailcow)(nil)
|
|
|
|
// NameMailcow is the unique name of the mailcow provider.
|
|
const NameMailcow string = "mailcow"
|
|
|
|
// Mailcow allows authentication via mailcow OAuth2.
|
|
type Mailcow struct {
|
|
*baseProvider
|
|
}
|
|
|
|
// NewMailcowProvider creates a new mailcow provider instance with some defaults.
|
|
func NewMailcowProvider() *Mailcow {
|
|
return &Mailcow{&baseProvider{
|
|
ctx: context.Background(),
|
|
scopes: []string{"profile"},
|
|
}}
|
|
}
|
|
|
|
// FetchAuthUser returns an AuthUser instance based on mailcow's user api.
|
|
//
|
|
// API reference: https://github.com/mailcow/mailcow-dockerized/blob/master/data/web/oauth/profile.php
|
|
func (p *Mailcow) 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 {
|
|
Id string `json:"id"`
|
|
Username string `json:"username"`
|
|
Email string `json:"email"`
|
|
FullName string `json:"full_name"`
|
|
Active int `json:"active"`
|
|
}{}
|
|
if err := json.Unmarshal(data, &extracted); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if extracted.Active != 1 {
|
|
return nil, errors.New("the mailcow user is not active")
|
|
}
|
|
|
|
user := &AuthUser{
|
|
Id: extracted.Id,
|
|
Name: extracted.FullName,
|
|
Username: extracted.Username,
|
|
Email: extracted.Email,
|
|
RawUser: rawUser,
|
|
AccessToken: token.AccessToken,
|
|
RefreshToken: token.RefreshToken,
|
|
}
|
|
|
|
// mailcow usernames are usually just the email adresses, so we just take the part in front of the @
|
|
if strings.Contains(user.Username, "@") {
|
|
user.Username = strings.Split(user.Username, "@")[0]
|
|
}
|
|
|
|
return user, nil
|
|
}
|