blob: b015f16ec9c88a74b2fc93d34bb321effd69a1d6 [file] [log] [blame]
Akron90f65212025-06-12 14:32:55 +02001package config
2
3import (
4 "fmt"
5
6 "golang.org/x/oauth2"
7)
8
9// OAuthConfig represents OAuth2 configuration for KorAP authentication
10type OAuthConfig struct {
11 // ClientID is the OAuth2 client identifier
12 ClientID string `yaml:"client_id"`
13
14 // ClientSecret is the OAuth2 client secret
15 ClientSecret string `yaml:"client_secret"`
16
17 // AuthURL is the authorization endpoint URL
18 AuthURL string `yaml:"auth_url"`
19
20 // TokenURL is the token endpoint URL
21 TokenURL string `yaml:"token_url"`
22
23 // RedirectURL is the callback URL for authorization code flow
24 RedirectURL string `yaml:"redirect_url"`
25
26 // Scopes are the requested OAuth2 scopes
27 Scopes []string `yaml:"scopes"`
28
29 // Enabled indicates whether OAuth2 authentication is enabled
30 Enabled bool `yaml:"enabled"`
31}
32
33// DefaultOAuthConfig returns a default OAuth2 configuration
34func DefaultOAuthConfig() *OAuthConfig {
35 return &OAuthConfig{
36 AuthURL: "https://korap.ids-mannheim.de/api/v1.0/oauth2/authorize",
37 TokenURL: "https://korap.ids-mannheim.de/api/v1.0/oauth2/token",
38 RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
39 Scopes: []string{"read"},
40 Enabled: false,
41 }
42}
43
44// ToOAuth2Config converts the config to golang.org/x/oauth2.Config
45func (c *OAuthConfig) ToOAuth2Config() *oauth2.Config {
46 if !c.Enabled {
47 return nil
48 }
49
50 return &oauth2.Config{
51 ClientID: c.ClientID,
52 ClientSecret: c.ClientSecret,
53 Endpoint: oauth2.Endpoint{
54 AuthURL: c.AuthURL,
55 TokenURL: c.TokenURL,
56 },
57 RedirectURL: c.RedirectURL,
58 Scopes: c.Scopes,
59 }
60}
61
62// Validate checks if the OAuth2 configuration is valid
63func (c *OAuthConfig) Validate() error {
64 if !c.Enabled {
65 return nil
66 }
67
68 if c.ClientID == "" {
69 return fmt.Errorf("oauth2 client_id is required when authentication is enabled")
70 }
71
72 if c.ClientSecret == "" {
73 return fmt.Errorf("oauth2 client_secret is required when authentication is enabled")
74 }
75
76 if c.TokenURL == "" {
77 return fmt.Errorf("oauth2 token_url is required when authentication is enabled")
78 }
79
80 // AuthURL is only required for authorization code flow, not client credentials
81
82 return nil
83}