Skip to content

Commit

Permalink
Add #244 Integrate policy endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
albinpa committed Oct 15, 2023
1 parent 38af443 commit 04d84d4
Show file tree
Hide file tree
Showing 13 changed files with 849 additions and 163 deletions.
142 changes: 142 additions & 0 deletions src/common/utils.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
package common

import (
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"time"

"github.com/microcosm-cc/bluemonday"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

const (
Expand Down Expand Up @@ -119,6 +128,8 @@ func ParsePaginationQueryParameters(r *http.Request) (startID string, limit int)

if ok {
limit, _ = strconv.Atoi(limits[0])
} else {
limit = 10
}
return
}
Expand Down Expand Up @@ -172,3 +183,134 @@ func Sanitize(s string) string {
p := bluemonday.UGCPolicy()
return p.Sanitize(s)
}

func SemverVersion(version int) string {
major := version
minor := 0
patch := 0

return fmt.Sprintf("%d.%d.%d", major, minor, patch)
}

func UpdateSemverVersion(version string) (string, error) {
// Split the version into major, minor, and patch
versionParts := strings.Split(version, ".")

// Parse the parts into integers
major, err := strconv.Atoi(versionParts[0])
if err != nil {
return version, err
}

// Increment the major version and reset minor and patch to zero
return fmt.Sprintf("%d.0.0", major+1), err
}

func CalculateSHA1(data string) (string, error) {
// Convert the JSON string to bytes
dataBytes := []byte(data)

// Create a new SHA-1 hasher
sha1Hasher := sha1.New()

// Write the data to the hasher
_, err := sha1Hasher.Write(dataBytes)
if err != nil {
return "", err
}

// Get the hash sum
hashSum := sha1Hasher.Sum(nil)

// Convert the hash sum to a hex string
hashHex := hex.EncodeToString(hashSum)

return hashHex, err
}

type Pagination struct {
CurrentPage int `json:"currentPage"`
TotalItems int `json:"totalItems"`
TotalPages int `json:"totalPages"`
Limit int `json:"limit"`
HasPrevious bool `json:"hasPrevious"`
HasNext bool `json:"hasNext"`
}

type PaginationQuery struct {
Filter bson.M
Collection *mongo.Collection
Context context.Context
CurrentPage int
Limit int
Offset int
Count int
}

type PaginatedResult struct {
Items interface{} `json:"items"`
Pagination Pagination `json:"pagination"`
}

func Paginate(query PaginationQuery, resultSlice interface{}) (*PaginatedResult, error) {

// Calculate total items
opts := options.Count().SetSkip(int64(query.Offset))
totalItems, err := query.Collection.CountDocuments(query.Context, query.Filter, opts)

Check failure

Code scanning / CodeQL

Database query built from user-controlled sources High

This query depends on a
user-provided value
.
if err != nil {
return nil, err
}

// Initialize pagination structure
pagination := Pagination{
CurrentPage: query.CurrentPage,
TotalItems: int(totalItems),
Limit: query.Limit,
}

// Calculate total pages
pagination.TotalPages = int(totalItems) / query.Limit
if int(totalItems)%query.Limit > 0 {
pagination.TotalPages++
}

// Set HasNext and HasPrevious
pagination.HasPrevious = query.CurrentPage > 1
pagination.HasNext = query.CurrentPage < pagination.TotalPages

// Query the database
findOpts := options.Find().SetSkip(int64(query.Offset + ((query.CurrentPage - 1) * query.Limit))).SetLimit(int64(query.Limit))
cursor, err := query.Collection.Find(query.Context, query.Filter, findOpts)

Check failure

Code scanning / CodeQL

Database query built from user-controlled sources High

This query depends on a
user-provided value
.
if err != nil {
return nil, err
}
defer cursor.Close(query.Context)

// Decode items
sliceValue := reflect.ValueOf(resultSlice)
if sliceValue.Kind() != reflect.Ptr || sliceValue.Elem().Kind() != reflect.Slice {
return nil, errors.New("resultSlice must be a slice pointer")
}
sliceElem := sliceValue.Elem()
itemTyp := sliceElem.Type().Elem()

for cursor.Next(query.Context) {
itemPtr := reflect.New(itemTyp).Interface()
if err := cursor.Decode(itemPtr); err != nil {
return nil, err
}
sliceElem = reflect.Append(sliceElem, reflect.ValueOf(itemPtr).Elem())
}

if sliceElem.Len() == 0 {
sliceElem = reflect.MakeSlice(sliceElem.Type(), 0, 0)
}
if err := cursor.Err(); err != nil {
return nil, err
}

return &PaginatedResult{
Items: sliceElem.Interface(),
Pagination: pagination,
}, nil
}
7 changes: 7 additions & 0 deletions src/config/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ const (
PolicyId = "policyId"
DataAgreementRecordId = "dataAgreementRecordId"
)

// Schemas
const (
DataAgreement = "dataAgreement"
Policy = "policy"
DataAgreementRecord = "dataAgreementRecord"
)
5 changes: 5 additions & 0 deletions src/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ func Init(config *config.Configuration) error {
return err
}

err = initCollection("policies", []string{"id"}, true)
if err != nil {
return err
}

return nil
}

Expand Down
Loading

0 comments on commit 04d84d4

Please sign in to comment.