Skip to content

Commit 1941de1

Browse files
authored
refactor: remove init functions from methods (#228)
1 parent 49c4c7a commit 1941de1

10 files changed

Lines changed: 142 additions & 181 deletions

File tree

cmd/root.go

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@ import (
88
"time"
99
totpCmd "tinyauth/cmd/totp"
1010
userCmd "tinyauth/cmd/user"
11-
"tinyauth/internal/api"
1211
"tinyauth/internal/auth"
1312
"tinyauth/internal/constants"
1413
"tinyauth/internal/docker"
1514
"tinyauth/internal/handlers"
1615
"tinyauth/internal/hooks"
1716
"tinyauth/internal/providers"
17+
"tinyauth/internal/server"
1818
"tinyauth/internal/types"
1919
"tinyauth/internal/utils"
2020

@@ -114,8 +114,8 @@ var rootCmd = &cobra.Command{
114114
RedirectCookieName: redirectCookieName,
115115
}
116116

117-
// Create api config
118-
apiConfig := types.APIConfig{
117+
// Create server config
118+
serverConfig := types.ServerConfig{
119119
Port: config.Port,
120120
Address: config.Address,
121121
}
@@ -140,10 +140,7 @@ var rootCmd = &cobra.Command{
140140
}
141141

142142
// Create docker service
143-
docker := docker.NewDocker()
144-
145-
// Initialize docker
146-
err = docker.Init()
143+
docker, err := docker.NewDocker()
147144
HandleError(err, "Failed to initialize docker")
148145

149146
// Create auth service
@@ -152,24 +149,19 @@ var rootCmd = &cobra.Command{
152149
// Create OAuth providers service
153150
providers := providers.NewProviders(oauthConfig)
154151

155-
// Initialize providers
156-
providers.Init()
157-
158152
// Create hooks service
159153
hooks := hooks.NewHooks(hooksConfig, auth, providers)
160154

161155
// Create handlers
162156
handlers := handlers.NewHandlers(handlersConfig, auth, hooks, providers, docker)
163157

164-
// Create API
165-
api := api.NewAPI(apiConfig, handlers)
166-
167-
// Setup routes
168-
api.Init()
169-
api.SetupRoutes()
158+
// Create server
159+
srv, err := server.NewServer(serverConfig, handlers)
160+
HandleError(err, "Failed to create server")
170161

171-
// Start
172-
api.Run()
162+
// Start server
163+
err = srv.Start()
164+
HandleError(err, "Failed to start server")
173165
},
174166
}
175167

internal/auth/auth.go

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,38 @@ import (
1616
"golang.org/x/crypto/bcrypt"
1717
)
1818

19-
func NewAuth(config types.AuthConfig, docker *docker.Docker) *Auth {
20-
return &Auth{
21-
Config: config,
22-
Docker: docker,
23-
LoginAttempts: make(map[string]*types.LoginAttempt),
24-
}
25-
}
26-
2719
type Auth struct {
2820
Config types.AuthConfig
2921
Docker *docker.Docker
3022
LoginAttempts map[string]*types.LoginAttempt
3123
LoginMutex sync.RWMutex
24+
Store *sessions.CookieStore
3225
}
3326

34-
func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
27+
func NewAuth(config types.AuthConfig, docker *docker.Docker) *Auth {
3528
// Create cookie store
36-
store := sessions.NewCookieStore([]byte(auth.Config.HMACSecret), []byte(auth.Config.EncryptionSecret))
29+
store := sessions.NewCookieStore([]byte(config.HMACSecret), []byte(config.EncryptionSecret))
3730

3831
// Configure cookie store
3932
store.Options = &sessions.Options{
4033
Path: "/",
41-
MaxAge: auth.Config.SessionExpiry,
42-
Secure: auth.Config.CookieSecure,
34+
MaxAge: config.SessionExpiry,
35+
Secure: config.CookieSecure,
4336
HttpOnly: true,
44-
Domain: fmt.Sprintf(".%s", auth.Config.Domain),
37+
Domain: fmt.Sprintf(".%s", config.Domain),
4538
}
4639

40+
return &Auth{
41+
Config: config,
42+
Docker: docker,
43+
LoginAttempts: make(map[string]*types.LoginAttempt),
44+
Store: store,
45+
}
46+
}
47+
48+
func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
4749
// Get session
48-
session, err := store.Get(c.Request, auth.Config.SessionCookieName)
50+
session, err := auth.Store.Get(c.Request, auth.Config.SessionCookieName)
4951

5052
if err != nil {
5153
log.Warn().Err(err).Msg("Invalid session, clearing cookie and retrying")
@@ -54,7 +56,7 @@ func (auth *Auth) GetSession(c *gin.Context) (*sessions.Session, error) {
5456
c.SetCookie(auth.Config.SessionCookieName, "", -1, "/", fmt.Sprintf(".%s", auth.Config.Domain), auth.Config.CookieSecure, true)
5557

5658
// Try to get the session again
57-
session, err = store.Get(c.Request, auth.Config.SessionCookieName)
59+
session, err = auth.Store.Get(c.Request, auth.Config.SessionCookieName)
5860

5961
if err != nil {
6062
// If we still can't get the session, log the error and return nil

internal/docker/docker.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,35 +11,30 @@ import (
1111
"github.com/rs/zerolog/log"
1212
)
1313

14-
func NewDocker() *Docker {
15-
return &Docker{}
16-
}
17-
1814
type Docker struct {
1915
Client *client.Client
2016
Context context.Context
2117
}
2218

23-
func (docker *Docker) Init() error {
19+
func NewDocker() (*Docker, error) {
2420
// Create a new docker client
2521
client, err := client.NewClientWithOpts(client.FromEnv)
2622

2723
// Check if there was an error
2824
if err != nil {
29-
return err
25+
return nil, err
3026
}
3127

3228
// Create the context
33-
docker.Context = context.Background()
29+
ctx := context.Background()
3430

3531
// Negotiate API version
36-
client.NegotiateAPIVersion(docker.Context)
37-
38-
// Set client
39-
docker.Client = client
32+
client.NegotiateAPIVersion(ctx)
4033

41-
// Done
42-
return nil
34+
return &Docker{
35+
Client: client,
36+
Context: ctx,
37+
}, nil
4338
}
4439

4540
func (docker *Docker) GetContainers() ([]container.Summary, error) {

internal/handlers/handlers.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ import (
1818
"github.com/rs/zerolog/log"
1919
)
2020

21+
type Handlers struct {
22+
Config types.HandlersConfig
23+
Auth *auth.Auth
24+
Hooks *hooks.Hooks
25+
Providers *providers.Providers
26+
Docker *docker.Docker
27+
}
28+
2129
func NewHandlers(config types.HandlersConfig, auth *auth.Auth, hooks *hooks.Hooks, providers *providers.Providers, docker *docker.Docker) *Handlers {
2230
return &Handlers{
2331
Config: config,
@@ -28,14 +36,6 @@ func NewHandlers(config types.HandlersConfig, auth *auth.Auth, hooks *hooks.Hook
2836
}
2937
}
3038

31-
type Handlers struct {
32-
Config types.HandlersConfig
33-
Auth *auth.Auth
34-
Hooks *hooks.Hooks
35-
Providers *providers.Providers
36-
Docker *docker.Docker
37-
}
38-
3939
func (h *Handlers) AuthHandler(c *gin.Context) {
4040
// Create struct for proxy
4141
var proxy types.Proxy

internal/hooks/hooks.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ import (
1212
"github.com/rs/zerolog/log"
1313
)
1414

15+
type Hooks struct {
16+
Config types.HooksConfig
17+
Auth *auth.Auth
18+
Providers *providers.Providers
19+
}
20+
1521
func NewHooks(config types.HooksConfig, auth *auth.Auth, providers *providers.Providers) *Hooks {
1622
return &Hooks{
1723
Config: config,
@@ -20,12 +26,6 @@ func NewHooks(config types.HooksConfig, auth *auth.Auth, providers *providers.Pr
2026
}
2127
}
2228

23-
type Hooks struct {
24-
Config types.HooksConfig
25-
Auth *auth.Auth
26-
Providers *providers.Providers
27-
}
28-
2929
func (hooks *Hooks) UseUserContext(c *gin.Context) types.UserContext {
3030
// Get session cookie and basic auth
3131
cookie, err := hooks.Auth.GetSessionCookie(c)

internal/oauth/oauth.go

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,42 +10,41 @@ import (
1010
"golang.org/x/oauth2"
1111
)
1212

13-
func NewOAuth(config oauth2.Config, insecureSkipVerify bool) *OAuth {
14-
return &OAuth{
15-
Config: config,
16-
InsecureSkipVerify: insecureSkipVerify,
17-
}
18-
}
19-
2013
type OAuth struct {
21-
Config oauth2.Config
22-
Context context.Context
23-
Token *oauth2.Token
24-
Verifier string
25-
InsecureSkipVerify bool
14+
Config oauth2.Config
15+
Context context.Context
16+
Token *oauth2.Token
17+
Verifier string
2618
}
2719

28-
func (oauth *OAuth) Init() {
20+
func NewOAuth(config oauth2.Config, insecureSkipVerify bool) *OAuth {
2921
// Create transport with TLS
3022
transport := &http.Transport{
3123
TLSClientConfig: &tls.Config{
32-
InsecureSkipVerify: oauth.InsecureSkipVerify,
24+
InsecureSkipVerify: insecureSkipVerify,
3325
MinVersion: tls.VersionTLS12,
3426
},
3527
}
3628

3729
// Create a new context
38-
oauth.Context = context.Background()
30+
ctx := context.Background()
3931

4032
// Create the HTTP client with the transport
4133
httpClient := &http.Client{
4234
Transport: transport,
4335
}
4436

4537
// Set the HTTP client in the context
46-
oauth.Context = context.WithValue(oauth.Context, oauth2.HTTPClient, httpClient)
38+
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
39+
4740
// Create the verifier
48-
oauth.Verifier = oauth2.GenerateVerifier()
41+
verifier := oauth2.GenerateVerifier()
42+
43+
return &OAuth{
44+
Config: config,
45+
Context: ctx,
46+
Verifier: verifier,
47+
}
4948
}
5049

5150
func (oauth *OAuth) GetAuthURL(state string) string {

internal/providers/providers.go

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,73 +11,64 @@ import (
1111
"golang.org/x/oauth2/endpoints"
1212
)
1313

14-
func NewProviders(config types.OAuthConfig) *Providers {
15-
return &Providers{
16-
Config: config,
17-
}
18-
}
19-
2014
type Providers struct {
2115
Config types.OAuthConfig
2216
Github *oauth.OAuth
2317
Google *oauth.OAuth
2418
Generic *oauth.OAuth
2519
}
2620

27-
func (providers *Providers) Init() {
21+
func NewProviders(config types.OAuthConfig) *Providers {
22+
providers := &Providers{
23+
Config: config,
24+
}
25+
2826
// If we have a client id and secret for github, initialize the oauth provider
29-
if providers.Config.GithubClientId != "" && providers.Config.GithubClientSecret != "" {
27+
if config.GithubClientId != "" && config.GithubClientSecret != "" {
3028
log.Info().Msg("Initializing Github OAuth")
3129

3230
// Create a new oauth provider with the github config
3331
providers.Github = oauth.NewOAuth(oauth2.Config{
34-
ClientID: providers.Config.GithubClientId,
35-
ClientSecret: providers.Config.GithubClientSecret,
36-
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/github", providers.Config.AppURL),
32+
ClientID: config.GithubClientId,
33+
ClientSecret: config.GithubClientSecret,
34+
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/github", config.AppURL),
3735
Scopes: GithubScopes(),
3836
Endpoint: endpoints.GitHub,
3937
}, false)
40-
41-
// Initialize the oauth provider
42-
providers.Github.Init()
4338
}
4439

4540
// If we have a client id and secret for google, initialize the oauth provider
46-
if providers.Config.GoogleClientId != "" && providers.Config.GoogleClientSecret != "" {
41+
if config.GoogleClientId != "" && config.GoogleClientSecret != "" {
4742
log.Info().Msg("Initializing Google OAuth")
4843

4944
// Create a new oauth provider with the google config
5045
providers.Google = oauth.NewOAuth(oauth2.Config{
51-
ClientID: providers.Config.GoogleClientId,
52-
ClientSecret: providers.Config.GoogleClientSecret,
53-
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/google", providers.Config.AppURL),
46+
ClientID: config.GoogleClientId,
47+
ClientSecret: config.GoogleClientSecret,
48+
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/google", config.AppURL),
5449
Scopes: GoogleScopes(),
5550
Endpoint: endpoints.Google,
5651
}, false)
57-
58-
// Initialize the oauth provider
59-
providers.Google.Init()
6052
}
6153

6254
// If we have a client id and secret for generic oauth, initialize the oauth provider
63-
if providers.Config.GenericClientId != "" && providers.Config.GenericClientSecret != "" {
55+
if config.GenericClientId != "" && config.GenericClientSecret != "" {
6456
log.Info().Msg("Initializing Generic OAuth")
6557

6658
// Create a new oauth provider with the generic config
6759
providers.Generic = oauth.NewOAuth(oauth2.Config{
68-
ClientID: providers.Config.GenericClientId,
69-
ClientSecret: providers.Config.GenericClientSecret,
70-
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/generic", providers.Config.AppURL),
71-
Scopes: providers.Config.GenericScopes,
60+
ClientID: config.GenericClientId,
61+
ClientSecret: config.GenericClientSecret,
62+
RedirectURL: fmt.Sprintf("%s/api/oauth/callback/generic", config.AppURL),
63+
Scopes: config.GenericScopes,
7264
Endpoint: oauth2.Endpoint{
73-
AuthURL: providers.Config.GenericAuthURL,
74-
TokenURL: providers.Config.GenericTokenURL,
65+
AuthURL: config.GenericAuthURL,
66+
TokenURL: config.GenericTokenURL,
7567
},
76-
}, providers.Config.GenericSkipSSL)
77-
78-
// Initialize the oauth provider
79-
providers.Generic.Init()
68+
}, config.GenericSkipSSL)
8069
}
70+
71+
return providers
8172
}
8273

8374
func (providers *Providers) GetProvider(provider string) *oauth.OAuth {

0 commit comments

Comments
 (0)