Skip to content

Commit

Permalink
feat: ajout de paramètres anchor et username pour FCE (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
fcoufour authored Jun 9, 2021
1 parent 0af0a0f commit dbf4de8
Showing 1 changed file with 60 additions and 3 deletions.
63 changes: 60 additions & 3 deletions fce.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import (
"net/url"
"strconv"
"time"
"io"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
)

// Fce type pour l'API Fiche Commune Entreprise
Expand Down Expand Up @@ -57,14 +63,65 @@ func getFceURL(c *gin.Context) {
c.JSON(500, err.Error())
return
}
fceVisitURL := makeFceVisitURL(siret, fce.Credential)
username := c.GetString("username")
fceVisitURL, err := makeFceVisitURL(siret, fce.Credential, username)
if err != nil {
c.JSON(500, err.Error())
return
}
c.String(200, fceVisitURL)
}

func makeFceVisitURL(siret string, credential string) (string) {
func encrypt(stringToEncrypt string, key string) (string, error) {
bytesToEncrypt := []byte(stringToEncrypt)
keyBytes := []byte(key)
cipherBlock, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
aesGCM, err := cipher.NewGCM(cipherBlock)
if err != nil {
return "", err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
encryptedBytes := aesGCM.Seal(nonce, nonce, bytesToEncrypt, nil)
return fmt.Sprintf("%x", encryptedBytes), nil
}

func decrypt(encryptedString string, key string) (string, error) {
encryptedBytes, _ := hex.DecodeString(encryptedString)
keyBytes := []byte(key)
cipherBlock, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
aesGCM, err := cipher.NewGCM(cipherBlock)
if err != nil {
return "", err
}
nonceSize := aesGCM.NonceSize()
nonce, data := encryptedBytes[:nonceSize], encryptedBytes[nonceSize:]
decryptedBytes, err := aesGCM.Open(nil, nonce, data, nil)
if err != nil {
return "", err
}
return fmt.Sprintf("%s", decryptedBytes), nil
}

func makeFceVisitURL(siret string, credential string, username string) (string, error) {
fceVisitURL := viper.GetString("fceVisitURL") + "establishment/" + siret
params := url.Values{}
params.Add("anchor", "direccte")
params.Add("credential", credential)
apiKey := viper.GetString("apiFceKey")
encryptedUsername, err := encrypt(username, apiKey)
params.Add("username", encryptedUsername)
if err != nil {
return "", err
}
fceVisitURL += "?" + params.Encode()
return fceVisitURL
return fceVisitURL, nil
}

0 comments on commit dbf4de8

Please sign in to comment.