|
| 1 | +// Copyright 2023 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | +// Package blenderid implements the OAuth2 protocol for authenticating users through Blender ID |
| 4 | +// This package can be used as a reference implementation of an OAuth2 provider for Goth. |
| 5 | +package blenderid |
| 6 | + |
| 7 | +// Allow "encoding/json" import. |
| 8 | +import ( |
| 9 | + "bytes" |
| 10 | + "encoding/json" //nolint:depguard |
| 11 | + "errors" |
| 12 | + "fmt" |
| 13 | + "io" |
| 14 | + "net/http" |
| 15 | + "strconv" |
| 16 | + |
| 17 | + "github.com/markbates/goth" |
| 18 | + "golang.org/x/oauth2" |
| 19 | +) |
| 20 | + |
| 21 | +// These vars define the default Authentication, Token, and Profile URLS for Blender ID |
| 22 | +// |
| 23 | +// Examples: |
| 24 | +// |
| 25 | +// blenderid.AuthURL = "https://id.blender.org/oauth/authorize |
| 26 | +// blenderid.TokenURL = "https://id.blender.org/oauth/token |
| 27 | +// blenderid.ProfileURL = "https://id.blender.org/api/me |
| 28 | +var ( |
| 29 | + AuthURL = "https://id.blender.org/oauth/authorize" |
| 30 | + TokenURL = "https://id.blender.org/oauth/token" |
| 31 | + ProfileURL = "https://id.blender.org/api/me" |
| 32 | +) |
| 33 | + |
| 34 | +// Provider is the implementation of `goth.Provider` for accessing Blender ID |
| 35 | +type Provider struct { |
| 36 | + ClientKey string |
| 37 | + Secret string |
| 38 | + CallbackURL string |
| 39 | + HTTPClient *http.Client |
| 40 | + config *oauth2.Config |
| 41 | + providerName string |
| 42 | + profileURL string |
| 43 | +} |
| 44 | + |
| 45 | +// New creates a new Blender ID provider and sets up important connection details. |
| 46 | +// You should always call `blenderid.New` to get a new provider. Never try to |
| 47 | +// create one manually. |
| 48 | +func New(clientKey, secret, callbackURL string, scopes ...string) *Provider { |
| 49 | + return NewCustomisedURL(clientKey, secret, callbackURL, AuthURL, TokenURL, ProfileURL, scopes...) |
| 50 | +} |
| 51 | + |
| 52 | +// NewCustomisedURL is similar to New(...) but can be used to set custom URLs to connect to |
| 53 | +func NewCustomisedURL(clientKey, secret, callbackURL, authURL, tokenURL, profileURL string, scopes ...string) *Provider { |
| 54 | + p := &Provider{ |
| 55 | + ClientKey: clientKey, |
| 56 | + Secret: secret, |
| 57 | + CallbackURL: callbackURL, |
| 58 | + providerName: "blenderid", |
| 59 | + profileURL: profileURL, |
| 60 | + } |
| 61 | + p.config = newConfig(p, authURL, tokenURL, scopes) |
| 62 | + return p |
| 63 | +} |
| 64 | + |
| 65 | +// Name is the name used to retrieve this provider later. |
| 66 | +func (p *Provider) Name() string { |
| 67 | + return p.providerName |
| 68 | +} |
| 69 | + |
| 70 | +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) |
| 71 | +func (p *Provider) SetName(name string) { |
| 72 | + p.providerName = name |
| 73 | +} |
| 74 | + |
| 75 | +func (p *Provider) Client() *http.Client { |
| 76 | + return goth.HTTPClientWithFallBack(p.HTTPClient) |
| 77 | +} |
| 78 | + |
| 79 | +// Debug is a no-op for the blenderid package. |
| 80 | +func (p *Provider) Debug(debug bool) {} |
| 81 | + |
| 82 | +// BeginAuth asks Blender ID for an authentication end-point. |
| 83 | +func (p *Provider) BeginAuth(state string) (goth.Session, error) { |
| 84 | + return &Session{ |
| 85 | + AuthURL: p.config.AuthCodeURL(state), |
| 86 | + }, nil |
| 87 | +} |
| 88 | + |
| 89 | +// FetchUser will go to Blender ID and access basic information about the user. |
| 90 | +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { |
| 91 | + sess := session.(*Session) |
| 92 | + user := goth.User{ |
| 93 | + AccessToken: sess.AccessToken, |
| 94 | + Provider: p.Name(), |
| 95 | + RefreshToken: sess.RefreshToken, |
| 96 | + ExpiresAt: sess.ExpiresAt, |
| 97 | + } |
| 98 | + |
| 99 | + if user.AccessToken == "" { |
| 100 | + // data is not yet retrieved since accessToken is still empty |
| 101 | + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) |
| 102 | + } |
| 103 | + |
| 104 | + req, err := http.NewRequest("GET", p.profileURL, nil) |
| 105 | + if err != nil { |
| 106 | + return user, err |
| 107 | + } |
| 108 | + |
| 109 | + req.Header.Add("Authorization", "Bearer "+sess.AccessToken) |
| 110 | + response, err := p.Client().Do(req) |
| 111 | + if err != nil { |
| 112 | + return user, err |
| 113 | + } |
| 114 | + if response.StatusCode != http.StatusOK { |
| 115 | + return user, fmt.Errorf("Blender ID responded with a %d trying to fetch user information", response.StatusCode) |
| 116 | + } |
| 117 | + |
| 118 | + bits, err := io.ReadAll(response.Body) |
| 119 | + if err != nil { |
| 120 | + return user, err |
| 121 | + } |
| 122 | + |
| 123 | + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) |
| 124 | + if err != nil { |
| 125 | + return user, err |
| 126 | + } |
| 127 | + |
| 128 | + err = userFromReader(bytes.NewReader(bits), &user) |
| 129 | + if err != nil { |
| 130 | + return user, err |
| 131 | + } |
| 132 | + |
| 133 | + return user, err |
| 134 | +} |
| 135 | + |
| 136 | +func newConfig(provider *Provider, authURL, tokenURL string, scopes []string) *oauth2.Config { |
| 137 | + c := &oauth2.Config{ |
| 138 | + ClientID: provider.ClientKey, |
| 139 | + ClientSecret: provider.Secret, |
| 140 | + RedirectURL: provider.CallbackURL, |
| 141 | + Endpoint: oauth2.Endpoint{ |
| 142 | + AuthURL: authURL, |
| 143 | + TokenURL: tokenURL, |
| 144 | + }, |
| 145 | + Scopes: []string{}, |
| 146 | + } |
| 147 | + |
| 148 | + if len(scopes) > 0 { |
| 149 | + c.Scopes = append(c.Scopes, scopes...) |
| 150 | + } |
| 151 | + return c |
| 152 | +} |
| 153 | + |
| 154 | +func userFromReader(r io.Reader, user *goth.User) error { |
| 155 | + u := struct { |
| 156 | + Name string `json:"full_name"` |
| 157 | + Email string `json:"email"` |
| 158 | + NickName string `json:"nickname"` |
| 159 | + ID int `json:"id"` |
| 160 | + }{} |
| 161 | + err := json.NewDecoder(r).Decode(&u) |
| 162 | + if err != nil { |
| 163 | + return err |
| 164 | + } |
| 165 | + user.Email = u.Email |
| 166 | + user.Name = u.Name |
| 167 | + user.NickName = gitealizeUsername(u.NickName) |
| 168 | + user.UserID = strconv.Itoa(u.ID) |
| 169 | + user.AvatarURL = fmt.Sprintf("https://id.blender.org/api/user/%s/avatar", user.UserID) |
| 170 | + return nil |
| 171 | +} |
| 172 | + |
| 173 | +// RefreshTokenAvailable refresh token is not provided by Blender ID |
| 174 | +func (p *Provider) RefreshTokenAvailable() bool { |
| 175 | + return true |
| 176 | +} |
| 177 | + |
| 178 | +// RefreshToken refresh token is not provided by Blender ID |
| 179 | +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { |
| 180 | + return nil, errors.New("Refresh token is not provided by Blender ID") |
| 181 | +} |
0 commit comments