moved db indices to uint

This commit is contained in:
Alex
2024-09-29 20:58:42 +02:00
parent e0cc893493
commit 1ded8bee33
22 changed files with 90 additions and 85 deletions

View File

@@ -49,8 +49,9 @@ func (uc *UserController) UpdateHandler(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "JWT parsing error"})
return
}
jwtUserID := int64((*claims)["user_id"].(float64))
jwtUserID := uint((*claims)["user_id"].(float64))
userRole := int8((*claims)["role_id"].(float64))
if user.ID == 0 {
logger.Error.Printf("No User.ID in request from user with id: %v, aborting", jwtUserID)
c.JSON(http.StatusBadRequest, gin.H{"error": "No user id provided"})
@@ -94,15 +95,15 @@ func (uc *UserController) CurrentUserHandler(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Missing or invalid user ID type"})
return
}
userID, ok := userIDInterface.(int64)
userID, ok := userIDInterface.(uint)
if !ok {
logger.Error.Printf("Error: user_id is not of type int64")
logger.Error.Printf("Error: user_id is not of type uint")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user ID type"})
return
}
user, err := uc.Service.GetUserByID(int64(userID))
user, err := uc.Service.GetUserByID(uint(userID))
if err != nil {
logger.Error.Printf("Error retrieving valid user: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error retrieving user."})

View File

@@ -493,7 +493,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
}
// Create request
req, _ := http.NewRequest("PUT", "/users/"+strconv.FormatInt(user.ID, 10), bytes.NewBuffer(jsonData))
req, _ := http.NewRequest("PUT", "/users/"+strconv.FormatUint(uint64(user.ID), 10), bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
tt.setupCookie(req)

View File

@@ -38,7 +38,7 @@ func Open(dbPath string, adminMail string) error {
var count int64
db.Model(&models.User{}).Count(&count)
if count == 0 {
admin, err := seedAdmin(adminMail)
admin, err := createAdmin(adminMail, createdModel.ID)
if err != nil {
return err
}
@@ -51,7 +51,7 @@ func Open(dbPath string, adminMail string) error {
}
// TODO: Landing page to create an admin
func seedAdmin(userMail string) (*models.User, error) {
func createAdmin(userMail string, subscriptionModelID uint) (*models.User, error) {
passwordBytes := make([]byte, 12)
_, err := rand.Read(passwordBytes)
if err != nil {

View File

@@ -17,7 +17,7 @@ import (
)
type Session struct {
UserID int64
UserID uint
ExpiresAt time.Time
}
@@ -28,27 +28,27 @@ var (
sessions = make(map[string]*Session)
)
func verifyAndRenewToken(tokenString string) (string, int64, error) {
func verifyAndRenewToken(tokenString string) (string, uint, error) {
if tokenString == "" {
logger.Error.Printf("empty tokenstring")
return "", -1, fmt.Errorf("Authorization token is required")
return "", 0, fmt.Errorf("Authorization token is required")
}
token, claims, err := ExtractContentFrom(tokenString)
if err != nil {
logger.Error.Printf("Couldn't parse JWT token String: %v", err)
return "", -1, err
return "", 0, err
}
sessionID := (*claims)["session_id"].(string)
userID := int64((*claims)["user_id"].(float64))
userID := uint((*claims)["user_id"].(float64))
roleID := int8((*claims)["role_id"].(float64))
session, ok := sessions[sessionID]
if !ok {
logger.Error.Printf("session not found")
return "", -1, fmt.Errorf("session not found")
return "", 0, fmt.Errorf("session not found")
}
if userID != session.UserID {
return "", -1, fmt.Errorf("Cookie has been altered, aborting..")
return "", 0, fmt.Errorf("Cookie has been altered, aborting..")
}
if token.Valid {
// token is valid, so we can return the old tokenString
@@ -58,7 +58,7 @@ func verifyAndRenewToken(tokenString string) (string, int64, error) {
if time.Now().After(sessions[sessionID].ExpiresAt) {
delete(sessions, sessionID)
logger.Error.Printf("session expired")
return "", -1, fmt.Errorf("session expired")
return "", 0, fmt.Errorf("session expired")
}
session.ExpiresAt = time.Now().Add(sessionDuration)
@@ -67,7 +67,7 @@ func verifyAndRenewToken(tokenString string) (string, int64, error) {
user := models.User{ID: userID, RoleID: roleID}
newTokenString, err := GenerateToken(config.Auth.JWTSecret, &user, sessionID)
if err != nil {
return "", -1, err
return "", 0, err
}
return newTokenString, session.UserID, nil
@@ -86,7 +86,7 @@ func AuthMiddleware() gin.HandlerFunc {
newToken, userID, err := verifyAndRenewToken(tokenString)
if err != nil {
if err == customerrors.ErrValidToken {
c.Set("user_id", int64(userID))
c.Set("user_id", uint(userID))
c.Next()
return
}
@@ -97,7 +97,7 @@ func AuthMiddleware() gin.HandlerFunc {
}
utils.SetCookie(c, newToken)
c.Set("user_id", int64(userID))
c.Set("user_id", uint(userID))
c.Next()
}
}
@@ -141,7 +141,7 @@ func ExtractContentFrom(tokenString string) (*jwt.Token, *jwt.MapClaims, error)
return token, &claims, nil
}
func UpdateSession(sessionID string, userID int64) {
func UpdateSession(sessionID string, userID uint) {
sessions[sessionID] = &Session{
UserID: userID,
ExpiresAt: time.Now().Add(sessionDuration),

View File

@@ -51,7 +51,7 @@ func TestAuthMiddleware(t *testing.T) {
setupAuth func(r *http.Request)
expectedStatus int
expectNewCookie bool
expectedUserID int64
expectedUserID uint
}{
{
name: "Valid Token",
@@ -169,7 +169,7 @@ func TestAuthMiddleware(t *testing.T) {
assert.Equal(t, tt.expectedStatus, w.Code)
if tt.expectedStatus == http.StatusOK {
var response map[string]int64
var response map[string]uint
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, tt.expectedUserID, response["user_id"])

View File

@@ -5,12 +5,11 @@ import "time"
type BankAccount struct {
CreatedAt time.Time
UpdatedAt time.Time
MandateDateSigned time.Time `gorm:"not null"` // json:"mandate_date_signed"`
Bank string //`json:"bank_name" validate:"omitempty,alphanumunicode,safe_content"`
AccountHolderName string //`json:"account_holder_name" validate:"omitempty,alphaunicode,safe_content"`
IBAN string `gorm:"not null" json:"iban" validate:"required,iban"`
BIC string //`json:"bic" validate:"omitempty,bic"`
MandateReference string `gorm:"not null"` //json:"mandate_reference"`
ID int64 `gorm:"primaryKey"`
UserID int64 //`json:"user_id"`
MandateDateSigned time.Time `gorm:"not null" json:"mandate_date_signed"`
Bank string `json:"bank_name" validate:"omitempty,alphanumunicode,safe_content"`
AccountHolderName string `json:"account_holder_name" validate:"omitempty,alphaunicode,safe_content"`
IBAN string `gorm:"not null" json:"iban" validate:"iban"`
BIC string `json:"bic" validate:"omitempty,bic"`
MandateReference string `gorm:"not null" json:"mandate_reference"`
ID uint `gorm:"primaryKey"`
}

View File

@@ -1,6 +1,8 @@
package models
import "time"
import (
"time"
)
type Consent struct {
CreatedAt time.Time
@@ -9,6 +11,7 @@ type Consent struct {
LastName string `gorm:"not null" json:"last_name" validate:"safe_content"`
Email string `json:"email" validate:"email,safe_content"`
ConsentType string `gorm:"not null" json:"consent_type" validate:"safe_content"`
ID int64 `gorm:"primaryKey"`
UserID int64 `gorm:"not null" json:"user_id"`
ID uint `gorm:"primaryKey"`
User User
UserID uint
}

View File

@@ -9,8 +9,7 @@ type Membership struct {
EndDate time.Time `json:"end_date"`
Status string `json:"status" validate:"safe_content"`
SubscriptionModel SubscriptionModel `gorm:"foreignKey:SubscriptionModelID" json:"subscription_model"`
ParentMembershipID int64 `json:"parent_member_id" validate:"omitempty,omitnil,number"`
SubscriptionModelID int64 `json:"subsription_model_id"`
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
SubscriptionModelID uint `json:"subsription_model_id"`
ParentMembershipID uint `json:"parent_member_id" validate:"omitempty,omitnil,number"`
ID uint `json:"id"`
}

View File

@@ -11,9 +11,9 @@ type SubscriptionModel struct {
Details string `json:"details" validate:"required"`
Conditions string `json:"conditions"`
RequiredMembershipField string `json:"required_membership_field" validate:"membershipField"`
ID int64 `gorm:"primaryKey"`
MonthlyFee float32 `json:"monthly_fee" validate:"required,number,gte=0"`
HourlyRate float32 `json:"hourly_rate" validate:"required,number,gte=0"`
ID uint `json:"id" gorm:"primaryKey"`
MonthlyFee float32 `json:"monthly_fee" validate:"number,gte=0"`
HourlyRate float32 `json:"hourly_rate" validate:"number,gte=0"`
IncludedPerYear int16 `json:"included_hours_per_year" validate:"omitempty,number,gte=0"`
IncludedPerMonth int16 `json:"included_hours_per_month" validate:"omitempty,number,gte=0"`
}

View File

@@ -9,9 +9,7 @@ import (
)
type User struct {
UpdatedAt time.Time
DateOfBirth time.Time `gorm:"not null" json:"date_of_birth" validate:"required,age"`
CreatedAt time.Time
Company string `json:"company" validate:"omitempty,omitnil,safe_content"`
Phone string `json:"phone" validate:"omitempty,omitnil,safe_content"`
Notes *string `json:"notes,safe_content"`
@@ -31,6 +29,7 @@ type User struct {
PaymentStatus int8 `json:"payment_status"`
Status int8 `json:"status"`
RoleID int8 `json:"role_id"`
gorm.Model
}
// BeforeCreate sets the default value for Status

View File

@@ -8,6 +8,6 @@ type Verification struct {
EmailVerifiedAt *time.Time `gorm:"Default:NULL" json:"email_verified_at"`
IDVerifiedAt *time.Time `gorm:"Default:NULL" json:"id_verified_at"`
VerificationToken string `json:"token"`
ID int64 `gorm:"primaryKey"`
UserID int64 `gorm:"unique;" json:"user_id"`
ID uint `gorm:"primaryKey"`
UserID uint `gorm:"unique;" json:"user_id"`
}

View File

@@ -6,12 +6,12 @@ import (
)
type BankAccountRepositoryInterface interface {
CreateBankAccount(account *models.BankAccount) (int64, error)
CreateBankAccount(account *models.BankAccount) (uint, error)
}
type BankAccountRepository struct{}
func (repo *BankAccountRepository) CreateBankAccount(account *models.BankAccount) (int64, error) {
func (repo *BankAccountRepository) CreateBankAccount(account *models.BankAccount) (uint, error) {
result := database.DB.Create(account)
if result.Error != nil {
return 0, result.Error

View File

@@ -6,12 +6,12 @@ import (
)
type ConsentRepositoryInterface interface {
CreateConsent(consent *models.Consent) (int64, error)
CreateConsent(consent *models.Consent) (uint, error)
}
type ConsentRepository struct{}
func (repo *ConsentRepository) CreateConsent(consent *models.Consent) (int64, error) {
func (repo *ConsentRepository) CreateConsent(consent *models.Consent) (uint, error) {
result := database.DB.Create(consent)
if result.Error != nil {

View File

@@ -2,19 +2,20 @@ package repositories
import (
"GoMembership/internal/database"
"gorm.io/gorm"
"GoMembership/internal/models"
)
type MembershipRepositoryInterface interface {
CreateMembership(membership *models.Membership) (int64, error)
FindMembershipByUserID(userID int64) (*models.Membership, error)
CreateMembership(membership *models.Membership) (uint, error)
FindMembershipByUserID(userID uint) (*models.Membership, error)
}
type MembershipRepository struct{}
func (repo *MembershipRepository) CreateMembership(membership *models.Membership) (int64, error) {
func (repo *MembershipRepository) CreateMembership(membership *models.Membership) (uint, error) {
result := database.DB.Create(membership)
if result.Error != nil {
return 0, result.Error
@@ -22,7 +23,7 @@ func (repo *MembershipRepository) CreateMembership(membership *models.Membership
return membership.ID, nil
}
func (repo *MembershipRepository) FindMembershipByUserID(userID int64) (*models.Membership, error) {
func (repo *MembershipRepository) FindMembershipByUserID(userID uint) (*models.Membership, error) {
var membership models.Membership
result := database.DB.First(&membership, userID)

View File

@@ -9,7 +9,7 @@ import (
)
type SubscriptionModelsRepositoryInterface interface {
CreateSubscriptionModel(subscriptionModel *models.SubscriptionModel) (int64, error)
CreateSubscriptionModel(subscriptionModel *models.SubscriptionModel) (uint, error)
GetMembershipModelNames() ([]string, error)
GetModelByName(modelname *string) (*models.SubscriptionModel, error)
GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error)
@@ -17,7 +17,7 @@ type SubscriptionModelsRepositoryInterface interface {
type SubscriptionModelsRepository struct{}
func (sr *SubscriptionModelsRepository) CreateSubscriptionModel(subscriptionModel *models.SubscriptionModel) (int64, error) {
func (sr *SubscriptionModelsRepository) CreateSubscriptionModel(subscriptionModel *models.SubscriptionModel) (uint, error) {
result := database.DB.Create(subscriptionModel)
if result.Error != nil {

View File

@@ -13,19 +13,19 @@ import (
)
type UserRepositoryInterface interface {
CreateUser(user *models.User) (int64, error)
CreateUser(user *models.User) (uint, error)
UpdateUser(user *models.User) (*models.User, error)
GetUsers(where map[string]interface{}) (*[]models.User, error)
GetUserByID(userID *int64) (*models.User, error)
GetUserByID(userID *uint) (*models.User, error)
GetUserByEmail(email string) (*models.User, error)
SetVerificationToken(verification *models.Verification) (int64, error)
IsVerified(userID *int64) (bool, error)
SetVerificationToken(verification *models.Verification) (uint, error)
IsVerified(userID *uint) (bool, error)
GetVerificationOfToken(token *string) (*models.Verification, error)
}
type UserRepository struct{}
func (ur *UserRepository) CreateUser(user *models.User) (int64, error) {
func (ur *UserRepository) CreateUser(user *models.User) (uint, error) {
result := database.DB.Create(user)
if result.Error != nil {
return 0, result.Error
@@ -83,7 +83,7 @@ func (ur *UserRepository) GetUsers(where map[string]interface{}) (*[]models.User
return &users, nil
}
func (ur *UserRepository) GetUserByID(userID *int64) (*models.User, error) {
func (ur *UserRepository) GetUserByID(userID *uint) (*models.User, error) {
var user models.User
result := database.DB.
Preload("Consents").
@@ -113,7 +113,7 @@ func (ur *UserRepository) GetUserByEmail(email string) (*models.User, error) {
return &user, nil
}
func (ur *UserRepository) IsVerified(userID *int64) (bool, error) {
func (ur *UserRepository) IsVerified(userID *uint) (bool, error) {
var user models.User
result := database.DB.Select("status").First(&user, userID)
if result.Error != nil {
@@ -138,7 +138,7 @@ func (ur *UserRepository) GetVerificationOfToken(token *string) (*models.Verific
return &emailVerification, nil
}
func (ur *UserRepository) SetVerificationToken(verification *models.Verification) (int64, error) {
func (ur *UserRepository) SetVerificationToken(verification *models.Verification) (uint, error) {
// Use GORM to insert or update the Verification record
result := database.DB.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "user_id"}},
@@ -146,7 +146,7 @@ func (ur *UserRepository) SetVerificationToken(verification *models.Verification
}).Create(&verification)
if result.Error != nil {
return -1, result.Error
return 0, result.Error
}
return verification.ID, nil

View File

@@ -8,14 +8,14 @@ import (
)
type ConsentServiceInterface interface {
RegisterConsent(consent *models.Consent) (int64, error)
RegisterConsent(consent *models.Consent) (uint, error)
}
type ConsentService struct {
Repo repositories.ConsentRepositoryInterface
}
func (service *ConsentService) RegisterConsent(consent *models.Consent) (int64, error) {
func (service *ConsentService) RegisterConsent(consent *models.Consent) (uint, error) {
consent.CreatedAt = time.Now()
consent.UpdatedAt = time.Now()
return service.Repo.CreateConsent(consent)

View File

@@ -90,7 +90,7 @@ func (s *EmailService) SendWelcomeEmail(user *models.User) error {
FirstName string
MembershipModel string
BASEURL string
MembershipID int64
MembershipID uint
MembershipFee float32
Logo string
WebsiteTitle string
@@ -131,7 +131,7 @@ func (s *EmailService) SendRegistrationNotification(user *models.User) error {
Company string
ZipCode string
BASEURL string
MembershipID int64
MembershipID uint
RentalFee float32
MembershipFee float32
Logo string

View File

@@ -13,9 +13,9 @@ import (
)
type MembershipServiceInterface interface {
RegisterMembership(membership *models.Membership) (int64, error)
FindMembershipByUserID(userID int64) (*models.Membership, error)
RegisterSubscription(subscription *models.SubscriptionModel) (int64, error)
RegisterMembership(membership *models.Membership) (uint, error)
FindMembershipByUserID(userID uint) (*models.Membership, error)
RegisterSubscription(subscription *models.SubscriptionModel) (uint, error)
GetMembershipModelNames() ([]string, error)
GetModelByName(modelname *string) (*models.SubscriptionModel, error)
GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error)
@@ -26,19 +26,19 @@ type MembershipService struct {
SubscriptionRepo repositories.SubscriptionModelsRepositoryInterface
}
func (service *MembershipService) RegisterMembership(membership *models.Membership) (int64, error) {
func (service *MembershipService) RegisterMembership(membership *models.Membership) (uint, error) {
membership.StartDate = time.Now()
return service.Repo.CreateMembership(membership)
}
func (service *MembershipService) FindMembershipByUserID(userID int64) (*models.Membership, error) {
func (service *MembershipService) FindMembershipByUserID(userID uint) (*models.Membership, error) {
return service.Repo.FindMembershipByUserID(userID)
}
// Membership_Subscriptions
func (service *MembershipService) RegisterSubscription(subscription *models.SubscriptionModel) (int64, error) {
func (service *MembershipService) RegisterSubscription(subscription *models.SubscriptionModel) (uint, error) {
if err := validateSubscriptionData(subscription); err != nil {
return -1, err
return 0, err
}
return service.SubscriptionRepo.CreateSubscriptionModel(subscription)
}

View File

@@ -19,12 +19,12 @@ import (
)
type UserServiceInterface interface {
RegisterUser(user *models.User) (int64, string, error)
RegisterUser(user *models.User) (uint, string, error)
GetUserByEmail(email string) (*models.User, error)
GetUserByID(id int64) (*models.User, error)
GetUserByID(id uint) (*models.User, error)
GetUsers(where map[string]interface{}) (*[]models.User, error)
VerifyUser(token *string) (*models.User, error)
UpdateUser(user *models.User) (*models.User, error)
UpdateUser(user *models.User, userRole int8) (*models.User, error)
}
type UserService struct {
@@ -58,8 +58,8 @@ func (service *UserService) UpdateUser(user *models.User) (*models.User, error)
return updatedUser, nil
}
func (service *UserService) RegisterUser(user *models.User) (int64, string, error) {
if err := validateUserData(user); err != nil {
func (service *UserService) RegisterUser(user *models.User) (uint, string, error) {
return http.StatusNotAcceptable, "", err
}
@@ -108,7 +108,7 @@ func (service *UserService) RegisterUser(user *models.User) (int64, string, erro
return id, token, nil
}
func (service *UserService) GetUserByID(id int64) (*models.User, error) {
func (service *UserService) GetUserByID(id uint) (*models.User, error) {
return service.Repo.GetUserByID(&id)
}

View File

@@ -98,5 +98,4 @@ func EncodeQuotedPrintable(s string) string {
// Encode the result into a MIME header
return mime.QEncoding.Encode("UTF-8", buf.String())
}

View File

@@ -33,6 +33,10 @@ var xssPatterns = []*regexp.Regexp{
regexp.MustCompile(`(?i)base64`),
}
func ValidateToTrue(fl validator.FieldLevel) bool {
return true
}
func AgeValidator(fl validator.FieldLevel) bool {
fieldValue := fl.Field()
dateOfBirth := fieldValue.Interface().(time.Time)
@@ -92,17 +96,17 @@ func ValidateRequiredMembershipField(fl validator.FieldLevel) bool {
logger.Info.Println("fieldValue is not a nil pointer")
// Ensure that the fieldValue is an int64
var fieldInt64 int64
if fieldValue.Kind() == reflect.Int64 {
fieldInt64 = fieldValue.Int()
// Ensure that the fieldValue is an uint
var fieldUint uint
if fieldValue.Kind() == reflect.Uint {
fieldUint = uint(fieldValue.Uint())
} else {
return false
}
logger.Info.Println("fieldValue is a int")
var membershipIDs []int64
var membershipIDs []uint
if err := database.DB.Model(&models.Membership{}).Pluck("id", &membershipIDs).Error; err != nil {
logger.Error.Fatalf("Couldn't get SubscriptionModel names: %#v", err)
return false
@@ -112,7 +116,7 @@ func ValidateRequiredMembershipField(fl validator.FieldLevel) bool {
// logger.Info.Printf("FIELD_NAME: %#v\nVALUE: %#v", fieldName, fieldValue)
// Check if the field value is zero (empty)
return slices.Contains(membershipIDs, fieldInt64)
return slices.Contains(membershipIDs, fieldUint)
}
func BICValidator(fl validator.FieldLevel) bool {