scotty/internal/auth/strategy.go
2023-11-27 14:47:46 +01:00

71 lines
1.9 KiB
Go

/*
Copyright © 2023 Philipp Wolfer <phw@uploadedlobster.com>
Scotty is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
Scotty is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Scotty. If not, see <https://www.gnu.org/licenses/>.
*/
package auth
import (
"context"
"golang.org/x/oauth2"
)
type OAuth2Strategy interface {
Config() oauth2.Config
AuthCodeURL(verifier string, state string) AuthUrl
ExchangeToken(code CodeResponse, verifier string) (*oauth2.Token, error)
}
type AuthUrl struct {
// The URL the user must visit to approve access
Url string
// Random state string passed on to the callback.
// Leave empty if the service does not support state.
State string
// Parameter name of the code passed on to the callback (usually "code")
Param string
}
type CodeResponse struct {
Code string
State string
}
func NewStandardStrategy(conf oauth2.Config) OAuth2Strategy {
return StandardStrategy{conf: conf}
}
type StandardStrategy struct {
conf oauth2.Config
}
func (s StandardStrategy) Config() oauth2.Config {
return s.conf
}
func (s StandardStrategy) AuthCodeURL(verifier string, state string) AuthUrl {
url := s.conf.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier))
return AuthUrl{
Url: url,
State: state,
Param: "code",
}
}
func (s StandardStrategy) ExchangeToken(code CodeResponse, verifier string) (*oauth2.Token, error) {
ctx := context.Background()
return s.conf.Exchange(ctx, code.Code, oauth2.VerifierOption(verifier))
}