Skip to content

Commit

Permalink
Refactor basicvalidators.go and fiskalhr.go to add file readability v…
Browse files Browse the repository at this point in the history
…alidation
  • Loading branch information
arvvoid committed Sep 22, 2024
1 parent 8b81c08 commit d631b27
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 34 deletions.
32 changes: 32 additions & 0 deletions basicvalidators.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package fiskalhrgo

import (
"os"
"path/filepath"
"regexp"
)

Expand Down Expand Up @@ -50,3 +52,33 @@ func ValidateLocationID(locationID string) bool {
validLocationID := regexp.MustCompile(`^[a-zA-Z0-9]{1,20}$`)
return validLocationID.MatchString(locationID)
}

// IsFileReadable checks if the given file exists and is readable.
// It returns true if the file exists and is readable, otherwise false.
func IsFileReadable(filePath string) bool {
// Get the absolute path
absPath, err := filepath.Abs(filePath)
if err != nil {
return false
}

// Check if the file exists
info, err := os.Stat(absPath)
if os.IsNotExist(err) {
return false
}

// Check if the path is a regular file
if !info.Mode().IsRegular() {
return false
}

// Check if the file is readable
file, err := os.Open(absPath)
if err != nil {
return false
}
defer file.Close()

return true
}
28 changes: 11 additions & 17 deletions fiskalhr.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,6 @@ type FiskalEntity struct {
// - centralizedInvoiceNumber: If true, invoice numbers are centralized for the entire location.
// If not, each register device within the location has its own sequence of invoice numbers.
// - demoMode: If true, the entity is in demo mode and will use the demo CIS certificate and endpoint.
// - certManager: If nil, a new CertManager is initialized using the provided certificate path and password.
// Otherwise, the existing CertManager is used as is.
// - chk_expired: If true, the entity creation will fail if the certificate is expired (recommended).
// - certPath, certPassword: These are required if certManager is nil and are used to load the certificate.
//
Expand All @@ -89,7 +87,7 @@ type FiskalEntity struct {
//
// Returns:
// - (*FiskalEntity, error): A pointer to a new FiskalEntity instance with the provided values, or an error if the input is invalid.
func NewFiskalEntity(oib string, sustavPDV bool, locationID string, centralizedInvoiceNumber bool, demoMode bool, cert *certManager, chk_expired bool, cert_config ...string) (*FiskalEntity, error) {
func NewFiskalEntity(oib string, sustavPDV bool, locationID string, centralizedInvoiceNumber bool, demoMode bool, chk_expired bool, certPath string, certPassword string) (*FiskalEntity, error) {

// Check if OIB is valid
if !ValidateOIB(oib) {
Expand All @@ -101,6 +99,11 @@ func NewFiskalEntity(oib string, sustavPDV bool, locationID string, centralizedI
return nil, errors.New("invalid locationID")
}

//check path is valid
if !IsFileReadable(certPath) {
return nil, errors.New("invalid certificate path or file not readable")
}

var CIScert *signatureCheckCIScert
var CIScerterror error

Expand All @@ -114,23 +117,14 @@ func NewFiskalEntity(oib string, sustavPDV bool, locationID string, centralizedI
return nil, fmt.Errorf("failed to get CIS public key and CA pool: %v", CIScerterror)
}

// Initialize a new CertManager if it's nil, otherwise use the provided one
if cert == nil {

// Check if the certificate path and password are provided
if len(cert_config) < 2 {
return nil, errors.New("certificate path and password are required")
}

cert = newCertManager()
err := cert.decodeP12Cert(cert_config[0], cert_config[1])
if err != nil {
return nil, fmt.Errorf("cert decode fail: %v", err)
}
cert := newCertManager()
err := cert.decodeP12Cert(certPath, certPassword)
if err != nil {
return nil, fmt.Errorf("certificate decode fail: %v", err)
}

if !cert.init_ok {
return nil, errors.New("failed to initialize CertManager")
return nil, errors.New("failed to initialize the certificate manager")
}
if cert.certOIB != oib {
return nil, errors.New("OIB does not match the certificate")
Expand Down
33 changes: 16 additions & 17 deletions fiskalhr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"math/rand"
)

var testCert *certManager
var testEntity *FiskalEntity

var certPath string
Expand Down Expand Up @@ -55,7 +54,7 @@ ___________.__ __ .__ ___ _____________ ________
func TestLoadCert(t *testing.T) {
t.Logf("Testing certificate loading...")

testCert = newCertManager()
testCert := newCertManager()
// Load the certificate
err := testCert.decodeP12Cert(certPath, certPassword)

Expand Down Expand Up @@ -90,6 +89,13 @@ func TestLoadCert(t *testing.T) {

func TestDisplayCertInfo(t *testing.T) {
t.Logf("Testing certificate display...")
testCert := newCertManager()
// Load the certificate
err := testCert.decodeP12Cert(certPath, certPassword)

if err != nil {
t.Fatalf("Failed to load certificate: %v", err)
}

t.Log("Cert Text:")
// Display the certificate information
Expand All @@ -107,7 +113,13 @@ func TestDisplayCertInfo(t *testing.T) {

func TestExtractOIB(t *testing.T) {
t.Logf("Testing OIB extraction...")
testCert := newCertManager()
// Load the certificate
err := testCert.decodeP12Cert(certPath, certPassword)

if err != nil {
t.Fatalf("Failed to load certificate: %v", err)
}
// Reuse the loaded certManager to extract the OIB
oib, err := testCert.getCertOIB()
if err != nil {
Expand All @@ -126,23 +138,10 @@ func TestExtractOIB(t *testing.T) {
}

// Test without passing a loaded certificate
func TestNewFiskalEntityStandalone(t *testing.T) {
t.Logf("Testing FiskalEntity with cert init creation...")
testEntityStandalone, err := NewFiskalEntity(testOIB, true, "TEST3", true, true, nil, true, certPath, certPassword)
if err != nil {
t.Fatalf("Failed: %v", err)
}
if !testEntityStandalone.cert.init_ok {
t.Fatalf("Failed to initialize CertManager")
}
}

// Test with passing the loaded certificate
// Also init global testEntity for other tests
func TestNewFiskalEntity(t *testing.T) {
t.Logf("Testing FiskalEntity with passing cert manager creation...")
t.Logf("Testing FiskalEntity with cert init creation...")
var err error
testEntity, err = NewFiskalEntity(testOIB, true, "TEST3", true, true, testCert, true)
testEntity, err = NewFiskalEntity(testOIB, true, "TEST3", true, true, true, certPath, certPassword)
if err != nil {
t.Fatalf("Failed: %v", err)
}
Expand Down

0 comments on commit d631b27

Please sign in to comment.