Spaces:
Configuration error
Configuration error
Commit ·
6596fcc
1
Parent(s): 73f8fa4
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)
- repositories/AccountRepository.go+2-2
- repositories/repositories.go-7
- services/LoginService.go+1-1
- services/RegisterService.go+2
- space/go.mod+1
- space/go.sum+2
- space/models/DatabaseModel.go+17-5
- space/repositories/AccountRepository.go-3
- space/services/RegisterService.go+3-2
- space/space/controller/LoginController.go+5-5
- space/space/controller/RegisterController.go+5-5
- space/space/controller/controller.go+5-2
- space/space/models/DatabaseModel.go+1-1
- space/space/repositories/AccountRepository.go+7-2
- space/space/repositories/repositories.go+18-5
- space/space/services/LoginService.go+1-2
- space/space/services/RegisterService.go-4
- space/space/space/controller/LoginController.go+1-1
- space/space/space/controller/controller.go+2
- space/space/space/middleware/AuthMiddleware.go+1-1
- space/space/space/models/DatabaseModel.go+5-8
- space/space/space/models/ResponseModel.go+5
- space/space/space/repositories/AccountRepository.go+3-5
- space/space/space/repositories/repositories.go+32-21
- space/space/space/services/LoginService.go+14-2
- space/space/space/services/RegisterService.go+6-1
- space/space/space/space/space/Dockerfile+2-2
- space/space/space/space/space/space/controller/HomeController.go+1-1
- space/space/space/space/space/space/router/router.go+2-1
- space/space/space/space/space/space/space/.env.exampleAdded+9
- space/space/space/space/space/space/space/.github/workflows/main.ymlAdded+52
- space/space/space/space/space/space/space/.gitignoreAdded+3
- space/space/space/space/space/space/space/DockerfileAdded+30
- space/space/space/space/space/space/space/config/DatabaseConfig.goAdded+60
- space/space/space/space/space/space/space/config/EnvConfig.goAdded+16
- space/space/space/space/space/space/space/controller/HomeController.goAdded+9
- space/space/space/space/space/space/space/controller/LoginController.goAdded+19
- space/space/space/space/space/space/space/controller/RegisterController.goAdded+19
- space/space/space/space/space/space/space/controller/controller.goAdded+53
- space/space/space/space/space/space/space/go.modAdded+48
- space/space/space/space/space/space/space/go.sumAdded+138
- space/space/space/space/space/space/space/logs/error_log.txtAdded
- space/space/space/space/space/space/space/logs/security_log.txtAdded
- space/space/space/space/space/space/space/main.goAdded+14
- space/space/space/space/space/space/space/middleware/AuthMiddleware.goAdded+103
- space/space/space/space/space/space/space/middleware/middleware.goAdded+31
- space/space/space/space/space/space/space/middleware/responseMiddleware.goAdded+39
- space/space/space/space/space/space/space/models/AuthModel.goAdded+7
- space/space/space/space/space/space/space/models/DatabaseModel.goAdded+30
- space/space/space/space/space/space/space/models/ExceptionModel.goAdded+11
3 unmodified lines4567891011123 unmodified lines"go-dp.abdanhafidz.com/models")func GetAccountbyEmailPassword(email string, password string) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],3 unmodified lines4567891011123 unmodified lines"go-dp.abdanhafidz.com/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],
1234567842 unmodified lines515253545556575859606162636465package repositoriesimport ("strconv""go-dp.abdanhafidz.com/config""gorm.io/gorm")42 unmodified lines}}func (repo *Repository[T1, T2]) Transactions(transactions ...func(*Repository[T1, T2]) *gorm.DB) {i := 1for _, tx := range transactions {repo.Transaction = tx(repo)if repo.RowsError != nil {repo.Transaction.Rollback()return} else {repo.Transaction.SavePoint("Save Point : " + strconv.Itoa(i))repo.Transaction.Commit()}}}12345642 unmodified lines49505152535455565758package repositoriesimport ("go-dp.abdanhafidz.com/config""gorm.io/gorm")42 unmodified lines}}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}}}
17 unmodified lines1819202122232417 unmodified lines}func (s *AuthenticationService) Authenticate() {accountData := repositories.GetAccountbyEmailPassword(s.Constructor.Email, s.Constructor.Password)if accountData.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "there is no account with given credentials!"17 unmodified lines1819202122232417 unmodified lines}func (s *AuthenticationService) Authenticate() {accountData := repositories.GetAccountbyEmail(s.Constructor.Email)if accountData.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "there is no account with given credentials!"
2 unmodified lines3456788 unmodified lines1718192021222 unmodified linesimport ("errors""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models""go-dp.abdanhafidz.com/repositories"8 unmodified lineshashed_password, err_hash := middleware.HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = true2 unmodified lines34567898 unmodified lines181920212223242 unmodified linesimport ("errors"uuid "github.com/satori/go.uuid""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models""go-dp.abdanhafidz.com/repositories"8 unmodified lineshashed_password, err_hash := middleware.HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwords.Constructor.UUID = uuid.NewV4()accountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = true
35 unmodified lines36373839404135 unmodified linesgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.1.0 // indirectgithub.com/rogpeppe/go-internal v1.11.0 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.11 // indirectgolang.org/x/arch v0.6.0 // indirect35 unmodified lines3637383940414235 unmodified linesgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.1.0 // indirectgithub.com/rogpeppe/go-internal v1.11.0 // indirectgithub.com/satori/go.uuid v1.2.0 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.11 // indirectgolang.org/x/arch v0.6.0 // indirect
78 unmodified lines79808182838478 unmodified linesgithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=78 unmodified lines798081828384858678 unmodified linesgithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
1 unmodified line234567891011121314156 unmodified lines2223242526271 unmodified lineimport ("time")type Account struct {Id uint `gorm:"primaryKey" json:"id"`Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`}type AccountDetails struct {6 unmodified linesDeletedAt time.Time `json:"deleted_at"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }1 unmodified line23456789101112131415161718196 unmodified lines26272829303132333435363738391 unmodified lineimport ("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 {6 unmodified linesDeletedAt time.Time `json:"deleted_at"`}type EmailVerification struct {Id int `gorm:"primaryKey" json:"id"`AccountId int `json:"account_id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }
123456781 unmodified line10111213141516package repositoriesimport ("fmt""go-dp.abdanhafidz.com/models")1 unmodified linerepo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)fmt.Println(repo.Constructor)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],1234561 unmodified line8910111213package repositoriesimport ("go-dp.abdanhafidz.com/models")1 unmodified linerepo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],
13 unmodified lines141516171819205 unmodified lines2627282930313213 unmodified lines}func (s *RegisterService) Create() {hashed_password, _ := middleware.HashPassword(s.Constructor.Password)s.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {5 unmodified liness.Exception.Message = "Bad request!"return}s.Result = accountCreated.Results.Result.Password = "SECRET"}13 unmodified lines14151617181920215 unmodified lines2728293031323313 unmodified lines}func (s *RegisterService) Create() {hashed_password, err_hash := middleware.HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {5 unmodified liness.Exception.Message = "Bad request!"return}s.Error = accountCreated.RowsErrors.Result = accountCreated.Results.Result.Password = "SECRET"}
10 unmodified lines11121314151617181910 unmodified linesloginController := Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{Service: &authentication.Service,}loginController.RequestJSON(c)loginController.Service.Constructor.Email = loginController.Request.EmailloginController.Service.Constructor.Password = loginController.Request.Passwordauthentication.Authenticate()loginController.Response(c)}10 unmodified lines11121314151617181910 unmodified linesloginController := Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{Service: &authentication.Service,}loginController.RequestJSON(c, func() {loginController.Service.Constructor.Email = loginController.Request.EmailloginController.Service.Constructor.Password = loginController.Request.Passwordauthentication.Authenticate()})}
10 unmodified lines11121314151617181910 unmodified linesregisterController := Controller[models.RegisterRequest, models.Account, models.Account]{Service: ®ister.Service,}registerController.RequestJSON(c)registerController.Service.Constructor.Password = registerController.Request.PasswordregisterController.Service.Constructor.Email = registerController.Request.Emailregister.Create()registerController.Response(c)}10 unmodified lines11121314151617181910 unmodified linesregisterController := Controller[models.RegisterRequest, models.Account, models.Account]{Service: ®ister.Service,}registerController.RequestJSON(c, func() {registerController.Service.Constructor.Password = registerController.Request.PasswordregisterController.Service.Constructor.Email = registerController.Request.Emailregister.Create()})}
18 unmodified lines192021222324252 unmodified lines28293031323334353618 unmodified lines})func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context) {cParam, _ := c.Get("accountData")if cParam != nil {controller.AccountData = cParam.(models.AccountData)2 unmodified linesif errBinding != nil {utils.ResponseFAIL(c, 400, models.Exception{BadRequest: true,Message: "Invalid Request Type",})return}}func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) {18 unmodified lines192021222324252 unmodified lines28293031323334353637383918 unmodified lines})func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context, act func()) {cParam, _ := c.Get("accountData")if cParam != nil {controller.AccountData = cParam.(models.AccountData)2 unmodified linesif errBinding != nil {utils.ResponseFAIL(c, 400, models.Exception{BadRequest: true,Message: "Invalid Request!, recheck your request, there's must be some problem about required parameter or type parameter",})return} else {act()controller.Response(c)}}func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) {
5 unmodified lines67891011125 unmodified linestype Account struct {Id uint `gorm:"primaryKey" json:"id"`Email string `gorm:"primaryKey" json:"email"`Password string `json:"password"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`5 unmodified lines67891011125 unmodified linestype Account struct {Id uint `gorm:"primaryKey" json:"id"`Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`
1234561 unmodified line8910111213141 unmodified line16171819202122package repositoriesimport ("go-dp.abdanhafidz.com/models")1 unmodified linerepo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)Find(repo)return *repo}1 unmodified linerepo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}123456781 unmodified line10111213141516171819201 unmodified line222324252627package repositoriesimport ("fmt""go-dp.abdanhafidz.com/models")1 unmodified linerepo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)fmt.Println(repo.Constructor)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}1 unmodified linerepo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}
12345649 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107package repositoriesimport ("go-dp.abdanhafidz.com/config""gorm.io/gorm")49 unmodified linesrepo.Transaction.Rollback()return} else {repo.Transaction.SavePoint("Save Point : " + string(i))repo.Transaction.Commit()}}}func WhereGivenConstructor[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {tx := repo.Transaction.Where(&repo.Constructor)repo.RowsError = repo.Transaction.Errorrepo.RowsError = tx.Errorreturn tx}func Find[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {tx := repo.Transaction.Find(&repo.Result)repo.RowsError = repo.Transaction.Errorrepo.RowsError = tx.Errorreturn 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.RowsError = tx.Errorreturn tx}func Create[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Create(&repo.Constructor)repo.Result = repo.Constructorrepo.RowsError = tx.Errorreturn tx}func Update[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Save(&repo.Constructor)repo.Result = repo.Constructorrepo.RowsError = tx.Errorreturn tx}func Delete[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Delete(&repo.Constructor)repo.RowsError = tx.Errorreturn 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.RowsError = tx.Errorreturn tx}1234567849 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120package repositoriesimport ("strconv""go-dp.abdanhafidz.com/config""gorm.io/gorm")49 unmodified linesrepo.Transaction.Rollback()return} else {repo.Transaction.SavePoint("Save Point : " + strconv.Itoa(i))repo.Transaction.Commit()}}}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 == 0repo.RowsError = tx.Errorreturn 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 == 0repo.RowsError = tx.Errorreturn 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 == 0repo.RowsError = tx.Errorreturn 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 == 0repo.RowsError = tx.Errorrepo.Result = repo.Constructorreturn 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 == 0repo.RowsError = tx.Errorreturn 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 == 0repo.RowsError = tx.Errorreturn 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 == 0repo.RowsError = tx.Errorreturn tx}
20 unmodified lines2122232425262728293020 unmodified linesaccountData := repositories.GetAccountbyEmailPassword(s.Constructor.Email, s.Constructor.Password)if accountData.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "there is no account with given email!"return}if middleware.VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {s.Exception.Unauthorized = trues.Exception.Message = "incorrect password!"20 unmodified lines21222324252627282920 unmodified linesaccountData := repositories.GetAccountbyEmailPassword(s.Constructor.Email, s.Constructor.Password)if accountData.NoRecord {s.Exception.DataNotFound = trues.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!"
1 unmodified line23456789 unmodified lines1819202122232425261 unmodified lineimport ("errors""fmt""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models"9 unmodified lineshashed_password, _ := middleware.HashPassword(s.Constructor.Password)s.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)// fmt.Println("Error :", accountCreated.RowsError.Error())fmt.Println(errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey))if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"1 unmodified line2345679 unmodified lines1718192021221 unmodified lineimport ("errors""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models"9 unmodified lineshashed_password, _ := middleware.HashPassword(s.Constructor.Password)s.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"
7 unmodified lines8910111213147 unmodified linesfunc LoginController(c *gin.Context) {authentication := services.AuthenticationService{}loginController := Controller[models.LoginRequest, services.LoginConstructor, models.Account]{Service: &authentication.Service,}loginController.RequestJSON(c)7 unmodified lines8910111213147 unmodified linesfunc LoginController(c *gin.Context) {authentication := services.AuthenticationService{}loginController := Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{Service: &authentication.Service,}loginController.RequestJSON(c)
40 unmodified lines41424344454640 unmodified linesMessage: "Internal Server Error",})utils.LogError(controller.Service.Error)case controller.Service.Exception.Unauthorized:utils.ResponseFAIL(c, 401, controller.Service.Exception)case controller.Service.Exception.DataNotFound:40 unmodified lines414243444546474840 unmodified linesMessage: "Internal Server Error",})utils.LogError(controller.Service.Error)case controller.Service.Exception.DataDuplicate:utils.ResponseFAIL(c, 400, controller.Service.Exception)case controller.Service.Exception.Unauthorized:utils.ResponseFAIL(c, 401, controller.Service.Exception)case controller.Service.Exception.DataNotFound:
24 unmodified lines2526272829303124 unmodified lines// Set claimsclaims := token.Claims.(jwt.MapClaims)claims["id"] = user.IDAccountclaims["exp"] = time.Now().Add(time.Hour * 24).Unix() // Token expires in 24 hours// Sign the token with the secret key24 unmodified lines2526272829303124 unmodified lines// 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 key
4 unmodified lines567891011121314151617184 unmodified lines)type Account struct {IDAccount uint `gorm:"primaryKey" json:"id_account"`Name string `json:"name"`Username string `json:"username"`Email string `json:"email"`Password string `json:"password"`PhoneNumber int `json:"phone_number"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`}type AccountDetails struct {4 unmodified lines567891011121314154 unmodified lines)type Account struct {Id uint `gorm:"primaryKey" json:"id"`Email string `gorm:"primaryKey" json:"email"`Password string `json:"password"`CreatedAt time.Time `json:"created_at"`DeletedAt time.Time `json:"deleted_at"`}type AccountDetails struct {
1package models123456package modelstype AuthenticatedUser struct {Account Account `json:"account"`Token string `json:"token"`}
123456789101112131415161718192021222324package repositoriesimport ("fmt""go-dp.abdanhafidz.com/models")func GetAccountbyEmailPassword(username string, password string) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Username: username, Password: password},)Find(repo)return *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {fmt.Println(account)repo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}12345678910111213141516171819202122package repositoriesimport ("go-dp.abdanhafidz.com/models")func GetAccountbyEmailPassword(email string, password string) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Email: email, Password: password},)Find(repo)return *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}
1234567830 unmodified lines394041424344455 unmodified lines51525354555657585960613 unmodified lines6566676869707172737475767778798081828384858687888990919293949596package repositoriesimport ("fmt""go-dp.abdanhafidz.com/config""gorm.io/gorm")30 unmodified lines}func Construct[TConstructor any, TResult any](constructor ...TConstructor) *Repository[TConstructor, TResult] {fmt.Println("Len = ", len(constructor))if len(constructor) == 1 {return &Repository[TConstructor, TResult]{Constructor: constructor[0],5 unmodified linesTransaction: config.DB.Begin(),}}func (repo *Repository[T1, T2]) Transactions(transactions ...func(*Repository[T1, T2])) {i := 1for _, tx := range transactions {tx(repo)repo.RowsError = repo.Transaction.Errorif repo.RowsError != nil {repo.Transaction.Rollback()return3 unmodified lines}}}func WhereGivenConstructor[T1 any, T2 any](repo *Repository[T1, T2]) {repo.Transaction.Where(&repo.Constructor)}func Find[T1 any, T2 any](repo *Repository[T1, T2]) {repo.Transaction.Find(&repo.Result)}func FinddAllPaginate[T1 any, T2 any](repo *Repository[T1, T2]) {repo.Transaction.Limit(repo.Pagination.Limit).Offset(repo.Pagination.Offset).Find(&repo.Result)}func Create[T1 any](repo *Repository[T1, T1]) {fmt.Println(repo.Constructor)repo.Transaction.Create(&repo.Constructor)repo.Result = repo.Constructor}func Update[T1 any](repo *Repository[T1, T1]) {repo.Transaction.Save(&repo.Constructor)repo.Result = repo.Constructor}func Delete[T1 any](repo *Repository[T1, T1]) {repo.Transaction.Delete(&repo.Constructor)}func CustomQuery[T1 any, T2 any](repo *Repository[T1, T2]) {repo.Transaction.Raw(repo.CustomQuery.SQL, repo.CustomQuery.Values).Scan(&repo.Result)}12345630 unmodified lines3738394041425 unmodified lines484950515253545556573 unmodified lines616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107package repositoriesimport ("go-dp.abdanhafidz.com/config""gorm.io/gorm")30 unmodified lines}func Construct[TConstructor any, TResult any](constructor ...TConstructor) *Repository[TConstructor, TResult] {if len(constructor) == 1 {return &Repository[TConstructor, TResult]{Constructor: constructor[0],5 unmodified linesTransaction: config.DB.Begin(),}}func (repo *Repository[T1, T2]) Transactions(transactions ...func(*Repository[T1, T2]) *gorm.DB) {i := 1for _, tx := range transactions {repo.Transaction = tx(repo)if repo.RowsError != nil {repo.Transaction.Rollback()return3 unmodified lines}}}func WhereGivenConstructor[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {tx := repo.Transaction.Where(&repo.Constructor)repo.RowsError = repo.Transaction.Errorrepo.RowsError = tx.Errorreturn tx}func Find[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {tx := repo.Transaction.Find(&repo.Result)repo.RowsError = repo.Transaction.Errorrepo.RowsError = tx.Errorreturn 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.RowsError = tx.Errorreturn tx}func Create[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Create(&repo.Constructor)repo.Result = repo.Constructorrepo.RowsError = tx.Errorreturn tx}func Update[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Save(&repo.Constructor)repo.Result = repo.Constructorrepo.RowsError = tx.Errorreturn tx}func Delete[T1 any](repo *Repository[T1, T1]) *gorm.DB {tx := repo.Transaction.Delete(&repo.Constructor)repo.RowsError = tx.Errorreturn 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.RowsError = tx.Errorreturn tx}
1234565 unmodified lines1213141516171810 unmodified lines29303132333435package servicesimport ("go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models""go-dp.abdanhafidz.com/repositories"5 unmodified lines}type AuthenticationService struct {Service[LoginConstructor, models.Account]}func (s *AuthenticationService) Authenticate() {10 unmodified linesreturn}s.Result = accountData.Results.Error = accountData.RowsError}123456785 unmodified lines1415161718192010 unmodified lines3132333435363738394041424344454647package servicesimport ("errors""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models""go-dp.abdanhafidz.com/repositories"5 unmodified lines}type AuthenticationService struct {Service[LoginConstructor, models.AuthenticatedUser]}func (s *AuthenticationService) Authenticate() {10 unmodified linesreturn}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}
1 unmodified line2345679 unmodified lines1718192021222324252627282930311 unmodified lineimport ("errors""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models"9 unmodified lineshashed_password, _ := middleware.HashPassword(s.Constructor.Password)s.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "There is account registered with given data!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}s.Result = accountCreated.Results.Result.Password = "SECRET"}1 unmodified line23456789 unmodified lines181920212223242526272829303132333435361 unmodified lineimport ("errors""fmt""go-dp.abdanhafidz.com/middleware""go-dp.abdanhafidz.com/models"9 unmodified lineshashed_password, _ := middleware.HashPassword(s.Constructor.Password)s.Constructor.Password = hashed_passwordaccountCreated := repositories.CreateAccount(s.Constructor)// fmt.Println("Error :", accountCreated.RowsError.Error())fmt.Println(errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey))if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}s.Result = accountCreated.Results.Result.Password = "SECRET"}
20 unmodified lines212223242526272820 unmodified linesecho "DB_NAME=postgres" >> .env && \echo "HOST_ADDRESS = 0.0.0.0" >> .env && \echo "HOST_PORT = 7860" >> .env && \echo "SALT=NZNZtY7dNPz8l0dWINJZLKafWaJrql1s" >> .envecho "LOG_PATH = logs"# Build aplikasiRUN go build -o main .20 unmodified lines212223242526272820 unmodified linesecho "DB_NAME=postgres" >> .env && \echo "HOST_ADDRESS = 0.0.0.0" >> .env && \echo "HOST_PORT = 7860" >> .env && \echo "SALT=NZNZtY7dNPz8l0dWINJZLKafWaJrql1s" >> .env && \echo "LOG_PATH = logs" >> .env# Build aplikasiRUN go build -o main .
3 unmodified lines4567893 unmodified linesfunc HomeController(c *gin.Context) {c.JSON(200, gin.H{"message": "Api Quzuu Backend 2024!",})}3 unmodified lines4567893 unmodified linesfunc HomeController(c *gin.Context) {c.JSON(200, gin.H{"message": "Api Qobiltu 2025!",})}
7 unmodified lines891011121314157 unmodified linesfunc StartService() {router := gin.Default()routerGroup := router.Group("/api"){routerGroup.POST("/login", controller.LoginController)routerGroup.POST("/register", controller.RegisterController)}7 unmodified lines89101112131415167 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)}
123456789DB_HOST =DB_USER =DB_PASSWORD =DB_PORT =DB_NAME =SALT =HOST_ADDRESS = HOST_PORT = LOG_PATH = logs12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152name: Deploy to Development via Huggingface
on: push: branches: - main
jobs: deploy-to-huggingface: runs-on: ubuntu-latest
steps: # Checkout repository - name: Checkout Repository uses: actions/checkout@v3
# Setup Git - name: Setup Git for Huggingface run: | git config --global user.email "abdan.hafidz@gmail.com" git config --global user.name "abdanhafidz"
# Clone Huggingface Space Repository - name: Clone Huggingface Space env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | git clone https://huggingface.co/spaces/lifedebugger/api-qobiltu-dev space
# Update Git Remote URL and Pull Latest Changes - name: Update Remote and Pull Changes env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | cd space git remote set-url origin https://lifedebugger:$HF_TOKEN@huggingface.co/spaces/lifedebugger/api-qobiltu-dev git pull origin main || echo "No changes to pull"
# Copy Files to Huggingface Space - name: Copy Files to Space run: | rsync -av --exclude='.git' ./ space/
# Commit and Push to Huggingface Space - name: Commit and Push to Huggingface env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | cd space git add . git commit -m "Deploy files from GitHub repository" || echo "No changes to commit" git push origin main || echo "No changes to push"123.env
vendor/
quzuu-be.exe123456789101112131415161718192021222324252627282930# Gunakan image dasar Golang versi 1.21.6
FROM golang:1.21.6
# Set working directory
WORKDIR /app
# Copy go.mod dan go.sum
COPY go.mod go.sum ./
# Download dependencies
RUN go mod download
# Copy seluruh kode
COPY . .
# Buat file .env dengan variabel environment yang dibutuhkan
RUN echo "DB_HOST=aws-0-ap-southeast-1.pooler.supabase.com" >> .env && \
echo "DB_USER=postgres.rdscploxoikqsevhduii" >> .env && \
echo "DB_PASSWORD=Qobiltu12233334444" >> .env && \
echo "DB_PORT=5432" >> .env && \
echo "DB_NAME=postgres" >> .env && \
echo "HOST_ADDRESS = 0.0.0.0" >> .env && \
echo "HOST_PORT = 7860" >> .env && \
echo "SALT=NZNZtY7dNPz8l0dWINJZLKafWaJrql1s" >> .env
echo "LOG_PATH = logs"
# Build aplikasi
RUN go build -o main .
# Jalankan aplikasi
CMD ["./main"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960package config
import (
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/joho/godotenv"
"go-dp.abdanhafidz.com/models"
)
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.")
}
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)
}12345678910111213141516package config
import "os"
var TCP_ADDRESS string
var LOG_PATH string
var HOST_ADDRESS string
var HOST_PORT string
func init() {
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
}123456789package controller
import "github.com/gin-gonic/gin"
func HomeController(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Api Quzuu Backend 2024!",
})
}12345678910111213141516171819package controller
import (
"github.com/gin-gonic/gin"
"go-dp.abdanhafidz.com/models"
"go-dp.abdanhafidz.com/services"
)
func LoginController(c *gin.Context) {
authentication := services.AuthenticationService{}
loginController := Controller[models.LoginRequest, services.LoginConstructor, models.Account]{
Service: &authentication.Service,
}
loginController.RequestJSON(c)
loginController.Service.Constructor.Email = loginController.Request.Email
loginController.Service.Constructor.Password = loginController.Request.Password
authentication.Authenticate()
loginController.Response(c)
}12345678910111213141516171819package controller
import (
"github.com/gin-gonic/gin"
"go-dp.abdanhafidz.com/models"
"go-dp.abdanhafidz.com/services"
)
func RegisterController(c *gin.Context) {
register := services.RegisterService{}
registerController := Controller[models.RegisterRequest, models.Account, models.Account]{
Service: ®ister.Service,
}
registerController.RequestJSON(c)
registerController.Service.Constructor.Password = registerController.Request.Password
registerController.Service.Constructor.Email = registerController.Request.Email
register.Create()
registerController.Response(c)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package controller
import (
"github.com/gin-gonic/gin"
"go-dp.abdanhafidz.com/models"
"go-dp.abdanhafidz.com/services"
"go-dp.abdanhafidz.com/utils"
)
type (
Controllers interface {
RequestJSON(c *gin.Context)
Response(c *gin.Context)
}
Controller[T1 any, T2 any, T3 any] struct {
AccountData models.AccountData
Request T1
Service *services.Service[T2, T3]
}
)
func (controller *Controller[T1, T2, T3]) RequestJSON(c *gin.Context) {
cParam, _ := c.Get("accountData")
if cParam != nil {
controller.AccountData = cParam.(models.AccountData)
}
errBinding := c.ShouldBindJSON(&controller.Request)
if errBinding != nil {
utils.ResponseFAIL(c, 400, models.Exception{
BadRequest: true,
Message: "Invalid Request Type",
})
return
}
}
func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) {
switch {
case controller.Service.Error != nil:
utils.ResponseFAIL(c, 500, models.Exception{
InternalServerError: true,
Message: "Internal Server Error",
})
utils.LogError(controller.Service.Error)
case controller.Service.Exception.Unauthorized:
utils.ResponseFAIL(c, 401, controller.Service.Exception)
case controller.Service.Exception.DataNotFound:
utils.ResponseFAIL(c, 404, controller.Service.Exception)
case controller.Service.Exception.Message != "":
utils.ResponseFAIL(c, 400, controller.Service.Exception)
default:
utils.ResponseOK(c, controller.Service.Result)
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748module go-dp.abdanhafidz.com
go 1.21.0
require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.9.1 github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.32.0 gorm.io/driver/postgres v1.5.4 gorm.io/gorm v1.25.5)
require ( github.com/bytedance/sonic v1.10.2 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.25.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgx/v5 v5.5.0 // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.6 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.1.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect golang.org/x/arch v0.6.0 // indirect golang.org/x/net v0.34.0 // indirect golang.org/x/sync v0.10.0 // indirect golang.org/x/sys v0.29.0 // indirect golang.org/x/text v0.21.0 // indirect google.golang.org/protobuf v1.31.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE=github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.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.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=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 v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.16.0 h1:x+plE831WK4vaKHO/jpgUGsvLKIqRRkz6M78GuJAfGE=github.com/go-playground/validator/v10 v10.16.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=github.com/jackc/pgx/v5 v5.5.0 h1:NxstgwndsTRy7eq9/kqYc/BZh5w2hHJV86wjvO+1xPw=github.com/jackc/pgx/v5 v5.5.0/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=golang.org/x/arch v0.6.0 h1:S0JTfE48HbRj80+4tbvZDYsJ3tGv6BUU3XxyZ7CirAc=golang.org/x/arch v0.6.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg=golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ=golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo=gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0=gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=1234567891011121314package main
import (
"fmt"
"go-dp.abdanhafidz.com/config"
"go-dp.abdanhafidz.com/router"
)
func main() {
fmt.Println("Server started on ", config.TCP_ADDRESS, ", port :", config.HOST_PORT)
router.StartService()
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103// auth/auth.go
package middleware
import (
"errors"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go-dp.abdanhafidz.com/config"
"go-dp.abdanhafidz.com/models"
"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.IDAccount
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.StandardClaims
IDUser 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
}
claims, ok := token.Claims.(*CustomClaims)
if !ok || !token.Valid {
return 0, "invalid-token", err
} else if claims.StandardClaims.ExpiresAt != 0 && claims.ExpiresAt < time.Now().Unix() {
return 0, "expired", err
} else if !ok && token.Valid {
return 0, "invalid-token", err
}
return claims.IDUser, "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.IdUser, currAccData.VerifyStatus, currAccData.ErrVerif = VerifyToken(token[0])
// fmt.Println("Verify Status :", currAccData.verifyStatus)
if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {
currAccData.IdUser = 0
message := "Your session is expired, Please re-Login!"
SendJSON401(c, &currAccData.VerifyStatus, &message)
c.Abort()
return
}
} else {
currAccData.IdUser = 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()
}12345678910111213141516171819202122232425262728293031package middleware
import (
"math"
"time"
"gorm.io/gorm"
)
func RecordCheck(rows *gorm.DB) (string, error) {
count := rows.RowsAffected
err := rows.Error
// fmt.Println(rows)
// fmt.Println(count)
if count == 0 {
return "no-record", err
} else if err != nil {
return "query-error", err
} else {
return "ok", err
}
}
func DiffTime(t1 time.Time, t2 time.Time) (int, int, int) {
hs := t1.Sub(t2).Hours()
hs, mf := math.Modf(hs)
ms := mf * 60
ms, sf := math.Modf(ms)
ss := sf * 60
return int(hs), int(ms), int(ss)
}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 {
IdUser int
VerifyStatus string
ErrVerif error
}123456789101112131415161718192021222324252627282930package models
import (
"time"
)
type Account struct {
IDAccount uint `gorm:"primaryKey" json:"id_account"`
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
PhoneNumber int `json:"phone_number"`
CreatedAt time.Time `json:"created_at"`
DeletedAt time.Time `json:"deleted_at"`
}
type AccountDetails struct {
IDDetail uint `gorm:"primaryKey" json:"id_detail"`
IDAccount 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" }1234567891011package 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"`
Message string `json:"message,omitempty"`
}repositories/AccountRepository.go+2-2
repositories/repositories.go-7
services/LoginService.go+1-1
services/RegisterService.go+2
space/go.mod+1
space/go.sum+2
space/models/DatabaseModel.go+17-5
space/repositories/AccountRepository.go-3
space/services/RegisterService.go+3-2
space/space/controller/LoginController.go+5-5
space/space/controller/RegisterController.go+5-5
space/space/controller/controller.go+5-2
space/space/models/DatabaseModel.go+1-1
space/space/repositories/AccountRepository.go+7-2
space/space/repositories/repositories.go+18-5
space/space/services/LoginService.go+1-2
space/space/services/RegisterService.go-4
space/space/space/controller/LoginController.go+1-1
space/space/space/controller/controller.go+2
space/space/space/middleware/AuthMiddleware.go+1-1
space/space/space/models/DatabaseModel.go+5-8
space/space/space/models/ResponseModel.go+5
space/space/space/repositories/AccountRepository.go+3-5
space/space/space/repositories/repositories.go+32-21
space/space/space/services/LoginService.go+14-2
space/space/space/services/RegisterService.go+6-1
space/space/space/space/space/Dockerfile+2-2
space/space/space/space/space/space/controller/HomeController.go+1-1
space/space/space/space/space/space/router/router.go+2-1
space/space/space/space/space/space/space/.env.exampleAdded+9
space/space/space/space/space/space/space/.github/workflows/main.ymlAdded+52
space/space/space/space/space/space/space/.gitignoreAdded+3
space/space/space/space/space/space/space/DockerfileAdded+30
space/space/space/space/space/space/space/config/DatabaseConfig.goAdded+60
space/space/space/space/space/space/space/config/EnvConfig.goAdded+16
space/space/space/space/space/space/space/controller/HomeController.goAdded+9
space/space/space/space/space/space/space/controller/LoginController.goAdded+19
space/space/space/space/space/space/space/controller/RegisterController.goAdded+19
space/space/space/space/space/space/space/controller/controller.goAdded+53
space/space/space/space/space/space/space/go.modAdded+48
space/space/space/space/space/space/space/go.sumAdded+138
space/space/space/space/space/space/space/logs/error_log.txtAdded
space/space/space/space/space/space/space/logs/security_log.txtAdded
space/space/space/space/space/space/space/main.goAdded+14
space/space/space/space/space/space/space/middleware/AuthMiddleware.goAdded+103
space/space/space/space/space/space/space/middleware/middleware.goAdded+31
space/space/space/space/space/space/space/middleware/responseMiddleware.goAdded+39
space/space/space/space/space/space/space/models/AuthModel.goAdded+7
space/space/space/space/space/space/space/models/DatabaseModel.goAdded+30
space/space/space/space/space/space/space/models/ExceptionModel.goAdded+11