1
0
mirror of https://github.com/pocket-id/pocket-id.git synced 2026-02-15 23:51:11 +00:00

refactor: complete conversion of log calls to slog (#787)

This commit is contained in:
Alessandro (Ale) Segala
2025-07-27 06:34:23 +02:00
committed by GitHub
parent 78266e3e4c
commit 42a861d206
22 changed files with 142 additions and 88 deletions

View File

@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"log"
"mime/multipart"
"os"
"reflect"
@@ -28,22 +27,22 @@ type AppConfigService struct {
db *gorm.DB
}
func NewAppConfigService(ctx context.Context, db *gorm.DB) *AppConfigService {
func NewAppConfigService(ctx context.Context, db *gorm.DB) (*AppConfigService, error) {
service := &AppConfigService{
db: db,
}
err := service.LoadDbConfig(ctx)
if err != nil {
log.Fatalf("Failed to initialize app config service: %v", err)
return nil, fmt.Errorf("failed to initialize app config service: %w", err)
}
err = service.initInstanceID(ctx)
if err != nil {
log.Fatalf("Failed to initialize instance ID: %v", err)
return nil, fmt.Errorf("failed to initialize instance ID: %w", err)
}
return service
return service, nil
}
// GetDbConfig returns the application configuration.

View File

@@ -22,7 +22,12 @@ type AuditLogService struct {
}
func NewAuditLogService(db *gorm.DB, appConfigService *AppConfigService, emailService *EmailService, geoliteService *GeoLiteService) *AuditLogService {
return &AuditLogService{db: db, appConfigService: appConfigService, emailService: emailService, geoliteService: geoliteService}
return &AuditLogService{
db: db,
appConfigService: appConfigService,
emailService: emailService,
geoliteService: geoliteService,
}
}
// Create creates a new audit log entry in the database

View File

@@ -10,7 +10,7 @@ import (
"crypto/x509"
"encoding/base64"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"time"
@@ -402,9 +402,9 @@ func (s *TestService) ResetDatabase() error {
return err
}
func (s *TestService) ResetApplicationImages() error {
func (s *TestService) ResetApplicationImages(ctx context.Context) error {
if err := os.RemoveAll(common.EnvConfig.UploadPath); err != nil {
log.Printf("Error removing directory: %v", err)
slog.ErrorContext(ctx, "Error removing directory", slog.Any("error", err))
return err
}

View File

@@ -57,7 +57,8 @@ func NewGeoLiteService(httpClient *http.Client) *GeoLiteService {
}
// Initialize IPv6 local ranges
if err := service.initializeIPv6LocalRanges(); err != nil {
err := service.initializeIPv6LocalRanges()
if err != nil {
slog.Warn("Failed to initialize IPv6 local ranges", slog.Any("error", err))
}

View File

@@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/url"
@@ -169,13 +168,13 @@ func (s *LdapService) SyncGroups(ctx context.Context, tx *gorm.DB, client *ldap.
userResult, err := client.Search(userSearchReq)
if err != nil || len(userResult.Entries) == 0 {
log.Printf("Could not resolve group member DN '%s': %v", member, err)
slog.WarnContext(ctx, "Could not resolve group member DN", slog.String("member", member), slog.Any("error", err))
continue
}
username = userResult.Entries[0].GetAttributeValue(dbConfig.LdapAttributeUserUsername.Value)
if username == "" {
log.Printf("Could not extract username from group member DN '%s'", member)
slog.WarnContext(ctx, "Could not extract username from group member DN", slog.String("member", member))
continue
}
}

View File

@@ -8,7 +8,6 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"mime/multipart"
"net/http"
@@ -1180,9 +1179,13 @@ func (s *OidcService) VerifyDeviceCode(ctx context.Context, userCode string, use
}()
var deviceAuth model.OidcDeviceCode
if err := tx.WithContext(ctx).Preload("Client.AllowedUserGroups").First(&deviceAuth, "user_code = ?", userCode).Error; err != nil {
log.Printf("Error finding device code with user_code %s: %v", userCode, err)
return err
err := tx.
WithContext(ctx).
Preload("Client.AllowedUserGroups").
First(&deviceAuth, "user_code = ?", userCode).
Error
if err != nil {
return fmt.Errorf("error finding device code: %w", err)
}
if time.Now().After(deviceAuth.ExpiresAt.ToTime()) {
@@ -1191,17 +1194,26 @@ func (s *OidcService) VerifyDeviceCode(ctx context.Context, userCode string, use
// Check if the user group is allowed to authorize the client
var user model.User
if err := tx.WithContext(ctx).Preload("UserGroups").First(&user, "id = ?", userID).Error; err != nil {
return err
err = tx.
WithContext(ctx).
Preload("UserGroups").
First(&user, "id = ?", userID).
Error
if err != nil {
return fmt.Errorf("error finding user groups: %w", err)
}
if !s.IsUserGroupAllowedToAuthorize(user, deviceAuth.Client) {
return &common.OidcAccessDeniedError{}
}
if err := tx.WithContext(ctx).Preload("Client").First(&deviceAuth, "user_code = ?", userCode).Error; err != nil {
log.Printf("Error finding device code with user_code %s: %v", userCode, err)
return err
err = tx.
WithContext(ctx).
Preload("Client").
First(&deviceAuth, "user_code = ?", userCode).
Error
if err != nil {
return fmt.Errorf("error finding device code: %w", err)
}
if time.Now().After(deviceAuth.ExpiresAt.ToTime()) {
@@ -1211,16 +1223,12 @@ func (s *OidcService) VerifyDeviceCode(ctx context.Context, userCode string, use
deviceAuth.UserID = &userID
deviceAuth.IsAuthorized = true
if err := tx.WithContext(ctx).Save(&deviceAuth).Error; err != nil {
log.Printf("Error saving device auth: %v", err)
return err
}
// Verify the update was successful
var verifiedAuth model.OidcDeviceCode
if err := tx.WithContext(ctx).First(&verifiedAuth, "device_code = ?", deviceAuth.DeviceCode).Error; err != nil {
log.Printf("Error verifying update: %v", err)
return err
err = tx.
WithContext(ctx).
Save(&deviceAuth).
Error
if err != nil {
return fmt.Errorf("error saving device auth: %w", err)
}
// Create user authorization if needed
@@ -1229,15 +1237,16 @@ func (s *OidcService) VerifyDeviceCode(ctx context.Context, userCode string, use
return err
}
auditLogData := model.AuditLogData{"clientName": deviceAuth.Client.Name}
if !hasAuthorizedClient {
err := s.createAuthorizedClientInternal(ctx, userID, deviceAuth.ClientID, deviceAuth.Scope, tx)
err = s.createAuthorizedClientInternal(ctx, userID, deviceAuth.ClientID, deviceAuth.Scope, tx)
if err != nil {
return err
}
s.auditLogService.Create(ctx, model.AuditLogEventNewDeviceCodeAuthorization, ipAddress, userAgent, userID, model.AuditLogData{"clientName": deviceAuth.Client.Name}, tx)
s.auditLogService.Create(ctx, model.AuditLogEventNewDeviceCodeAuthorization, ipAddress, userAgent, userID, auditLogData, tx)
} else {
s.auditLogService.Create(ctx, model.AuditLogEventDeviceCodeAuthorization, ipAddress, userAgent, userID, model.AuditLogData{"clientName": deviceAuth.Client.Name}, tx)
s.auditLogService.Create(ctx, model.AuditLogEventDeviceCodeAuthorization, ipAddress, userAgent, userID, auditLogData, tx)
}
return tx.Commit().Error
@@ -1428,7 +1437,7 @@ func (s *OidcService) verifyClientCredentialsInternal(ctx context.Context, tx *g
case isClientAssertion:
err = s.verifyClientAssertionFromFederatedIdentities(ctx, client, input)
if err != nil {
log.Printf("Invalid assertion for client '%s': %v", client.ID, err)
slog.WarnContext(ctx, "Invalid assertion for client", slog.String("client", client.ID), slog.Any("error", err))
return nil, &common.OidcClientAssertionInvalidError{}
}
return client, nil

View File

@@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"net/url"
"os"
@@ -35,7 +34,13 @@ type UserService struct {
}
func NewUserService(db *gorm.DB, jwtService *JwtService, auditLogService *AuditLogService, emailService *EmailService, appConfigService *AppConfigService) *UserService {
return &UserService{db: db, jwtService: jwtService, auditLogService: auditLogService, emailService: emailService, appConfigService: appConfigService}
return &UserService{
db: db,
jwtService: jwtService,
auditLogService: auditLogService,
emailService: emailService,
appConfigService: appConfigService,
}
}
func (s *UserService) ListUsers(ctx context.Context, searchTerm string, sortedPaginationRequest utils.SortedPaginationRequest) ([]model.User, utils.PaginationResponse, error) {
@@ -47,7 +52,8 @@ func (s *UserService) ListUsers(ctx context.Context, searchTerm string, sortedPa
if searchTerm != "" {
searchPattern := "%" + searchTerm + "%"
query = query.Where("email LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR username LIKE ?",
query = query.Where(
"email LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR username LIKE ?",
searchPattern, searchPattern, searchPattern, searchPattern)
}
@@ -120,13 +126,14 @@ func (s *UserService) GetProfilePicture(ctx context.Context, userID string) (io.
defaultPictureBytes := defaultPicture.Bytes()
go func() {
// Ensure the directory exists
err = os.MkdirAll(defaultProfilePicturesDir, os.ModePerm)
if err != nil {
log.Printf("Failed to create directory for default profile picture: %v", err)
errInternal := os.MkdirAll(defaultProfilePicturesDir, os.ModePerm)
if errInternal != nil {
slog.Error("Failed to create directory for default profile picture", slog.Any("error", errInternal))
return
}
if err := utils.SaveFileStream(bytes.NewReader(defaultPictureBytes), defaultPicturePath); err != nil {
log.Printf("Failed to cache default profile picture for initials %s: %v", user.Initials(), err)
errInternal = utils.SaveFileStream(bytes.NewReader(defaultPictureBytes), defaultPicturePath)
if errInternal != nil {
slog.Error("Failed to cache default profile picture for initials", slog.String("initials", user.Initials()), slog.Any("error", errInternal))
}
}()

View File

@@ -25,8 +25,8 @@ type WebAuthnService struct {
appConfigService *AppConfigService
}
func NewWebAuthnService(db *gorm.DB, jwtService *JwtService, auditLogService *AuditLogService, appConfigService *AppConfigService) *WebAuthnService {
webauthnConfig := &webauthn.Config{
func NewWebAuthnService(db *gorm.DB, jwtService *JwtService, auditLogService *AuditLogService, appConfigService *AppConfigService) (*WebAuthnService, error) {
wa, err := webauthn.New(&webauthn.Config{
RPDisplayName: appConfigService.GetDbConfig().AppName.Value,
RPID: utils.GetHostnameFromURL(common.EnvConfig.AppURL),
RPOrigins: []string{common.EnvConfig.AppURL},
@@ -45,15 +45,18 @@ func NewWebAuthnService(db *gorm.DB, jwtService *JwtService, auditLogService *Au
TimeoutUVD: time.Second * 60,
},
},
})
if err != nil {
return nil, fmt.Errorf("failed to init webauthn object: %w", err)
}
wa, _ := webauthn.New(webauthnConfig)
return &WebAuthnService{
db: db,
webAuthn: wa,
jwtService: jwtService,
auditLogService: auditLogService,
appConfigService: appConfigService,
}
}, nil
}
func (s *WebAuthnService) BeginRegistration(ctx context.Context, userID string) (*model.PublicKeyCredentialCreationOptions, error) {