Spaces:
Configuration error
Configuration error
Commit ·
34fb971
1
Parent(s): 164cc3b
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)
- controller/auth/auth_change_password_controller.goAdded+21
- controller/auth/auth_login_controller.goAdded+20
- controller/auth/auth_profile_controller.goAdded+21
- controller/auth/auth_register_controller.goAdded+20
- controller/auth/auth_update_profile_controller.goAdded+24
- go.mod-1
- go.sum-2
- logserror_log.txt+1
- middleware/authentication_middleware.go+9-39
- models/authentication_payload_model.go+1-1
- models/custom_claim.goAdded+8
- models/response_model.go+1
- repositories/account_repository.go+11-5
- repositories/email_verification_repository.go+2-2
- repositories/repository.go+3
- router/auth_route.goAdded+18
- router/router.go+1-1
- services/authentication_service.go+1-1
- services/email_verification_service.go+1-1
- services/jwt_service.go+46-11
- services/user_profile_service.go+1-1
- space/controller/user/user_change_password_controller.goAdded+21
- space/controller/user/user_login_controller.go+1-1
- space/controller/user/user_profile_controller.go+2-5
- space/controller/user/user_update_profile_controller.go+8-8
- space/logserror_log.txt+2
- space/models/request_model.go+4
- space/repositories/account_repository.go+38-4
- space/repositories/repository.go+1
- space/router/user_route.go+2
- space/services/authentication_service.goAdded+71
- space/services/register_service.go+7
- space/services/user_profile_service.go+13-8
- space/space/.github/workflows/main.yml+13-37
- space/space/.github/workflows/main_huggingface.ymlAdded+52
- space/space/Dockerfile+37-30
- space/space/README.md+19-3
- space/space/docker-compose.ymlAdded+31
- space/space/space/.gitignore+2-1
- space/space/space/config/config.go+3
- space/space/space/config/database_connection_config.go+10
- space/space/space/controller/controller.go+7
- space/space/space/controller/email/email_create_verification.goAdded+22
- space/space/space/controller/email/email_delete_verification.goAdded+22
- space/space/space/controller/email/email_verify.goAdded+22
- space/space/space/controller/user/user_login_controller.goAdded+20
- space/space/space/controller/user/user_profile_controller.goAdded+24
- space/space/space/controller/user/user_register_controller.goAdded+20
- space/space/space/controller/user/user_update_profile_controller.goAdded+24
- space/space/space/docker-compose.yamlAdded+10
123456789101112131415161718192021package user
import (
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func ChangePassword(c *gin.Context) {
authentication := services.AuthenticationService{}
changePasswordController := controller.Controller[models.ChangePasswordRequest, models.Account, models.AuthenticatedUser]{
Service: &authentication.Service,
}
changePasswordController.HeaderParse(c, func() {
changePasswordController.Service.Constructor.Id = uint(changePasswordController.AccountData.UserID)
})
changePasswordController.RequestJSON(c, func() {
authentication.Update(changePasswordController.Request.OldPassword, changePasswordController.Request.NewPassword)
})
}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, models.Account, 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()
})
}123456789101112131415161718192021package user
import (
"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, models.AccountDetails, models.AccountDetails]{
Service: &userProfile.Service,
}
userProfileController.HeaderParse(c, func() {
userProfileController.Service.Constructor.AccountID = uint(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 (
"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[models.AccountDetails, models.AccountDetails, models.AccountDetails]{
Service: &userProfile.Service,
}
userUpdateProfileController.RequestJSON(c, func() {
userUpdateProfileController.Service.Constructor = userUpdateProfileController.Request
userUpdateProfileController.HeaderParse(c, func() {
userUpdateProfileController.Service.Constructor.AccountID = uint(userUpdateProfileController.AccountData.UserID)
})
userProfile.Update()
},
)
}2 unmodified lines34566782 unmodified linesgo 1.24.0
require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.10.0 github.com/golang-jwt/jwt/v5 v5.2.1 github.com/joho/godotenv v1.5.19 unmodified lines10111213141314159 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=1232025/03/18 21:08:07 Error Log : ERROR: relasi « email_verifications » tidak ada (SQLSTATE 42P01)2025/03/22 14:00:34 Error Log : duplicated key not allowed2025/03/22 16:57:13 Error Log : ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification (SQLSTATE 42P10)2 unmodified lines34567867891210111516171819202122232425262728293031323334353637383940414243444512134849505114151617181920212223242 unmodified linespackage middleware
import (
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"api.qobiltu.id/utils"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
var salt = config.Salt
var secretKey = []byte(salt)
// VerifyPassword verifies if the provided password matches the hashed password
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 c.Request.Header["Authorization"] != nil {
token := c.Request.Header["Authorization"]
// fmt.Println("Authorization :", token)
currAccData.UserID, currAccData.VerifyStatus, currAccData.ErrVerif = services.VerifyToken(token[0])
// fmt.Println("Verify Status :", currAccData.VerifyStatus)
// fmt.Println("Verify UserID :", currAccData.UserID)
if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" {
currAccData.UserID = 0
utils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "Your session is expired, Please re-Login!"})12344567package models
type AccountData struct {
UserID int
UserID uint
VerifyStatus string
ErrVerif error
}12345678package models
import "github.com/golang-jwt/jwt/v5"
type CustomClaims struct { jwt.RegisteredClaims UserID uint `json:"id"`}12 unmodified lines1314151617181912 unmodified lines Errors Exception `json:"errors"`
MetaData any `json:"meta_data"`
}
type AuthenticatedUser struct {
Account Account `json:"account"`
Token string `json:"token"`16 unmodified lines17181920202122222324251 unmodified line272829303132331 unmodified line35363738373940394142434144454647484950515253541 unmodified line565758596061623 unmodified lines6667686970717216 unmodified lines return *repo
}
func GetAccountbyId(account_id uint) Repository[models.Account, models.Account] {
func GetAccountById(accountId uint) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
models.Account{Id: account_id},
models.Account{Id: accountId},
)
repo.Transactions(
WhereGivenConstructor[models.Account, models.Account],1 unmodified line )
return *repo
}
func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
account,1 unmodified line Update(repo)
return *repo
}
func GetAccountDetailsbyId(account_id uint) Repository[models.AccountDetails, models.AccountDetails] {
func GetDetailAccountById(accountId uint) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
models.AccountDetails{AccountID: account_id},
models.AccountDetails{AccountID: accountId},
)
fmt.Println("Account ID:", repo.Constructor.AccountID)
// fmt.Println("Account ID:", repo.Constructor.AccountID)
repo.Transactions(
WhereGivenConstructor[models.AccountDetails, models.AccountDetails],
Find[models.AccountDetails, models.AccountDetails],
)
return *repo
}
func CreateAccount(account models.Account) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
account,1 unmodified line Create(repo)
return *repo
}
func CreateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
accountDetails,3 unmodified lines Create(repo)
return *repo
}
func UpdateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
accountDetails,18 unmodified lines19202122222324252526272818 unmodified lines return *repo
}
func GetEmailVerification(account_id uint, token uint) Repository[models.EmailVerification, models.EmailVerification] {
func GetEmailVerification(accountId uint, token uint) Repository[models.EmailVerification, models.EmailVerification] {
repo := Construct[models.EmailVerification, models.EmailVerification](
models.EmailVerification{
AccountID: account_id,
AccountID: accountId,
IsExpired: false,
Token: token,
},47 unmodified lines484950515253542 unmodified lines575859606162631 unmodified line6566676869707147 unmodified lines 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)2 unmodified lines }
}
}
func WhereGivenConstructor[T1 any, T2 any](repo *Repository[T1, T2]) *gorm.DB {
tx := repo.Transaction.Where(&repo.Constructor)
repo.RowsCount = int(tx.RowsAffected)1 unmodified line 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)123456789101112131415161718package router
import (
AuthController "api.qobiltu.id/controller/auth"
"api.qobiltu.id/middleware"
"github.com/gin-gonic/gin"
)
func AuthRoute(router *gin.Engine) {
routerGroup := router.Group("/api/v1/auth")
{
routerGroup.POST("/login", AuthController.Login)
routerGroup.POST("/register", AuthController.Register)
routerGroup.GET("/me", middleware.AuthUser, AuthController.Profile)
routerGroup.PUT("/me", middleware.AuthUser, AuthController.UpdateProfile)
routerGroup.PUT("/change-password", middleware.AuthUser, AuthController.ChangePassword)
}
}8 unmodified lines9101112121314158 unmodified linesfunc StartService() {
router := gin.Default()
router.GET("/", controller.HomeController)
UserRoute(router)
AuthRoute(router)
EmailRoute(router)
router.Run(config.TCP_ADDRESS)
}44 unmodified lines454647484849505144 unmodified lines s.Exception.Message = "Password must have at least 8 characters!"
return
}
accountData := repositories.GetAccountbyId(s.Constructor.Id)
accountData := repositories.GetAccountById(s.Constructor.Id)
if accountData.NoRecord {
s.Exception.DataNotFound = true13 unmodified lines141516171718192013 unmodified lines}
func (s *EmailVerificationService) Create() {
accountRepo := repositories.GetAccountbyId(s.Constructor.AccountID)
accountRepo := repositories.GetAccountById(s.Constructor.AccountID)
if accountRepo.NoRecord {
s.Error = accountRepo.RowsError
s.Exception.DataNotFound = true1 unmodified line234567899101112131 unmodified line1516171819202122232425262728293031323334353637383918194041422122232443444546474849505152532627542955565758596061626364656632676869701 unmodified line
import (
"errors"
"strings"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"github.com/dgrijalva/jwt-go"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
1 unmodified linevar secretKey = []byte(salt)
func GenerateToken(user *models.Account) (string, error) {
claims := models.CustomClaims{
UserID: user.Id,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), // Token berlaku 24 jam
IssuedAt: jwt.NewNumericDate(time.Now()),
Issuer: "qobiltu.id",
},
}
// Buat token dengan metode signing
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(secretKey)
}
func ExtractBearerToken(authHeader string) (string, error) {
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
return "", errors.New("invalid authorization header format")
}
return parts[1], nil
}
// Create a new token
token := jwt.New(jwt.SigningMethodHS256)
func VerifyToken(bearerToken string) (uint, string, error) {
// fmt.Println("bearerToken :", bearerToken)
// 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
tokenData, err := ExtractBearerToken(bearerToken)
if err != nil {
return 0, "invalid-token", err
} else {
// fmt.Println("Extracted Token:", tokenData)
}
token, err := jwt.ParseWithClaims(tokenData, &models.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return secretKey, nil
})
// Sign the token with the secret key
tokenString, err := token.SignedString(secretKey)
if err != nil {
return "", err
return 0, "invalid-token", err
}
// Extract the claims
claims, ok := token.Claims.(*models.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 tokenString, nil
return claims.UserID, "valid", err
}
func VerifyPassword(hashedPassword, password string) error {19 unmodified lines202122232324252619 unmodified lines s.Result = userProfile.Result
}
func (s *UserProfileService) Retrieve() {
userProfile := repositories.GetAccountDetailsbyId(s.Constructor.AccountID)
userProfile := repositories.GetDetailAccountById(s.Constructor.AccountID)
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true123456789101112131415161718192021package user
import (
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func ChangePassword(c *gin.Context) {
authentication := services.AuthenticationService{}
changePasswordController := controller.Controller[models.ChangePasswordRequest, models.Account, models.AuthenticatedUser]{
Service: &authentication.Service,
}
changePasswordController.HeaderParse(c, func() {
changePasswordController.Service.Constructor.Id = uint(changePasswordController.AccountData.UserID)
})
changePasswordController.RequestJSON(c, func() {
authentication.Update(changePasswordController.Request.OldPassword, changePasswordController.Request.NewPassword)
})
}8 unmodified lines9101112121314158 unmodified lines
func Login(c *gin.Context) {
authentication := services.AuthenticationService{}
loginController := controller.Controller[models.LoginRequest, services.LoginConstructor, models.AuthenticatedUser]{
loginController := controller.Controller[models.LoginRequest, models.Account, models.AuthenticatedUser]{
Service: &authentication.Service,
}
loginController.RequestJSON(c, func() {123454562 unmodified lines910111412131417151916171819package user
import (
"fmt"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"2 unmodified lines
func Profile(c *gin.Context) {
userProfile := services.UserProfileService{}
userProfileController := controller.Controller[any, services.UserProfileConstructor, models.Account]{
userProfileController := controller.Controller[any, models.AccountDetails, models.AccountDetails]{
Service: &userProfile.Service,
}
fmt.Println(userProfileController.AccountData)
userProfileController.HeaderParse(c, func() {
userProfileController.Service.Constructor.AccountId = userProfileController.AccountData.UserID
userProfileController.Service.Constructor.AccountID = uint(userProfileController.AccountData.UserID)
userProfile.Retrieve()
userProfileController.Response(c)
},123454562 unmodified lines9101114121314171819202115161718192021222324package user
import (
"fmt"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"2 unmodified lines
func UpdateProfile(c *gin.Context) {
userProfile := services.UserProfileService{}
userUpdateProfileController := controller.Controller[any, services.UserProfileConstructor, models.Account]{
userUpdateProfileController := controller.Controller[models.AccountDetails, models.AccountDetails, models.AccountDetails]{
Service: &userProfile.Service,
}
fmt.Println(userUpdateProfileController.AccountData)
userUpdateProfileController.HeaderParse(c, func() {
userUpdateProfileController.Service.Constructor.AccountId = userUpdateProfileController.AccountData.UserID
userProfile.Retrieve()
userUpdateProfileController.Response(c)
userUpdateProfileController.RequestJSON(c, func() {
userUpdateProfileController.Service.Constructor = userUpdateProfileController.Request
userUpdateProfileController.HeaderParse(c, func() {
userUpdateProfileController.Service.Constructor.AccountID = uint(userUpdateProfileController.AccountData.UserID)
})
userProfile.Update()
},
)
}1232025/03/18 21:08:07 Error Log : ERROR: relasi « email_verifications » tidak ada (SQLSTATE 42P01)2025/03/22 14:00:34 Error Log : duplicated key not allowed2025/03/22 16:57:13 Error Log : ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification (SQLSTATE 42P10)13 unmodified lines14151617181920212213 unmodified lines
type CreateEmailVerificationRequest struct {
AccountID int `json:"account_id" binding:"required"`
}
type ChangePasswordRequest struct {
OldPassword string `json:"old_password" binding:"required" `
NewPassword string `json:"new_password" binding:"required" `
}1234567818 unmodified lines2728293031323334353637383940414243444546474849501 unmodified line52535435363738555657585960616263646566676869707172package repositories
import (
"fmt"
"api.qobiltu.id/models"
)
18 unmodified lines )
return *repo
}
func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
account,
)
Update(repo)
return *repo
}
func GetAccountDetailsbyId(account_id uint) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
models.AccountDetails{AccountID: account_id},
)
fmt.Println("Account ID:", repo.Constructor.AccountID)
repo.Transactions(
WhereGivenConstructor[models.AccountDetails, models.AccountDetails],
Find[models.AccountDetails, models.AccountDetails],
)
return *repo
}
func CreateAccount(account models.Account) Repository[models.Account, models.Account] {
repo := Construct[models.Account, models.Account](
account,1 unmodified line Create(repo)
return *repo
}
// func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {
// repo := Construct
// }func CreateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
accountDetails,
)
fmt.Println(accountDetails)
fmt.Println("Account ID : ", accountDetails.AccountID)
Create(repo)
return *repo
}
func UpdateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {
repo := Construct[models.AccountDetails, models.AccountDetails](
accountDetails,
)
fmt.Println(accountDetails)
fmt.Println("Account ID : ", accountDetails.AccountID)
Update(repo)
return *repo
}92 unmodified lines9394959697989992 unmodified lines repo.RowsCount = int(tx.RowsAffected)
repo.NoRecord = repo.RowsCount == 0
repo.RowsError = tx.Error
repo.Result = repo.Constructor
return tx
}
11 unmodified lines1213141516171811 unmodified lines routerGroup.POST("/login", UserController.Login)
routerGroup.POST("/register", UserController.Register)
routerGroup.GET("/me", middleware.AuthUser, UserController.Profile)
routerGroup.PUT("/me", middleware.AuthUser, UserController.UpdateProfile)
routerGroup.PUT("/change-password", middleware.AuthUser, UserController.ChangePassword)
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package services
import (
"errors"
"fmt"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
)
type AuthenticationService struct {
Service[models.Account, 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 VerifyPassword(accountData.Result.Password, s.Constructor.Password) != nil {
s.Exception.Unauthorized = true
s.Exception.Message = "incorrect password!"
return
}
token, err_tok := 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
}
func (s *AuthenticationService) Update(oldPassword string, newPassword string) {
if len(newPassword) < 8 {
s.Exception.InvalidPasswordLength = true
s.Exception.Message = "Password must have at least 8 characters!"
return
}
accountData := repositories.GetAccountbyId(s.Constructor.Id)
if accountData.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "there is no account with given credentials!"
return
}
fmt.Println("Result Password", accountData.Result.Password)
fmt.Println("old Password given", oldPassword)
if VerifyPassword(accountData.Result.Password, oldPassword) != nil {
s.Exception.Unauthorized = true
s.Exception.Message = "incorrect old password!"
return
}
accountData.Result.Password = newPassword
changePassword := repositories.UpdateAccount(accountData.Result)
changePassword.Result.Password = "SECRET"
s.Result = models.AuthenticatedUser{
Account: changePassword.Result,
}
s.Error = changePassword.RowsError
}
// LoginHandler handles user login32 unmodified lines3334353637383940414243444532 unmodified lines s.Exception.Message = "Bad request!"
return
}
userProfile := UserProfileService{}
userProfile.Constructor.AccountID = accountCreated.Result.Id
userProfile.Create()
if userProfile.Error != nil {
s.Error = userProfile.Error
return
}
s.Error = accountCreated.RowsError
s.Result = accountCreated.Result
s.Result.Password = "SECRET"4 unmodified lines56789108129101112131415161718192021221623242526272829233031323328343536373839403541424 unmodified lines "api.qobiltu.id/repositories"
)
type UserProfileConstructor struct {
AccountId int
}
type UserProfileService struct {
Service[UserProfileConstructor, models.Account]
Service[models.AccountDetails, models.AccountDetails]
}
func (s *UserProfileService) Create() {
userProfile := repositories.CreateAccountDetails(s.Constructor)
s.Error = userProfile.RowsError
if userProfile.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account with given credentials!"
return
}
s.Result = userProfile.Result
}
func (s *UserProfileService) Retrieve() {
userProfile := repositories.GetAccountbyId(uint(s.Constructor.AccountId))
userProfile := repositories.GetAccountDetailsbyId(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))
userProfile := repositories.UpdateAccountDetails(s.Constructor)
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
}112341 unmodified line67899101112131314151718192021222324252627282930313233343536373839404142161718192044454647212249505152232425262728name: Deploy to Development via Huggingfacename: Deploy Golang App
on: push:1 unmodified line - main
jobs: deploy-to-huggingface: deploy: 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/ - name: Set up SSH key uses: webfactory/ssh-agent@v0.5.4 with: ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
# Commit and Push to Huggingface Space - name: Commit and Push to Huggingface env: HF_TOKEN: ${{ secrets.HF_TOKEN }} - name: Deploy to VPS 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" ssh -o StrictHostKeyChecking=no qobiltu@103.23.199.136 << 'EOF' cd /home/qobiltu/api-qobiltu git pull origin main docker-compose down -v docker-compose up --build -d EOF12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152name: 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"12345678910111213141516171819202122232425262728293012345678910111213141516171819202122232425262728293031323334353637# 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" >> .env
# Build aplikasi
RUN go build -o main .
# Jalankan aplikasi
CMD ["./main"]# Gunakan image dasar Golang versi 1.24.1FROM golang:1.24.1 AS builder
# Set working directoryWORKDIR /app
# Copy go.mod dan go.sumCOPY go.mod go.sum ./
# Download dependenciesRUN go mod download
# Copy seluruh kodeCOPY . .
# Build aplikasi# RUN go build -o /app/main .
# Build aplikasi untuk LinuxRUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /app/main .
# Stage 2: Gunakan image runtime yang lebih kecilFROM alpine:latest
# Set working directoryWORKDIR /app
# Copy hasil build dari builder ke image runtimeCOPY --from=builder /app/main .
# Copy file .env untuk konfigurasi environmentCOPY .env .env
RUN chmod +x /app/main
# Jalankan aplikasiCMD ["./main"]61 unmodified lines626364656566676869697071717273747576777879808182838485868761 unmodified lines
# Command Documentation
## GO Command
## Update Golang Project version
### Update Golang Project version
> go mod edit -go 1.24
> go mod tidy
## Update all package
### Update all package
> go get -u ./...
> go mod tidy> go mod tidy
## Docker Command
### Enter docker container
> docker exec -it api-qobiltu sh
### Docker Running Process
> docker ps
### Rebuild Docker Image
> docker-compose down -v
> docker-compose up --build -d
### View Log container
> docker logs --tail=50 -f api-qobiltu
> docker logs postgres-db12345678910111213141516171819202122232425262728293031version: '3.8'
services: app: container_name: api-qobiltu build: . depends_on: - db env_file: .env ports: - "8080:8080" # volumes: # - ./logs:/app/logs # - /home/qobiltu/api-qobiltu:/app restart: unless-stopped
db: image: postgres:15 container_name: postgres-db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_DB: ${DB_NAME} ports: - "5432:5432" volumes: - db-data:/var/lib/postgresql/data restart: always
volumes: db-data:123445.env
vendor/
quzuu-be.exe
README.mdREADME.md.qodo1 unmodified line23456782 unmodified lines111213141516171 unmodified line1920212223241 unmodified line
import (
"os"
"strconv"
"github.com/joho/godotenv"
)2 unmodified linesvar LOG_PATH string
var HOST_ADDRESS string
var HOST_PORT string
var EMAIL_VERIFICATION_DURATION int
func init() {
godotenv.Load()1 unmodified line HOST_PORT = os.Getenv("HOST_PORT")
TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORT
LOG_PATH = os.Getenv("LOG_PATH")
EMAIL_VERIFICATION_DURATION, _ = strconv.Atoi(os.Getenv("EMAIL_VERIFICATION_DURATION"))
// Menampilkan nilai variabel lingkungan
}50 unmodified lines515253545556575859606162636465666750 unmodified lines err := 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 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:5432controller/auth/auth_change_password_controller.goAdded+21
controller/auth/auth_login_controller.goAdded+20
controller/auth/auth_profile_controller.goAdded+21
controller/auth/auth_register_controller.goAdded+20
controller/auth/auth_update_profile_controller.goAdded+24
go.mod-1
go.sum-2
logserror_log.txt+1
middleware/authentication_middleware.go+9-39
models/authentication_payload_model.go+1-1
models/custom_claim.goAdded+8
models/response_model.go+1
repositories/account_repository.go+11-5
repositories/email_verification_repository.go+2-2
repositories/repository.go+3
router/auth_route.goAdded+18
router/router.go+1-1
services/authentication_service.go+1-1
services/email_verification_service.go+1-1
services/jwt_service.go+46-11
services/user_profile_service.go+1-1
space/controller/user/user_change_password_controller.goAdded+21
space/controller/user/user_login_controller.go+1-1
space/controller/user/user_profile_controller.go+2-5
space/controller/user/user_update_profile_controller.go+8-8
space/logserror_log.txt+2
space/models/request_model.go+4
space/repositories/account_repository.go+38-4
space/repositories/repository.go+1
space/router/user_route.go+2
space/services/authentication_service.goAdded+71
space/services/register_service.go+7
space/services/user_profile_service.go+13-8
space/space/.github/workflows/main.yml+13-37
space/space/.github/workflows/main_huggingface.ymlAdded+52
space/space/Dockerfile+37-30
space/space/README.md+19-3
space/space/docker-compose.ymlAdded+31
space/space/space/.gitignore+2-1
space/space/space/config/config.go+3
space/space/space/config/database_connection_config.go+10
space/space/space/controller/controller.go+7
space/space/space/controller/email/email_create_verification.goAdded+22
space/space/space/controller/email/email_delete_verification.goAdded+22
space/space/space/controller/email/email_verify.goAdded+22
space/space/space/controller/user/user_login_controller.goAdded+20
space/space/space/controller/user/user_profile_controller.goAdded+24
space/space/space/controller/user/user_register_controller.goAdded+20
space/space/space/controller/user/user_update_profile_controller.goAdded+24
space/space/space/docker-compose.yamlAdded+10