Spaces:
Configuration error
Configuration error
Commit ·
ecee9f6
1
Parent(s): 7e1ff30
Deploy files from GitHub repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignore+2-1
- config/config.go+3
- config/database_connection_config.go+10
- controller/controller.go+7
- controller/email/email_create_verification.goAdded+22
- controller/email/email_delete_verification.goAdded+22
- controller/email/email_verify.goAdded+22
- controller/user/user_login_controller.goAdded+20
- controller/user/user_profile_controller.goAdded+24
- controller/user/user_register_controller.goAdded+20
- controller/user/user_update_profile_controller.goAdded+24
- docker-compose.yamlAdded+10
- go.mod+2-1
- go.sum+3-1
- logserror_log.txtAdded+1
- middleware/authentication_middleware.go+6-40
- middleware/response_middleware.go+6
- models/database_orm_model.go+104-16
- models/request_model.go+5
- repositories/account_repository.go+14
- repositories/email_verification_repository.goAdded+49
- router/email_route.goAdded+15
- router/router.go+3-6
- router/user_route.goAdded+16
- services/email_verification_service.goAdded+57
- services/jwt_service.goAdded+45
- services/login_service.go+2-3
- services/register_service.go+1-2
- services/service.go+9-1
- services/user_profile_service.goAdded+37
- space/LICENSEAdded+201
- space/space/.github/workflows/main.yml+1-1
- space/space/space/.github/workflows/main.yml+1-1
- space/space/space/space/.gitignore+2-1
- space/space/space/space/config/config.goAdded+21
- space/space/space/space/config/database_connection_config.goAdded+60
- space/space/space/space/controller/home_controller.goAdded+9
- space/space/space/space/controller/login_controller.goAdded+19
- space/space/space/space/controller/register_controller.goAdded+19
- space/space/space/space/middleware/authentication_middleware.goAdded+104
- space/space/space/space/middleware/response_middleware.goAdded+39
- space/space/space/space/models/authentication_payload_model.goAdded+7
- space/space/space/space/models/database_orm_model.goAdded+31
- space/space/space/space/models/exception_model.goAdded+12
- space/space/space/space/models/model.goAdded+1
- space/space/space/space/models/request_model.goAdded+13
- space/space/space/space/models/response_model.goAdded+19
- space/space/space/space/repositories/account_repository.goAdded+24
- space/space/space/space/repositories/repository.goAdded+113
- space/space/space/space/services/login_service.goAdded+47
1234.envvendor/quzuu-be.exeREADME.md12345.envvendor/quzuu-be.exeREADME.md.qodo
1 unmodified line2345672 unmodified lines1011121314151 unmodified line17181920211 unmodified lineimport ("os""github.com/joho/godotenv")2 unmodified linesvar LOG_PATH stringvar HOST_ADDRESS stringvar HOST_PORT stringfunc init() {godotenv.Load()1 unmodified lineHOST_PORT = os.Getenv("HOST_PORT")TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORTLOG_PATH = os.Getenv("LOG_PATH")// Menampilkan nilai variabel lingkungan}1 unmodified line23456782 unmodified lines111213141516171 unmodified line1920212223241 unmodified lineimport ("os""strconv""github.com/joho/godotenv")2 unmodified linesvar LOG_PATH stringvar HOST_ADDRESS stringvar HOST_PORT stringvar EMAIL_VERIFICATION_DURATION intfunc init() {godotenv.Load()1 unmodified lineHOST_PORT = os.Getenv("HOST_PORT")TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORTLOG_PATH = os.Getenv("LOG_PATH")EMAIL_VERIFICATION_DURATION, _ = strconv.Atoi(os.Getenv("EMAIL_VERIFICATION_DURATION"))// Menampilkan nilai variabel lingkungan}
50 unmodified lines5152535455565750 unmodified lineserr := db.AutoMigrate(&models.Account{},&models.AccountDetails{},)if err != nil {log.Fatal(err)}50 unmodified lines515253545556575859606162636465666750 unmodified lineserr := db.AutoMigrate(&models.Account{},&models.AccountDetails{},&models.EmailVerification{},&models.ExternalAuth{},&models.FCM{},&models.ForgotPassword{},&models.Academy{},&models.AcademyMaterial{},&models.AcademyContent{},&models.AcademyMaterialProgress{},&models.AcademyContentProgress{},)if err != nil {log.Fatal(err)}
18 unmodified lines19202122232418 unmodified lines})func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context, act func()) {cParam, _ := c.Get("accountData")if cParam != nil {18 unmodified lines1920212223242526272829303118 unmodified lines})func (controller *Controller[T1, T2, T3]) HeaderParse(c *gin.Context, act func()) {cParam, _ := c.Get("accountData")if cParam != nil {controller.AccountData = cParam.(models.AccountData)}act()}func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context, act func()) {cParam, _ := c.Get("accountData")if cParam != nil {
12345678910111213141516171819202122package controller
import (
"strconv"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func CreateVerification(c *gin.Context) {
emailVerification := services.EmailVerificationService{}
emailVerificationController := controller.Controller[any, models.EmailVerification, models.EmailVerification]{
Service: &emailVerification.Service,
}
query, _ := c.GetQuery("account_id")
accountId, _ := strconv.Atoi(query)
emailVerificationController.Service.Constructor.AccountID = uint(accountId)
emailVerification.Create()
emailVerificationController.Response(c)
}12345678910111213141516171819202122package controller
import (
"strconv"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func DeleteVerification(c *gin.Context) {
emailVerification := services.EmailVerificationService{}
emailVerificationController := controller.Controller[any, models.EmailVerification, models.EmailVerification]{
Service: &emailVerification.Service,
}
query, _ := c.GetQuery("account_id")
accountId, _ := strconv.Atoi(query)
emailVerificationController.Service.Constructor.AccountID = uint(accountId)
emailVerification.Delete()
emailVerificationController.Response(c)
}12345678910111213141516171819202122package controller
import (
"strconv"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func Verify(c *gin.Context) {
emailVerification := services.EmailVerificationService{}
emailVerificationController := controller.Controller[any, models.EmailVerification, models.EmailVerification]{
Service: &emailVerification.Service,
}
query, _ := c.GetQuery("account_id")
accountId, _ := strconv.Atoi(query)
emailVerificationController.Service.Constructor.AccountID = uint(accountId)
emailVerification.Validate()
emailVerificationController.Response(c)
}1234567891011121314151617181920package user
import (
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func Login(c *gin.Context) {
authentication := services.AuthenticationService{}
loginController := controller.Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{
Service: &authentication.Service,
}
loginController.RequestJSON(c, func() {
loginController.Service.Constructor.Email = loginController.Request.Email
loginController.Service.Constructor.Password = loginController.Request.Password
authentication.Authenticate()
})
}123456789101112131415161718192021222324package user
import (
"fmt"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func Profile(c *gin.Context) {
userProfile := services.UserProfileService{}
userProfileController := controller.Controller[any, services.UserProfileConstructor, models.Account]{
Service: &userProfile.Service,
}
fmt.Println(userProfileController.AccountData)
userProfileController.HeaderParse(c, func() {
userProfileController.Service.Constructor.AccountId = userProfileController.AccountData.UserID
userProfile.Retrieve()
userProfileController.Response(c)
},
)
}1234567891011121314151617181920package user
import (
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func Register(c *gin.Context) {
register := services.RegisterService{}
registerController := controller.Controller[models.RegisterRequest, models.Account, models.Account]{
Service: ®ister.Service,
}
registerController.RequestJSON(c, func() {
registerController.Service.Constructor.Password = registerController.Request.Password
registerController.Service.Constructor.Email = registerController.Request.Email
register.Create()
})
}123456789101112131415161718192021222324package user
import (
"fmt"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func UpdateProfile(c *gin.Context) {
userProfile := services.UserProfileService{}
userUpdateProfileController := controller.Controller[any, services.UserProfileConstructor, models.Account]{
Service: &userProfile.Service,
}
fmt.Println(userUpdateProfileController.AccountData)
userUpdateProfileController.HeaderParse(c, func() {
userUpdateProfileController.Service.Constructor.AccountId = userUpdateProfileController.AccountData.UserID
userProfile.Retrieve()
userUpdateProfileController.Response(c)
},
)
}12345678910services:
postgres:
container_name: postgres
image: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
- POSTGRES_DB=qobiltu
ports:
- 5432:54322 unmodified lines34567837 unmodified lines464748492 unmodified linesgo 1.24.0require (github.com/gin-gonic/gin v1.10.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/joho/godotenv v1.5.137 unmodified linesgolang.org/x/text v0.23.0 // indirectgoogle.golang.org/protobuf v1.36.5 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect)2 unmodified lines345678937 unmodified lines474849502 unmodified linesgo 1.24.0require (github.com/dgrijalva/jwt-go v3.2.0+incompatiblegithub.com/gin-gonic/gin v1.10.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/joho/godotenv v1.5.137 unmodified linesgolang.org/x/text v0.23.0 // indirectgoogle.golang.org/protobuf v1.36.5 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect)
9 unmodified lines10111213141599 unmodified lines1151161171189 unmodified linesgithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=99 unmodified linesgorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=9 unmodified lines101112131415161799 unmodified lines1171181191209 unmodified linesgithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=99 unmodified linesgorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
12025/03/18 21:08:07 Error Log : ERROR: relasi « email_verifications » tidak ada (SQLSTATE 42P01)2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535429 unmodified lines848586878889909192939495969798991001011021031042 unmodified linespackage middlewareimport ("errors""time""api.qobiltu.id/config""api.qobiltu.id/models""github.com/gin-gonic/gin""github.com/golang-jwt/jwt/v5""golang.org/x/crypto/bcrypt")// Define a secret key for signing the JWT tokenvar salt = config.Saltvar secretKey = []byte(salt)// GenerateToken generates a JWT token for the given userfunc GenerateToken(user *models.Account) (string, error) {// Create a new tokentoken := jwt.New(jwt.SigningMethodHS256)// Set claimsclaims := token.Claims.(jwt.MapClaims)claims["id"] = user.Idclaims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Token expires in 24 hours// Sign the token with the secret keytokenString, err := token.SignedString(secretKey)if err != nil {return "", err}return tokenString, nil}// VerifyPassword verifies if the provided password matches the hashed passwordfunc VerifyPassword(hashedPassword, password string) error {err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))if err != nil {return errors.New("invalid password")}return nil}func HashPassword(password string) (string, error) {bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)return string(bytes), err}type CustomClaims struct {jwt.RegisteredClaims29 unmodified lines// fmt.Println("Verify Status :", currAccData.verifyStatus)if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {currAccData.UserID = 0message := "Your session is expired, Please re-Login!"SendJSON401(c, &currAccData.VerifyStatus, &message)c.Abort()return}} else {currAccData.UserID = 0currAccData.VerifyStatus = "no-token"currAccData.ErrVerif = nilmessage := "You have to Login First!"SendJSON401(c, &currAccData.VerifyStatus, &message)c.Abort()return}c.Set("accountData", currAccData)c.Next()}2 unmodified lines345678910111213141516171819202129 unmodified lines51525354555657585960616263646566676869702 unmodified linespackage middlewareimport ("time""api.qobiltu.id/config""api.qobiltu.id/models""api.qobiltu.id/utils""github.com/gin-gonic/gin""github.com/golang-jwt/jwt/v5")var salt = config.Saltvar secretKey = []byte(salt)// VerifyPassword verifies if the provided password matches the hashed passwordtype CustomClaims struct {jwt.RegisteredClaims29 unmodified lines// fmt.Println("Verify Status :", currAccData.verifyStatus)if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {currAccData.UserID = 0utils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "Your session is expired, Please re-Login!"})c.Abort()return} else {c.Set("accountData", currAccData)c.Next()}} else {currAccData.UserID = 0currAccData.VerifyStatus = "no-token"currAccData.ErrVerif = nilutils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "You have to login first!"})c.Abort()return}}
8 unmodified lines91011121314151617181920212223242526272829303132333435363738398 unmodified lines// SendJSON200 sends a JSON response with HTTP status code 200func SendJSON200(c *gin.Context, data interface{}) {c.JSON(http.StatusOK, gin.H{"status": "success", "data": data})}// SendJSON400 sends a JSON response with HTTP status code 400func SendJSON400(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error-status": error_status, "message": message})}// SendJSON401 sends a JSON response with HTTP status code 401func SendJSON401(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error-status": error_status, "message": message})}// SendJSON403 sends a JSON response with HTTP status code 403func SendJSON403(c *gin.Context, message *string) {c.JSON(http.StatusForbidden, gin.H{"status": "error", "message": message})}// SendJSON404 sends a JSON response with HTTP status code 404func SendJSON404(c *gin.Context, message *string) {c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": message})}// SendJSON500 sends a JSON response with HTTP status code 500func SendJSON500(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error-status": error_status, "message": message})}// JSONResponseMiddleware is a middleware that provides functions for sending JSON responses8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344458 unmodified lines// SendJSON200 sends a JSON response with HTTP status code 200func SendJSON200(c *gin.Context, data interface{}) {c.JSON(http.StatusOK, gin.H{"status": "success", "data": data})return}// SendJSON400 sends a JSON response with HTTP status code 400func SendJSON400(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error-status": error_status, "message": message})return}// SendJSON401 sends a JSON response with HTTP status code 401func SendJSON401(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error-status": error_status, "message": message})return}// SendJSON403 sends a JSON response with HTTP status code 403func SendJSON403(c *gin.Context, message *string) {c.JSON(http.StatusForbidden, gin.H{"status": "error", "message": message})return}// SendJSON404 sends a JSON response with HTTP status code 404func SendJSON404(c *gin.Context, message *string) {c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": message})return}// SendJSON500 sends a JSON response with HTTP status code 500func SendJSON500(c *gin.Context, error_status *string, message *string) {c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error-status": error_status, "message": message})return}// JSONResponseMiddleware is a middleware that provides functions for sending JSON responses
6 unmodified lines789101112131415161718192021222324252627282930316 unmodified lines)type Account struct {Id uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`IsEmailVerified bool `json:"is_email_verified"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`}type AccountDetails struct {IDDetail uint `gorm:"primaryKey" json:"id_detail"`Account_id uint `json:"id_account"`Province string `json:"province"`City string `json:"city"`Institution string `json:"institution"`UpdatedAt time.Time `json:"updated_at"`DeletedAt time.Time `json:"deleted_at"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181196 unmodified lines)type Account struct {Id uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`IsEmailVerified bool `json:"is_email_verified"`IsDetailCompleted bool `json:"is_detail_completed"`CreatedAt time.Time `json:"created_at"`DeletedAt *time.Time `json:"deleted_at,omitempty" gorm:"default:null"`}type AccountDetails struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`InitialName string `json:"initial_name"`FullName *string `json:"full_name,omitempty"`DateOfBirth *time.Time `json:"date_of_birth,omitempty"`PlaceOfBirth *string `json:"place_of_birth,omitempty"`Domicile *string `json:"domicile,omitempty"`LastJob *string `json:"last_job,omitempty"`Gender *bool `json:"gender,omitempty"`LastEducation *string `json:"last_education,omitempty"`MaritalStatus *bool `json:"marital_status,omitempty"`Avatar *string `json:"avatar,omitempty"`PhoneNumber *uint `json:"phone_number,omitempty"`}type EmailVerification struct {ID uint `gorm:"primaryKey" json:"id"`Token uint `json:"token"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type ExternalAuth struct {ID uint `gorm:"primaryKey" json:"id"`OauthID string `json:"oauth_id"`AccountID uint `json:"account_id"`OauthProvider string `json:"oauth_provider"`}type FCM struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`FCMToken string `json:"fcm_token"`}type ForgotPassword struct {ID uint `gorm:"primaryKey" json:"id"`UUID uint `json:"uuid"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type Academy struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`Title string `json:"title"`Slug string `json:"slug"`Description string `json:"description"`}type AcademyMaterial struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AcademyID uint `json:"academy_id"`Title string `json:"title"`Slug string `json:"slug"`Description string `json:"description"`}type AcademyContent struct {ID uint `gorm:"primaryKey" json:"id"`UUID uint `json:"uuid"`Title string `json:"title"`Order uint `json:"order"`AcademyMaterialID uint `json:"academy_material_id"`Description string `json:"description"`}type AcademyMaterialProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyMaterialID uint `json:"academy_material_id"`Progress uint `json:"progress"`}type AcademyContentProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyID uint `json:"academy_id"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }
10 unmodified lines11121310 unmodified linesPhone int `json:"phone"`Password string `json:"password" binding:"required"`}10 unmodified lines111213141516171810 unmodified linesPhone int `json:"phone"`Password string `json:"password" binding:"required"`}type CreateEmailVerificationRequest struct {AccountID int `json:"account_id" binding:"required"`}
14 unmodified lines1516171819201 unmodified line22232414 unmodified linesreturn *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,1 unmodified lineCreate(repo)return *repo}14 unmodified lines151617181920212223242526272829301 unmodified line3233343536373814 unmodified linesreturn *repo}func GetAccountbyId(account_id uint) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Id: account_id},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,1 unmodified lineCreate(repo)return *repo}// func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {// repo := Construct// }
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849package repositories
import (
"time"
"api.qobiltu.id/models"
)
func CreateEmailVerification(accountId uint, dueTime time.Time, token uint) Repository[models.EmailVerification, models.EmailVerification] {
repo := Construct[models.EmailVerification, models.EmailVerification](
models.EmailVerification{
AccountID: accountId,
IsExpired: false,
ExpiredAt: dueTime,
Token: token,
},
)
Create(repo)
return *repo
}
func GetEmailVerification(account_id uint, token uint) Repository[models.EmailVerification, models.EmailVerification] {
repo := Construct[models.EmailVerification, models.EmailVerification](
models.EmailVerification{
AccountID: account_id,
IsExpired: false,
Token: token,
},
)
repo.Transactions(
WhereGivenConstructor[models.EmailVerification, models.EmailVerification],
Find[models.EmailVerification, models.EmailVerification],
)
return *repo
}
func DeleteEmailVerification(token uint) Repository[models.EmailVerification, models.EmailVerification] {
repo := Construct[models.EmailVerification, models.EmailVerification](
models.EmailVerification{
Token: token,
},
)
repo.Transactions(
WhereGivenConstructor[models.EmailVerification, models.EmailVerification],
Delete[models.EmailVerification],
)
return *repo
}123456789101112131415package router
import (
EmailController "api.qobiltu.id/controller/email"
"github.com/gin-gonic/gin"
)
func EmailRoute(router *gin.Engine) {
routerGroup := router.Group("/api/v1/email")
{
routerGroup.POST("/verify", EmailController.CreateVerification)
routerGroup.POST("/create-verification", EmailController.CreateVerification)
routerGroup.DELETE("/delete-verification", EmailController.DeleteVerification)
}
}7 unmodified lines891011121314151617187 unmodified linesfunc StartService() {router := gin.Default()routerGroup := router.Group("/api/v1"){routerGroup.GET("/", controller.HomeController)routerGroup.POST("/login", controller.LoginController)routerGroup.POST("/register", controller.RegisterController)}router.Run(config.TCP_ADDRESS)}7 unmodified lines891011121314157 unmodified linesfunc StartService() {router := gin.Default()router.GET("/", controller.HomeController)UserRoute(router)EmailRoute(router)router.Run(config.TCP_ADDRESS)}
12345678910111213141516package router
import (
UserController "api.qobiltu.id/controller/user"
"api.qobiltu.id/middleware"
"github.com/gin-gonic/gin"
)
func UserRoute(router *gin.Engine) {
routerGroup := router.Group("/api/v1/user")
{
routerGroup.POST("/login", UserController.Login)
routerGroup.POST("/register", UserController.Register)
routerGroup.GET("/me", middleware.AuthUser, UserController.Profile)
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package services
import (
"math/rand"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
)
type EmailVerificationService struct {
Service[models.EmailVerification, models.EmailVerification]
}
func (s *EmailVerificationService) Create() {
accountRepo := repositories.GetAccountbyId(s.Constructor.AccountID)
if accountRepo.NoRecord {
s.Error = accountRepo.RowsError
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account data with given credentials!"
return
}
remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.Hour
dueTime := CalculateDueTime(remainingTime)
randomizer := rand.New(rand.NewSource(10))
token := uint(randomizer.Int())
repo := repositories.CreateEmailVerification(s.Constructor.AccountID, dueTime, token)
s.Error = repo.RowsError
s.Result = repo.Result
}
func (s *EmailVerificationService) Validate() {
repo := repositories.GetEmailVerification(s.Constructor.AccountID, s.Constructor.Token)
s.Error = repo.RowsError
if repo.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "Invalid token!"
return
}
s.Result = repo.Result
}
func (s *EmailVerificationService) Delete() {
repo := repositories.DeleteEmailVerification(s.Constructor.Token)
s.Error = repo.RowsError
if repo.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "Invalid token!"
return
}
s.Result = repo.Result
}123456789101112131415161718192021222324252627282930313233343536373839404142434445package services
import (
"errors"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
var salt = config.Salt
var secretKey = []byte(salt)
func GenerateToken(user *models.Account) (string, error) {
// Create a new token
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["id"] = user.Id
claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Token expires in 24 hours
// Sign the token with the secret key
tokenString, err := token.SignedString(secretKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func VerifyPassword(hashedPassword, password string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err != nil {
return errors.New("invalid password")
}
return nil
}
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}2 unmodified lines345678914 unmodified lines242526272829303132333435362 unmodified linesimport ("errors""api.qobiltu.id/middleware""api.qobiltu.id/models""api.qobiltu.id/repositories")14 unmodified liness.Exception.Message = "there is no account with given credentials!"return}if middleware.VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {s.Exception.Unauthorized = trues.Exception.Message = "incorrect password!"return}token, err_tok := middleware.GenerateToken(&accountData.Result)if err_tok != nil {s.Error = errors.Join(s.Error, err_tok)2 unmodified lines34567814 unmodified lines232425262728293031323334352 unmodified linesimport ("errors""api.qobiltu.id/models""api.qobiltu.id/repositories")14 unmodified liness.Exception.Message = "there is no account with given credentials!"return}if VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {s.Exception.Unauthorized = trues.Exception.Message = "incorrect password!"return}token, err_tok := GenerateToken(&accountData.Result)if err_tok != nil {s.Error = errors.Join(s.Error, err_tok)
2 unmodified lines345678910 unmodified lines202122232425262 unmodified linesimport ("errors""api.qobiltu.id/middleware""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid"10 unmodified liness.Exception.Message = "Password must have at least 8 characters!"return}hashed_password, err_hash := middleware.HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwords.Constructor.UUID = uuid.NewV4()2 unmodified lines34567810 unmodified lines192021222324252 unmodified linesimport ("errors""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid"10 unmodified liness.Exception.Message = "Password must have at least 8 characters!"return}hashed_password, err_hash := HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwords.Constructor.UUID = uuid.NewV4()
12345622 unmodified lines293031package servicesimport "api.qobiltu.id/models"type (Services interface {22 unmodified linesConstructor: constructor[0],}}1234567891022 unmodified lines33343536373839package servicesimport ("time""api.qobiltu.id/models")type (Services interface {22 unmodified linesConstructor: constructor[0],}}func CalculateDueTime(duration time.Duration) time.Time {return time.Now().Add(duration)}
12345678910111213141516171819202122232425262728293031323334353637package services
import (
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
)
type UserProfileConstructor struct {
AccountId int
}
type UserProfileService struct {
Service[UserProfileConstructor, models.Account]
}
func (s *UserProfileService) Retrieve() {
userProfile := repositories.GetAccountbyId(uint(s.Constructor.AccountId))
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
s.Result.Password = "SECRET"
s.Result = userProfile.Result
}
func (s *UserProfileService) Update() {
userProfile := repositories.GetAccountbyId(uint(s.Constructor.AccountId))
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
s.Result.Password = "SECRET"
s.Result = userProfile.Result
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 Abdan Hafidz
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.48 unmodified lines4950515248 unmodified linescd spacegit add .git commit -m "Deploy files from GitHub repository" || echo "No changes to commit"git push --force origin main || echo "No changes to push"48 unmodified lines4950515248 unmodified linescd spacegit add .git commit -m "Deploy files from GitHub repository" || echo "No changes to commit"git push origin main || echo "No changes to push"
48 unmodified lines4950515248 unmodified linescd spacegit add .git commit -m "Deploy files from GitHub repository" || echo "No changes to commit"git push origin main || echo "No changes to push"48 unmodified lines4950515248 unmodified linescd spacegit add .git commit -m "Deploy files from GitHub repository" || echo "No changes to commit"git push --force origin main || echo "No changes to push"
123.envvendor/quzuu-be.exe1234.envvendor/quzuu-be.exeREADME.md
123456789101112131415161718192021package config
import (
"os"
"github.com/joho/godotenv"
)
var TCP_ADDRESS string
var LOG_PATH string
var HOST_ADDRESS string
var HOST_PORT string
func init() {
godotenv.Load()
HOST_ADDRESS = os.Getenv("HOST_ADDRESS")
HOST_PORT = os.Getenv("HOST_PORT")
TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORT
LOG_PATH = os.Getenv("LOG_PATH")
// Menampilkan nilai variabel lingkungan
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960package config
import (
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"api.qobiltu.id/models"
"github.com/joho/godotenv"
)
var DB *gorm.DB
var err error
var Salt string
func init() {
godotenv.Load()
if err != nil {
fmt.Println("Gagal membaca file .env")
return
}
os.Setenv("TZ", "Asia/Jakarta")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbName := os.Getenv("DB_NAME")
Salt := os.Getenv("SALT")
dsn := "host=" + dbHost + " user=" + dbUser + " password=" + dbPassword + " dbname=" + dbName + " port=" + dbPort + " sslmode=disable TimeZone=Asia/Jakarta"
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})
if err != nil {
panic(err)
}
if Salt == "" {
Salt = "D3f4u|t"
}
// Call AutoMigrateAll to perform auto-migration
AutoMigrateAll(DB)
}
func AutoMigrateAll(db *gorm.DB) {
// Enable logger to see SQL logs
db.Logger.LogMode(logger.Info)
// Auto-migrate all models
err := db.AutoMigrate(
&models.Account{},
&models.AccountDetails{},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("Migration completed successfully.")
}123456789package controller
import "github.com/gin-gonic/gin"
func HomeController(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Api Qobiltu 2025!",
})
}12345678910111213141516171819package controller
import (
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func LoginController(c *gin.Context) {
authentication := services.AuthenticationService{}
loginController := Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{
Service: &authentication.Service,
}
loginController.RequestJSON(c, func() {
loginController.Service.Constructor.Email = loginController.Request.Email
loginController.Service.Constructor.Password = loginController.Request.Password
authentication.Authenticate()
})
}12345678910111213141516171819package controller
import (
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func RegisterController(c *gin.Context) {
register := services.RegisterService{}
registerController := Controller[models.RegisterRequest, models.Account, models.Account]{
Service: ®ister.Service,
}
registerController.RequestJSON(c, func() {
registerController.Service.Constructor.Password = registerController.Request.Password
registerController.Service.Constructor.Email = registerController.Request.Email
register.Create()
})
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104// auth/auth.go
package middleware
import (
"errors"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
// Define a secret key for signing the JWT token
var salt = config.Salt
var secretKey = []byte(salt)
// GenerateToken generates a JWT token for the given user
func GenerateToken(user *models.Account) (string, error) {
// Create a new token
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["id"] = user.Id
claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Token expires in 24 hours
// Sign the token with the secret key
tokenString, err := token.SignedString(secretKey)
if err != nil {
return "", err
}
return tokenString, nil
}
// VerifyPassword verifies if the provided password matches the hashed password
func VerifyPassword(hashedPassword, password string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err != nil {
return errors.New("invalid password")
}
return nil
}
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
type CustomClaims struct {
jwt.RegisteredClaims
UserID int `json:"id"`
}
func VerifyToken(bearer_token string) (int, string, error) {
// fmt.Println(bearer_token)
token, err := jwt.ParseWithClaims(bearer_token, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
if err != nil {
return 0, "invalid-token", err
}
// Extract the claims
claims, ok := token.Claims.(*CustomClaims)
if !ok || !token.Valid {
return 0, "invalid-token", err
}
if claims.ExpiresAt != nil && claims.ExpiresAt.Time.Before(time.Now()) {
return 0, "expired", err
}
return claims.UserID, "valid", err
}
func AuthUser(c *gin.Context) {
var currAccData models.AccountData
if c.Request.Header["Auth-Bearer-Token"] != nil {
token := c.Request.Header["Auth-Bearer-Token"]
currAccData.UserID, currAccData.VerifyStatus, currAccData.ErrVerif = VerifyToken(token[0])
// fmt.Println("Verify Status :", currAccData.verifyStatus)
if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {
currAccData.UserID = 0
message := "Your session is expired, Please re-Login!"
SendJSON401(c, &currAccData.VerifyStatus, &message)
c.Abort()
return
}
} else {
currAccData.UserID = 0
currAccData.VerifyStatus = "no-token"
currAccData.ErrVerif = nil
message := "You have to Login First!"
SendJSON401(c, &currAccData.VerifyStatus, &message)
c.Abort()
return
}
c.Set("accountData", currAccData)
c.Next()
}123456789101112131415161718192021222324252627282930313233343536373839package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
// SendJSON200 sends a JSON response with HTTP status code 200
func SendJSON200(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, gin.H{"status": "success", "data": data})
}
// SendJSON400 sends a JSON response with HTTP status code 400
func SendJSON400(c *gin.Context, error_status *string, message *string) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error-status": error_status, "message": message})
}
// SendJSON401 sends a JSON response with HTTP status code 401
func SendJSON401(c *gin.Context, error_status *string, message *string) {
c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "error-status": error_status, "message": message})
}
// SendJSON403 sends a JSON response with HTTP status code 403
func SendJSON403(c *gin.Context, message *string) {
c.JSON(http.StatusForbidden, gin.H{"status": "error", "message": message})
}
// SendJSON404 sends a JSON response with HTTP status code 404
func SendJSON404(c *gin.Context, message *string) {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": message})
}
// SendJSON500 sends a JSON response with HTTP status code 500
func SendJSON500(c *gin.Context, error_status *string, message *string) {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error-status": error_status, "message": message})
}
// JSONResponseMiddleware is a middleware that provides functions for sending JSON responses1234567package models
type AccountData struct {
UserID int
VerifyStatus string
ErrVerif error
}12345678910111213141516171819202122232425262728293031package models
import (
"time"
uuid "github.com/satori/go.uuid"
)
type Account struct {
Id uint `gorm:"primaryKey" json:"id"`
UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `
Email string `gorm:"uniqueIndex" json:"email"`
Password string `json:"password"`
IsEmailVerified bool `json:"is_email_verified"`
CreatedAt time.Time `json:"created_at"`
DeletedAt time.Time `json:"deleted_at"`
}
type AccountDetails struct {
IDDetail uint `gorm:"primaryKey" json:"id_detail"`
Account_id uint `json:"id_account"`
Province string `json:"province"`
City string `json:"city"`
Institution string `json:"institution"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
}
// Gorm table name settings
func (Account) TableName() string { return "account" }
func (AccountDetails) TableName() string { return "account_details" }123456789101112package models
type Exception struct {
Unauthorized bool `json:"unauthorized,omitempty"`
BadRequest bool `json:"bad_request,omitempty"`
DataNotFound bool `json:"data_not_found,omitempty"`
InternalServerError bool `json:"internal_server_error,omitempty"`
DataDuplicate bool `json:"data_duplicate,omitempty"`
QueryError bool `json:"query_error,omitempty"`
InvalidPasswordLength bool `json:"invalid_password_length,omitempty"`
Message string `json:"message,omitempty"`
}1package models12345678910111213package models
type LoginRequest struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
type RegisterRequest struct {
Name string `json:"name"`
Email string `json:"email" binding:"required,email"`
Phone int `json:"phone"`
Password string `json:"password" binding:"required"`
}12345678910111213141516171819package models
type SuccessResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Data any `json:"data"`
MetaData any `json:"meta_data"`
}
type ErrorResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Errors Exception `json:"errors"`
MetaData any `json:"meta_data"`
}
type AuthenticatedUser struct {
Account Account `json:"account"`
Token string `json:"token"`
}123456789101112131415161718192021222324package repositories
import (
"api.qobiltu.id/models"
)
func GetAccountbyEmail(email string) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
models.Account{Email: email},
)
repo.Transactions(
WhereGivenConstructor[models.Account, models.Account],
Find[models.Account, models.Account],
)
return *repo
}
func CreateAccount(account models.Account) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
account,
)
Create(repo)
return *repo
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package repositories
import (
"api.qobiltu.id/config"
"gorm.io/gorm"
)
type Repositories interface {
FindAllPaginate()
Where()
Find()
Create()
Update()
CustomQuery()
Delete()
}
type PaginationConstructor struct {
Limit int
Offset int
Filter string
}
type CustomQueryConstructor struct {
SQL string
Values interface{}
}
type Repository[TConstructor any, TResult any] struct {
Constructor TConstructor
Pagination PaginationConstructor
CustomQuery CustomQueryConstructor
Result TResult
Transaction *gorm.DB
RowsCount int
NoRecord bool
RowsError error
}
func Construct[TConstructor any, TResult any](constructor ...TConstructor) *Repository[TConstructor, TResult] {
if len(constructor) == 1 {
return &Repository[TConstructor, TResult]{
Constructor: constructor[0],
Transaction: config.DB,
}
}
return &Repository[TConstructor, TResult]{
Constructor: constructor[0],
Transaction: config.DB.Begin(),
}
}
func (repo *Repository[T1, T2]) Transactions(transactions ...func(*Repository[T1, T2]) *gorm.DB) {
for _, tx := range transactions {
repo.Transaction = tx(repo)
if repo.RowsError != nil {
return
}
}
}
func WhereGivenConstructor[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {
tx := repo.Transaction.Where(&repo.Constructor)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}
func Find[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {
tx := repo.Transaction.Find(&repo.Result)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}
func FinddAllPaginate[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {
tx := repo.Transaction.Limit(repo.Pagination.Limit).Offset(repo.Pagination.Offset).Find(&repo.Result)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}
func Create[T1 any](repo *Repository[T1, T1]) *gorm.DB {
tx := repo.Transaction.Create(&repo.Constructor)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
repo.Result = repo.Constructor
return tx
}
func Update[T1 any](repo *Repository[T1, T1]) *gorm.DB {
tx := repo.Transaction.Save(&repo.Constructor)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}
func Delete[T1 any](repo *Repository[T1, T1]) *gorm.DB {
tx := repo.Transaction.Delete(&repo.Constructor)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}
func CustomQuery[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {
tx := repo.Transaction.Raw(repo.CustomQuery.SQL, repo.CustomQuery.Values).Scan(&repo.Result)
repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
return tx
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package services
import (
"errors"
"api.qobiltu.id/middleware"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
)
type LoginConstructor struct {
Email string
Password string
}
type AuthenticationService struct {
Service[LoginConstructor, models.AuthenticatedUser]
}
func (s *AuthenticationService) Authenticate() {
accountData := repositories.GetAccountbyEmail(s.Constructor.Email)
if accountData.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "there is no account with given credentials!"
return
}
if middleware.VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {
s.Exception.Unauthorized = true
s.Exception.Message = "incorrect password!"
return
}
token, err_tok := middleware.GenerateToken(&accountData.Result)
if err_tok != nil {
s.Error = errors.Join(s.Error, err_tok)
}
accountData.Result.Password = "SECRET"
s.Result = models.AuthenticatedUser{
Account: accountData.Result,
Token: token,
}
s.Error = accountData.RowsError
}
// LoginHandler handles user login.gitignore+2-1
config/config.go+3
config/database_connection_config.go+10
controller/controller.go+7
controller/email/email_create_verification.goAdded+22
controller/email/email_delete_verification.goAdded+22
controller/email/email_verify.goAdded+22
controller/user/user_login_controller.goAdded+20
controller/user/user_profile_controller.goAdded+24
controller/user/user_register_controller.goAdded+20
controller/user/user_update_profile_controller.goAdded+24
docker-compose.yamlAdded+10
go.mod+2-1
go.sum+3-1
logserror_log.txtAdded+1
middleware/authentication_middleware.go+6-40
middleware/response_middleware.go+6
models/database_orm_model.go+104-16
models/request_model.go+5
repositories/account_repository.go+14
repositories/email_verification_repository.goAdded+49
router/email_route.goAdded+15
router/router.go+3-6
router/user_route.goAdded+16
services/email_verification_service.goAdded+57
services/jwt_service.goAdded+45
services/login_service.go+2-3
services/register_service.go+1-2
services/service.go+9-1
services/user_profile_service.goAdded+37
space/LICENSEAdded+201
space/space/.github/workflows/main.yml+1-1
space/space/space/.github/workflows/main.yml+1-1
space/space/space/space/.gitignore+2-1
space/space/space/space/config/config.goAdded+21
space/space/space/space/config/database_connection_config.goAdded+60
space/space/space/space/controller/home_controller.goAdded+9
space/space/space/space/controller/login_controller.goAdded+19
space/space/space/space/controller/register_controller.goAdded+19
space/space/space/space/middleware/authentication_middleware.goAdded+104
space/space/space/space/middleware/response_middleware.goAdded+39
space/space/space/space/models/authentication_payload_model.goAdded+7
space/space/space/space/models/database_orm_model.goAdded+31
space/space/space/space/models/exception_model.goAdded+12
space/space/space/space/models/model.goAdded+1
space/space/space/space/models/request_model.goAdded+13
space/space/space/space/models/response_model.goAdded+19
space/space/space/space/repositories/account_repository.goAdded+24
space/space/space/space/repositories/repository.goAdded+113
space/space/space/space/services/login_service.goAdded+47