Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions havril/internal/api/handlers/oauth_handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers

import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
Expand Down Expand Up @@ -29,8 +30,32 @@ type codeEntry struct {
expiresAt time.Time
}

func NewOAuthHandler(baseURL string, userRepo *user.Repository) *OAuthHandler {
return &OAuthHandler{baseURL: baseURL, userRepo: userRepo}
func NewOAuthHandler(ctx context.Context, baseURL string, userRepo *user.Repository) *OAuthHandler {
h := &OAuthHandler{baseURL: baseURL, userRepo: userRepo}
go h.cleanupExpiredCodes(ctx, 5*time.Minute)
return h
}

func (h *OAuthHandler) cleanupExpiredCodes(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.deleteExpiredCodes(time.Now())
}
}
}

func (h *OAuthHandler) deleteExpiredCodes(now time.Time) {
h.codes.Range(func(k, v any) bool {
if now.After(v.(*codeEntry).expiresAt) {
h.codes.Delete(k)
}
return true
})
}

// Metadata handles GET /.well-known/oauth-authorization-server
Expand Down
6 changes: 4 additions & 2 deletions havril/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,13 @@ func main() {
}
goth.UseProviders(providers...)

ctx := context.Background()

// Dependency injection
userRepo := user.NewRepository(db)
userSvc := user.NewService(userRepo)
authHandler := handlers.NewAuthHandler(userSvc)
oauthHandler := handlers.NewOAuthHandler(baseURL, userRepo)
oauthHandler := handlers.NewOAuthHandler(ctx, baseURL, userRepo)
authMid := middleware.NewAuthMiddleware(userSvc)
modelRepo := user.NewModelRepository(db)
modelSvc := user.NewModelService(modelRepo)
Expand All @@ -84,7 +86,7 @@ func main() {
if err != nil {
log.Fatalf("connect qdrant: %v", err)
}
if err := store.EnsureCollection(context.Background(), qdrantHost, qdrantAPIKey); err != nil {
if err := store.EnsureCollection(ctx, qdrantHost, qdrantAPIKey); err != nil {
log.Fatalf("failed to ensure qdrant collection: %v", err)
}
embedder, err := embedding.New(embedding.Config{
Expand Down