Skip to content

Commit

Permalink
add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
loan-mgt committed Feb 6, 2025
1 parent 8285b1e commit 48c7dd4
Show file tree
Hide file tree
Showing 8 changed files with 306 additions and 35 deletions.
51 changes: 46 additions & 5 deletions decrypt/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,24 @@ import (
"encoding/base64"
"encoding/pem"
"fmt"
"log"
"os"

"cpe/calendar/logger"
)

func DecryptMessage(encryptedBase64 string, privateKey *rsa.PrivateKey) (string, error) {
// Log the decryption attempt with context
logger.Log.Info().
Str("encryptedBase64", encryptedBase64).
Msg("Attempting to decrypt message")

// Decode the Base64-encoded message
encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedBase64)
if err != nil {
logger.Log.Error().
Str("encryptedBase64", encryptedBase64).
Err(err).
Msg("Failed to decode base64 string")
return "", fmt.Errorf("failed to decode base64 string: %v", err)
}

Expand All @@ -25,26 +35,45 @@ func DecryptMessage(encryptedBase64 string, privateKey *rsa.PrivateKey) (string,
// Decrypt the message using the private key
decryptedBytes, err := rsa.DecryptOAEP(hash, rand.Reader, privateKey, encryptedBytes, nil)
if err != nil {
logger.Log.Error().
Str("encryptedBase64", encryptedBase64).
Err(err).
Msg("Failed to decrypt message")
return "", fmt.Errorf("failed to decrypt message: %v", err)
}

logger.Log.Info().
Str("decryptedMessage", string(decryptedBytes)).
Msg("Message decrypted successfully")

// Return the decrypted message as a string
return string(decryptedBytes), nil
}

func LoadPrivateKey() (*rsa.PrivateKey, error) {
pemFile := "secret/private.pem"

// Log the private key loading attempt
logger.Log.Info().
Str("pemFile", pemFile).
Msg("Loading private key from PEM file")

// Read the private key file
keyData, err := os.ReadFile(pemFile)
if err != nil {
logger.Log.Error().
Str("pemFile", pemFile).
Err(err).
Msg("Failed to read private key file")
return nil, fmt.Errorf("failed to read private key file: %v", err)
}

// Decode the PEM block
block, _ := pem.Decode(keyData)
if block == nil {
log.Fatalf("Failed to decode PEM block containing private key")
logger.Log.Fatal().
Str("pemFile", pemFile).
Msg("Failed to decode PEM block containing private key")
}

var privateKey interface{}
Expand All @@ -53,17 +82,29 @@ func LoadPrivateKey() (*rsa.PrivateKey, error) {
// PKCS#8 format
privateKey, err = x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
log.Fatalf("Failed to parse PKCS#8 private key: %v", err)
logger.Log.Fatal().
Str("pemFile", pemFile).
Err(err).
Msg("Failed to parse PKCS#8 private key")
}
} else if block.Type == "RSA PRIVATE KEY" {
// PKCS#1 format
privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatalf("Failed to parse PKCS#1 private key: %v", err)
logger.Log.Fatal().
Str("pemFile", pemFile).
Err(err).
Msg("Failed to parse PKCS#1 private key")
}
} else {
log.Fatalf("Unknown PEM block type")
logger.Log.Fatal().
Str("pemFile", pemFile).
Msg("Unknown PEM block type")
}

logger.Log.Info().
Str("pemFile", pemFile).
Msg("Private key loaded successfully")

return privateKey.(*rsa.PrivateKey), nil
}
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ require (
github.com/gorilla/mux v1.8.1
github.com/joho/godotenv v1.5.1
github.com/prometheus/client_golang v1.20.5
github.com/rs/zerolog v1.33.0
)

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
Expand Down
15 changes: 15 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
Expand All @@ -12,8 +14,15 @@ github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
Expand All @@ -22,6 +31,12 @@ github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G
github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
Expand Down
81 changes: 66 additions & 15 deletions handlers/your-cal.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,34 @@ package handlers
import (
"cpe/calendar/decrypt"
"cpe/calendar/ical"
"cpe/calendar/logger"
"cpe/calendar/request"
"fmt"
"log"
"net/http"
"os"
"strings"
)

func Health(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
logger.Log.Info().
Msg("Health check endpoint hit, status OK")
}

// generateICSHandler generates the ICS file and sends it in the response with a given filename
// GenerateICSHandler generates the ICS file and sends it in the response with a given filename
func GenerateICSHandler(w http.ResponseWriter, r *http.Request) {
// Get start and end times from environment variables
start := os.Getenv("START_TIMESTAMP")
end := os.Getenv("END_TIMESTAMP")

// Get separator from environment variable
separator := os.Getenv("SEPARATOR")

filename := "cpe-calendar" + ".ics"
// Log environment variables
logger.Log.Info().
Str("start", start).
Str("end", end).
Str("separator", separator).
Msg("Using environment variables for start, end, and separator")

filename := "cpe-calendar.ics"
calendarName := "CPE Calendar"

// Get query param 'creds'
Expand All @@ -34,33 +39,55 @@ func GenerateICSHandler(w http.ResponseWriter, r *http.Request) {
// Load the RSA private key
privateKey, err := decrypt.LoadPrivateKey()
if err != nil {
log.Fatalf("Error loading private key: %v", err)
logger.Log.Error().
Err(err).
Msg("Error loading private key")
http.Error(w, "Failed to load private key", http.StatusInternalServerError)
return
}

// Decrypt the message
decryptedMessage, err := decrypt.DecryptMessage(cryptedCreds, privateKey)
if err != nil {
log.Printf("Error decrypting message: %v", err)
logger.Log.Error().
Err(err).
Str("cryptedCreds", cryptedCreds).
Msg("Error decrypting message")
http.Error(w, "Invalid credentials", http.StatusBadRequest)
return
}

// Split the decrypted message using the separator
parts := strings.Split(decryptedMessage, separator)
if len(parts) < 2 {
logger.Log.Error().
Str("decryptedMessage", decryptedMessage).
Msg("Invalid credentials format")
http.Error(w, "Invalid credentials format", http.StatusBadRequest)
return
}
username := parts[0]
pass := parts[1]

// Log successful decryption of message
logger.Log.Info().
Str("username", username).
Msg("Credentials decrypted successfully")

// Fetch data from the source
events, err := request.FetchData(start, end, username, pass)
if err != nil {
log.Printf("Failed to fetch data: %v", err)
logger.Log.Error().
Err(err).
Str("username", username).
Msg("Failed to fetch data")
http.Error(w, "Failed to fetch data", http.StatusInternalServerError)
return
}

fmt.Println("Event found", len(events))
logger.Log.Info().
Int("eventsCount", len(events)).
Msg("Fetched events successfully")

// Generate the iCal file with the calendar name
icsContent := ical.GenerateICS(events, calendarName)
Expand All @@ -73,45 +100,69 @@ func GenerateICSHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(icsContent))
}

// ValidateHandler validates the credentials and checks if the login is successful
func ValidateHandler(w http.ResponseWriter, r *http.Request) {
// Get separator from environment variable
separator := os.Getenv("SEPARATOR")

// Get query param 'creds'
cryptedCreds := r.URL.Query().Get("creds")

// Log incoming credentials request
logger.Log.Info().
Str("cryptedCreds", cryptedCreds).
Msg("Validate credentials request received")

// Load the RSA private key
privateKey, err := decrypt.LoadPrivateKey()
if err != nil {
log.Printf("Error loading private key: %v", err)
logger.Log.Error().
Err(err).
Msg("Error loading private key")
http.Error(w, "Failed to load private key", http.StatusInternalServerError)
return
}

// Decrypt the message
decryptedMessage, err := decrypt.DecryptMessage(cryptedCreds, privateKey)
if err != nil {
log.Printf("Error decrypting message: %v", err)
logger.Log.Error().
Err(err).
Str("cryptedCreds", cryptedCreds).
Msg("Error decrypting message")
http.Error(w, "Invalid credentials", http.StatusBadRequest)
return
}

// Split the decrypted message using the separator
parts := strings.Split(decryptedMessage, separator)
if len(parts) < 2 {
logger.Log.Error().
Str("decryptedMessage", decryptedMessage).
Msg("Invalid credentials format")
http.Error(w, "Invalid credentials format", http.StatusBadRequest)
return
}
username := parts[0]
pass := parts[1]

// Fetch data from the source
// Log successful decryption
logger.Log.Info().
Str("username", username).
Msg("Credentials decrypted successfully")

// Fetch data to validate credentials
_, err = request.Login(username, pass)
if err != nil {
log.Printf("Failed to fetch data: %v", err)
logger.Log.Error().
Err(err).
Str("username", username).
Msg("Failed to validate credentials")
w.WriteHeader(http.StatusUnauthorized)
return
}

logger.Log.Info().
Str("username", username).
Msg("User validated successfully")
w.WriteHeader(http.StatusOK)
}
Loading

0 comments on commit 48c7dd4

Please sign in to comment.