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