Spaces:
Configuration error
Configuration error
Commit ·
48471f7
1
Parent(s): 98c95a0
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+1
- apperror/apperror.goAdded+168
- config/database_connection_config.go+80-79
- config/tx.goAdded+34
- controller/health_check/health_check_controller.goAdded+31
- main.go+16-1
- models/exception_model.go+17-15
- models/health_check_model.goAdded+10
- repositories/health_check_repository.goAdded+41
- response/paging.goAdded+58
- response/response.goAdded+152
- router/health_check_route.goAdded+5
- router/router.go+12-19
- router/server.goAdded+32
- services/health_check_service/health_check_service.goAdded+15
- services/health_check_service/health_check_service_check.goAdded+21
- services/register_service.go+66-66
- space/.gitignore+2-1
- space/MakefileAdded+7
- space/assets/efs.goAdded+13
- space/assets/emails/email-confirmation.tmplAdded+55
- space/assets/emails/email-forgot-password.tmplAdded+56
- space/config/config.go+63-36
- space/controller/api_response.goAdded+53
- space/controller/controller.go+65-65
- space/controller/email/email_create_verification_controller.go+21-21
- space/docker-compose.dev.ymlAdded+18
- space/docker-compose.yml+23
- space/go.mod+9
- space/go.sum+22
- space/mail/sender.goAdded+8
- space/mail/smtp.goAdded+71
- space/main.go+62-14
- space/middleware/authentication_middleware.go+37-37
- space/router/router.go+27-24
- space/services/email_verification_service.go+101-181
- space/services/forgot_password_service.go+114-113
- space/services/register_service.go+86-86
- space/space/models/database_orm_model.go+4-4
- space/space/services/academy_quiz_service.go-1
- space/space/space/models/database_orm_model.go+3-3
- space/space/space/space/controller/quiz/question_quiz_controller.go+1-1
- space/space/space/space/models/database_orm_model.go+1-1
- space/space/space/space/space/controller/quiz/answer_quiz_controller.go+2-2
- space/space/space/space/space/controller/quiz/question_quiz_controller.go+5-3
- space/space/space/space/space/space/controller/quiz/answer_quiz_controller.go+2-1
- space/space/space/space/space/space/space/controller/quiz/attempt_quiz_controller.go+2-1
- space/space/space/space/space/space/space/controller/quiz/submit_quiz_controller.goAdded+23
- space/space/space/space/space/space/space/models/database_orm_model.go+6
- space/space/space/space/space/space/space/models/response_model.go+5
24 unmodified lines252627282924 unmodified lines git pull origin main docker-compose down -v docker-compose up --build -d docker image prune -f EOF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168package apperror
import ( "api.qobiltu.id/validation" "fmt")
// AppError is a custom error type for the application.type AppError struct { Code string // Optional: Error code for programmatic handling Message string // Human-readable error message Err error // Underlying error, if any Details map[string]any // Optional: Additional details about the error}
func (e AppError) Error() string { if e.Code != "" { return fmt.Sprintf("[%s] %s", e.Code, e.Message) } return e.Message}
// NewAppError creates a new AppError.func NewAppError(code, message string, err error, details map[string]any) error { return &AppError{ Code: code, Message: message, Err: err, Details: details, }}
// ValidationError represents errors related to data validation.type ValidationError struct { Errors []validation.ErrorMessage // Structure to hold field and message of validation errors}
func (e ValidationError) Error() string { return fmt.Sprintf("validation failed: %+v", e.Errors)}
// NewValidationError creates a new ValidationError.func NewValidationError(message string, errors []validation.ErrorMessage) error { return &AppError{ Code: "VALIDATION_ERROR", Message: message, Err: ValidationError{Errors: errors}, }}
// InternalError represents unexpected errors within the application.type InternalError struct { Message string Err error}
func (e InternalError) Error() string { return fmt.Sprintf("internal server error: %v", e.Err)}
// NewInternalError creates a new InternalError wrapped in AppError.func NewInternalError(message string, err error) error { return &AppError{ Code: "INTERNAL_ERROR", Message: message, Err: InternalError{Message: message, Err: err}, }}
// ConflictError represents errors due to a conflict with the current state.type ConflictError struct { Message string Err error}
func (e ConflictError) Error() string { return fmt.Sprintf("conflict: %s", e.Err)}
// NewConflictError creates a new ConflictError wrapped in AppError.func NewConflictError(message string, err error) error { return &AppError{ Code: "CONFLICT_ERROR", Message: message, Err: ConflictError{Message: message, Err: err}, }}
// NotFoundError represents errors when a resource is not found.type NotFoundError struct { Message string Resource string ID any}
func (e NotFoundError) Error() string { return fmt.Sprintf("%s with ID '%v' not found", e.Resource, e.ID)}
// NewNotFoundError creates a new NotFoundError wrapped in AppError.func NewNotFoundError(resource string, id any) error { message := fmt.Sprintf("%s not found", resource) return &AppError{ Code: "NOT_FOUND_ERROR", Message: fmt.Sprintf("%s not found", resource), Err: NotFoundError{Message: message, Resource: resource, ID: id}, Details: map[string]any{ "resource": resource, "id": id, }, }}
// UnauthorizedError represents errors when access is denied due to lack of credentials.type UnauthorizedError struct { Message string Err error}
func (e UnauthorizedError) Error() string { return fmt.Sprintf("unauthorized: %s", e.Err)}
// NewUnauthorizedError creates a new UnauthorizedError wrapped in AppError.func NewUnauthorizedError(message string, err error) error { return &AppError{ Code: "UNAUTHORIZED_ERROR", Message: message, Err: UnauthorizedError{Message: message, Err: err}, }}
// ForbiddenError represents errors when access is denied even with valid credentials.type ForbiddenError struct { Message string Err error}
func (e ForbiddenError) Error() string { return fmt.Sprintf("forbidden: %s", e.Err)}
// NewForbiddenError creates a new ForbiddenError wrapped in AppError.func NewForbiddenError(message string, err error) error { return &AppError{ Code: "FORBIDDEN_ERROR", Message: message, Err: ForbiddenError{Message: message, Err: err}, }}
// BadRequestError represents errors due to an invalid request.type BadRequestError struct { Message string Err error}
func (e BadRequestError) Error() string { return fmt.Sprintf("bad request: %s", e.Err)}
func NewBadRequestError(message string, err error) error { return &AppError{ Code: "BAD_REQUEST_ERROR", Message: message, Err: BadRequestError{Message: message, Err: err}, }}112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package configpackage 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{},
&models.EmailVerification{},
&models.ExternalAuth{},
&models.FCM{},
&models.ForgotPassword{},
&models.Academy{},
&models.AcademyMaterial{},
&models.AcademyContent{},
&models.AcademyMaterialProgress{},
&models.AcademyContentProgress{},
&models.RegionCity{},
&models.RegionProvince{},
&models.OptionCategory{},
&models.OptionValues{},
&models.Quiz{},
&models.QuizAttempt{},
&models.Question{},
&models.Answer{},
&models.UserAnswer{},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("Migration completed successfully.")
}
import ( "fmt" "log" "log/slog" "os"
"gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger"
"api.qobiltu.id/models" "github.com/joho/godotenv")
var DB *gorm.DBvar err errorvar 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{}, &models.EmailVerification{}, &models.ExternalAuth{}, &models.FCM{}, &models.ForgotPassword{}, &models.Academy{}, &models.AcademyMaterial{}, &models.AcademyContent{}, &models.AcademyMaterialProgress{}, &models.AcademyContentProgress{}, &models.RegionCity{}, &models.RegionProvince{}, &models.OptionCategory{}, &models.OptionValues{}, &models.Quiz{}, &models.QuizAttempt{}, &models.Question{}, &models.Answer{}, &models.UserAnswer{}, )
if err != nil { log.Fatal(err) }
slog.Info("Auto-migration completed successfully")}12345678910111213141516171819202122232425262728293031323334package config
import ( "context" "fmt" "gorm.io/gorm")
func RunTx(ctx context.Context, db *gorm.DB, fn func(tx *gorm.DB) error) error { tx := db.WithContext(ctx).Begin() if tx.Error != nil { return fmt.Errorf("failed to begin transaction: %w", tx.Error) }
defer func() { if p := recover(); p != nil { _ = tx.Rollback() panic(p) // Re-throw panic setelah rollback } }()
if err := fn(tx); err != nil { if rbErr := tx.Rollback().Error; rbErr != nil { return fmt.Errorf("transaction error: %v, rollback error: %w", err, rbErr) } return err }
if err := tx.Commit().Error; err != nil { return fmt.Errorf("failed to commit transaction: %w", err) }
return nil}12345678910111213141516171819202122232425262728293031package health_check_controller
import ( "api.qobiltu.id/models" "api.qobiltu.id/response" "api.qobiltu.id/services/health_check_service" "github.com/gin-gonic/gin" "net/http")
type HealthCheckController struct { healthCheckService *health_check_service.HealthCheckService}
func NewHealthCheckController(healthCheckService *health_check_service.HealthCheckService) *HealthCheckController { return &HealthCheckController{ healthCheckService: healthCheckService, }}
func (h *HealthCheckController) Check(ctx *gin.Context) { req := models.HealthCheckRequest{}
res, err := h.healthCheckService.Check(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, "Service is running", http.StatusOK, res, nil)}1 unmodified line2345678910111228 unmodified lines41424344454647484950515253545556575859466061621 unmodified line
import ( "api.qobiltu.id/config" "api.qobiltu.id/controller/health_check" "api.qobiltu.id/mail" "api.qobiltu.id/repositories" "api.qobiltu.id/router" "api.qobiltu.id/services/health_check_service" "api.qobiltu.id/utils" "api.qobiltu.id/worker" "github.com/hibiken/asynq"28 unmodified lines taskProcessor := worker.NewRedisTaskProcessor(asynqRedisOpt, emailSender) worker.AsyncTaskDistributor = taskDistributor
// setup repo, service, and controller healthCheckRepository := repositories.NewHealthCheckRepository(config.DB) healthCheckService := health_check_service.NewHealthCheckService(healthCheckRepository) healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)
// start task processor err = taskProcessor.Start() utils.FatalIfErr("failed to start task processor", err) slog.Info("Task processor started")
// create server s, err := router.NewServer(healthCheckController) utils.FatalIfErr("failed to create server", err)
// run server slog.Info("Starting server", "address", config.TCP_ADDRESS, "port", config.HOST_PORT) router.StartService() err = s.Start(config.TCP_ADDRESS) utils.FatalIfErr("failed to start server", err)}1234567891011121314151234567891011121314151617package 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"`
IsPassTheLimit bool `json:"is_pass_the_limit,omitempty"`
IsTimeOut bool `json:"is_time_out,omitempty"`
AttemptNotFound bool `json:"attempt_not_found,omitempty"`
Message string `json:"message,omitempty"`
}package 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"` IsPassTheLimit bool `json:"is_pass_the_limit,omitempty"` IsTimeOut bool `json:"is_time_out,omitempty"` AttemptNotFound bool `json:"attempt_not_found,omitempty"` Forbidden bool `json:"forbidden,omitempty"` ValidationError bool `json:"validation_error,omitempty"` Message string `json:"message,omitempty"`}12345678910package models
type HealthCheckRequest struct { ExampleCallback func() (string, string)}
type HealthCheckResponse struct { DatabaseStatus string `json:"database_status"` RedisStatus string `json:"redis_status"`}1234567891011121314151617181920212223242526272829303132333435363738394041package repositories
import ( "api.qobiltu.id/config" "api.qobiltu.id/models" "context" "gorm.io/gorm")
type HealthCheckRepository struct { db *gorm.DB}
func NewHealthCheckRepository(db *gorm.DB) *HealthCheckRepository { return &HealthCheckRepository{ db: db, }}
func (r *HealthCheckRepository) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) { res := &models.HealthCheckResponse{}
err := config.RunTx(ctx, r.db, func(tx *gorm.DB) error { if err := tx.Exec("SELECT 1").Error; err != nil { return err }
// call logic from service if needed // instead of writing the logic in the repository // and make sure the param consist of the ctx and request res.DatabaseStatus, res.RedisStatus = req.ExampleCallback()
return nil })
if err != nil { return nil, err }
return res, nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package response
import ( "errors" "fmt")
type PagingInfo struct { HasPreviousPage bool `json:"has_previous_page"` HasNextPage bool `json:"has_next_page"` CurrentPage int `json:"current_page"` PerPage int `json:"per_page"` TotalData int `json:"total_data"` LastPage int `json:"last_page"` From int `json:"from"` To int `json:"to"` TotalDataInCurrentPage int `json:"total_data_in_current_page"` Label string `json:"label"`}
var ErrPageInfo = errors.New("per_page harus lebih besar dari 0 dan offset tidak boleh negatif")
func NewPagingInfo(currentPage, perPage, offset, totalData int) (*PagingInfo, error) { if perPage <= 0 || offset < 0 { return nil, ErrPageInfo }
lastPage := totalData / perPage if totalData%perPage != 0 { lastPage++ }
to := min(offset+perPage, totalData) from := int(0) if to > offset { from = offset + 1 }
if currentPage > lastPage { currentPage = lastPage }
totalDataInCurrentPage := to - offset label := fmt.Sprintf("Menampilkan %d sampai %d dari %d data", from, to, totalData)
return &PagingInfo{ HasPreviousPage: currentPage > 1, HasNextPage: currentPage < lastPage, CurrentPage: currentPage, PerPage: perPage, TotalData: totalData, LastPage: lastPage, From: from, To: to, TotalDataInCurrentPage: totalDataInCurrentPage, Label: label, }, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152package response
import ( errors "api.qobiltu.id/apperror" "api.qobiltu.id/models" goErrors "errors" "fmt" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "net/http")
type ErrorResponse struct { Details string `json:"details"` ValidationErrors []ValidationError `json:"validation_errors,omitempty"` models.Exception}
type API struct { Status string `json:"status"` Message string `json:"message,omitempty"` Data any `json:"data,omitempty"` MetaData any `json:"meta_data"` Error *ErrorResponse `json:"errors,omitempty"`}
type List struct { List any `json:"list"`}
type ValidationError struct { Field string `json:"field"` Message string `json:"message"`}
func HandleError(c *gin.Context, err error) {
apiResponse := API{ Status: "error", Message: "An error occurred, " + err.Error(), Error: &ErrorResponse{ Exception: models.Exception{Message: ""}, }, MetaData: struct{}{}, }
var appErr *errors.AppError
if goErrors.As(err, &appErr) { apiResponse.Error.Details = fmt.Sprintf("%v", appErr.Err)
switch specificErr := appErr.Err.(type) { case errors.ValidationError: validationError := make([]ValidationError, len(specificErr.Errors)) apiResponse.Message = "Validation Error" apiResponse.Error.ValidationErrors = validationError for i, ve := range specificErr.Errors { apiResponse.Error.ValidationErrors[i] = ValidationError{ Field: ve.Field, Message: ve.Message, } } c.JSON(http.StatusBadRequest, apiResponse) return case errors.ConflictError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.DataDuplicate = true c.JSON(http.StatusConflict, apiResponse) return case errors.InternalError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.InternalServerError = true c.JSON(http.StatusInternalServerError, apiResponse) return case errors.NotFoundError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.DataNotFound = true c.JSON(http.StatusNotFound, apiResponse) return case errors.UnauthorizedError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.Unauthorized = true c.JSON(http.StatusUnauthorized, apiResponse) return case errors.ForbiddenError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.Forbidden = true c.JSON(http.StatusForbidden, apiResponse) return case errors.BadRequestError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.BadRequest = true c.JSON(http.StatusBadRequest, apiResponse) return default: apiResponse.Error.Details = "An unexpected error occurred." apiResponse.Error.Exception.InternalServerError = true c.JSON(http.StatusInternalServerError, apiResponse) return } } else if validationErrors, ok := err.(validator.ValidationErrors); ok { apiResponse.Error.Details = "Validation failed for the request." apiResponse.Error.Exception.ValidationError = true apiResponse.Error.ValidationErrors = make([]ValidationError, len(validationErrors)) for i, fe := range validationErrors { apiResponse.Error.ValidationErrors[i] = ValidationError{ Field: fe.Field(), Message: fe.Translate(nil), // adjust if you use translator } } c.JSON(http.StatusBadRequest, apiResponse) return }
c.JSON(http.StatusInternalServerError, apiResponse) apiResponse.Error.Details = err.Error()}
func HandleSuccess(c *gin.Context, message string, statusCode int, data any, metaData any) { apiResponse := API{ Status: "success", Message: message, Data: data, MetaData: metaData, }
if metaData == nil { apiResponse.MetaData = struct{}{} }
c.JSON(statusCode, apiResponse)}
func HandleSuccessWithPaging(c *gin.Context, message string, content any, pagingInfo *PagingInfo) {
apiResponse := API{ Message: message, Status: "success", Data: List{ List: content, }, MetaData: pagingInfo, }
c.JSON(http.StatusOK, apiResponse)}12345package router
func (s *Server) HealthCheckRoute() { s.router.GET("/api/v1/health-check", s.healthCheckController.Check)}1234567485611121378910151617181920211112131415161723242526181920package router
import ( "log"
"api.qobiltu.id/config" "api.qobiltu.id/controller" "api.qobiltu.id/controller" "github.com/gin-gonic/gin")
func StartService() { router := gin.Default() router.Use(gin.Recovery())func (s *Server) setupRoutes() {
s.router.GET("/", controller.HomeController)
router.GET("/", controller.HomeController) AuthRoute(router) UserRoute(router) EmailRoute(router) OptionsRoute(router) AcademyRoute(router) QuizRoute(router) AuthRoute(s.router) UserRoute(s.router) EmailRoute(s.router) OptionsRoute(s.router) AcademyRoute(s.router) QuizRoute(s.router)
err := router.Run(config.TCP_ADDRESS) if err != nil { log.Fatalf("Failed to run server: %v", err) } // another way to register routes s.HealthCheckRoute()}1234567891011121314151617181920212223242526272829303132package router
import ( "api.qobiltu.id/controller/health_check" "github.com/gin-gonic/gin")
type Server struct { router *gin.Engine healthCheckController *health_check_controller.HealthCheckController}
func NewServer( healthCheckController *health_check_controller.HealthCheckController,) (*Server, error) {
router := gin.Default() router.Use(gin.Recovery())
server := &Server{ healthCheckController: healthCheckController, router: router, }
server.setupRoutes()
return server, nil}
func (s *Server) Start(address string) error { return s.router.Run(address)}123456789101112131415package health_check_service
import ( "api.qobiltu.id/repositories")
type HealthCheckService struct { healthCheckRepository *repositories.HealthCheckRepository}
func NewHealthCheckService(healthCheckRepository *repositories.HealthCheckRepository) *HealthCheckService { return &HealthCheckService{ healthCheckRepository: healthCheckRepository, }}123456789101112131415161718192021package health_check_service
import ( "api.qobiltu.id/apperror" "api.qobiltu.id/models" "context")
func (s *HealthCheckService) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) {
req.ExampleCallback = func() (string, string) { return "OK", "OK" }
res, err := s.healthCheckRepository.Check(ctx, req) if err != nil { return nil, apperror.NewInternalError("Failed to check health", err) }
return res, nil}12345456789107891011121314141516171819202122231819202122232425262725262728293031323334353637383940414243444546474849293031323334353637383940414243444546474849505152535455565753545556575859606162635960616263646566676869707172736566676869707172737475767778798081757677787980818283848583848586package services
import ( "errors" "unicode" "errors" "unicode"
"api.qobiltu.id/models" "api.qobiltu.id/repositories" uuid "github.com/satori/go.uuid" "gorm.io/gorm" "api.qobiltu.id/models" "api.qobiltu.id/repositories" uuid "github.com/satori/go.uuid" "gorm.io/gorm")
type RegisterService struct { Service[models.Account, models.Account] Service[models.Account, models.Account]}
func ValidatePassword(password string) models.Exception { var ( hasMinLen = false hasUpper = false hasLower = false hasNumber = false ) var ( hasMinLen = false hasUpper = false hasLower = false hasNumber = false )
if len(password) >= 8 { hasMinLen = true } if len(password) >= 8 { hasMinLen = true }
for _, char := range password { switch { case unicode.IsUpper(char): hasUpper = true break case unicode.IsLower(char): hasLower = true break case unicode.IsDigit(char): hasNumber = true break } } approve := hasMinLen && hasUpper && hasLower && hasNumber if !approve { return models.Exception{ BadRequest: true, Message: "Password must contain at least 8 characters, including uppercase, lowercase, and number!", } } return models.Exception{} for _, char := range password { switch { case unicode.IsUpper(char): hasUpper = true break case unicode.IsLower(char): hasLower = true break case unicode.IsDigit(char): hasNumber = true break } } approve := hasMinLen && hasUpper && hasLower && hasNumber if !approve { return models.Exception{ BadRequest: true, Message: "Password must contain at least 8 characters, including uppercase, lowercase, and number!", } } return models.Exception{}}
func (s *RegisterService) Create() { validatePassword := ValidatePassword(s.Constructor.Password) if validatePassword.BadRequest { s.Exception = validatePassword return } validatePassword := ValidatePassword(s.Constructor.Password) if validatePassword.BadRequest { s.Exception = validatePassword return }
hashedPassword, err := HashPassword(s.Constructor.Password) s.Error = err s.Constructor.Password = hashedPassword s.Constructor.UUID = uuid.NewV4() accountCreated := repositories.CreateAccount(s.Constructor) hashedPassword, err := HashPassword(s.Constructor.Password) s.Error = err s.Constructor.Password = hashedPassword s.Constructor.UUID = uuid.NewV4() accountCreated := repositories.CreateAccount(s.Constructor)
if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) { s.Exception.DataDuplicate = true s.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!" return } else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) { s.Exception.BadRequest = true s.Exception.Message = "Bad request!" return } if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) { s.Exception.DataDuplicate = true s.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!" return } else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) { s.Exception.BadRequest = true 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 } 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" s.Error = accountCreated.RowsError s.Result = accountCreated.Result s.Result.Password = "SECRET"}3 unmodified lines4567783 unmodified linesREADME.md
.qodo
.error
logs/logs/
.idea1234567up-dev: docker compose -f docker-compose.dev.yml up -d
run-dev: go run main.go
.PHONY : up-dev run-dev12345678910111213package assets
import ( "embed")
//go:embed "emails"var EmbeddedFiles embed.FS
const ( EmailConfirmationTemplatePath = "emails/email-confirmation.tmpl" EmailForgotPasswordTemplatePath = "emails/email-forgot-password.tmpl")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{{define "htmlBody"}}<!DOCTYPE html><html><head> <meta charset="UTF-8"> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; } .container { background-color: #ffffff; max-width: 600px; margin: 40px auto; padding: 30px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); color: #333; } .code-box { font-size: 28px; font-weight: bold; letter-spacing: 8px; background: #f0f8ff; border: 2px dashed #007BFF; padding: 15px 25px; margin: 30px 0; text-align: center; border-radius: 6px; color: #007BFF; } .footer { font-size: 12px; color: #aaa; margin-top: 20px; text-align: center; } </style></head><body> <div class="container"> <p>Berikut adalah kode verifikasi Anda:</p> <div class="code-box">{{.VerificationCode}}</div> <p>Silakan masukkan kode ini untuk memverifikasi alamat email Anda. Kode ini akan kedaluwarsa dalam <strong>{{.ExpirationInMinutes}} menit</strong>.</p> <p>Jika Anda tidak meminta ini, abaikan email ini.</p> <p>Salam hormat,<br><strong>Tim Support Qobiltu Indonesia</strong></p> <div class="footer"> Email ini dikirim otomatis oleh sistem. Jangan membalas email ini. </div> </div></body></html>{{end}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{{define "htmlBody"}}<!DOCTYPE html><html><head> <meta charset="UTF-8"> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; } .container { background-color: #ffffff; max-width: 600px; margin: 40px auto; padding: 30px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); color: #333; } .code-box { font-size: 28px; font-weight: bold; letter-spacing: 8px; background: #f0f8ff; border: 2px dashed #007BFF; padding: 15px 25px; margin: 30px 0; text-align: center; border-radius: 6px; color: #007BFF; } .footer { font-size: 12px; color: #aaa; margin-top: 20px; text-align: center; } </style></head><body> <div class="container"> <p>Anda menerima email ini karena ada permintaan untuk mengatur ulang kata sandi akun Anda.</p> <p>Berikut adalah kode verifikasi Anda:</p> <div class="code-box">{{.ResetToken}}</div> <p>Tautan ini akan kedaluwarsa dalam <strong>{{.ExpirationInMinutes}} menit</strong>.</p> <p>Jika Anda tidak meminta pengaturan ulang kata sandi ini, abaikan email ini. Tidak ada perubahan yang akan dilakukan pada akun Anda.</p> <p>Salam hormat,<br><strong>Tim Support Qobiltu Indonesia</strong></p> <div class="footer"> Email ini dikirim otomatis oleh sistem. Jangan membalas email ini. </div> </div></body></html>{{end}}123456789101112131415161718192021222324252627282930313233343536123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package config
import (
"os"
"strconv"
"github.com/joho/godotenv"
)
var ENV string
var TCP_ADDRESS string
var LOG_PATH string
var HOST_ADDRESS string
var HOST_PORT string
var EMAIL_VERIFICATION_DURATION int
var SMTP_SENDER_EMAIL string
var SMTP_SENDER_PASSWORD string
var SMTP_HOST string
var SMTP_PORT string
func init() {
godotenv.Load()
ENV = os.Getenv("ENV")
HOST_ADDRESS = os.Getenv("HOST_ADDRESS")
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"))
SMTP_SENDER_EMAIL = os.Getenv("SMTP_SENDER_EMAIL")
SMTP_SENDER_PASSWORD = os.Getenv("SMTP_SENDER_PASSWORD")
SMTP_HOST = os.Getenv("SMTP_HOST")
SMTP_PORT = os.Getenv("SMTP_PORT")
// Menampilkan nilai variabel lingkungan
}package config
import ( "os" "strconv" "time"
"github.com/joho/godotenv")
var ENV stringvar TCP_ADDRESS stringvar LOG_PATH string
var HOST_ADDRESS stringvar HOST_PORT stringvar EMAIL_VERIFICATION_DURATION int
var SMTP_SENDER_EMAIL stringvar SMTP_SENDER_PASSWORD stringvar SMTP_HOST stringvar SMTP_PORT string
var REDIS_HOST stringvar REDIS_PORT intvar REDIS_PASSWORD stringvar REDIS_DB intvar REDIS_MIN_IDLE_CONNS intvar REDIS_POOL_SIZE intvar REDIS_POOL_TIMEOUT time.Duration
func init() { godotenv.Load() ENV = os.Getenv("ENV") HOST_ADDRESS = os.Getenv("HOST_ADDRESS") 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")) SMTP_SENDER_EMAIL = os.Getenv("SMTP_SENDER_EMAIL") SMTP_SENDER_PASSWORD = os.Getenv("SMTP_SENDER_PASSWORD") SMTP_HOST = os.Getenv("SMTP_HOST") SMTP_PORT = os.Getenv("SMTP_PORT")
REDIS_HOST = getValue(os.Getenv("REDIS_HOST"), "redis", func(s string) (string, error) { return s, nil }) REDIS_PORT = getValue(os.Getenv("REDIS_PORT"), 6379, func(s string) (int, error) { return strconv.Atoi(s) }) REDIS_PASSWORD = getValue(os.Getenv("REDIS_PASSWORD"), "qobiltu", func(s string) (string, error) { return s, nil }) REDIS_DB = getValue(os.Getenv("REDIS_DB"), 0, func(s string) (int, error) { return strconv.Atoi(s) }) REDIS_POOL_SIZE = getValue(os.Getenv("REDIS_POOL_SIZE"), 10, func(s string) (int, error) { return strconv.Atoi(s) }) REDIS_MIN_IDLE_CONNS = getValue(os.Getenv("REDIS_MIN_IDLE_CONNS"), 10, func(s string) (int, error) { return strconv.Atoi(s) }) REDIS_POOL_TIMEOUT = getValue(os.Getenv("REDIS_POOL_TIMEOUT"), time.Second*30, func(s string) (time.Duration, error) { return time.ParseDuration(s) })}
func getValue[T any](value string, defaultValue T, convert func(string) (T, error)) T { if value == "" { return defaultValue } convertedValue, err := convert(value) if err != nil { return defaultValue } return convertedValue}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package controller
import ( "net/http" "reflect"
"api.qobiltu.id/models" "api.qobiltu.id/services"
"github.com/gin-gonic/gin")
func ResponseOK(c *gin.Context, data any) { res := models.SuccessResponse{ Status: "success", Message: "Data retrieved successfully!", Data: data, MetaData: c.Request.Body, } c.JSON(http.StatusOK, res) return}
func ResponseFAIL(c *gin.Context, status int, exception models.Exception) { message := exception.Message exception.Message = "" res := models.ErrorResponse{ Status: "error", Message: message, Errors: exception, MetaData: c.Request.Body, } c.AbortWithStatusJSON(status, res) return}
func SendResponse(c *gin.Context, data services.Service[any, any]) { if reflect.ValueOf(data.Exception).IsNil() { ResponseOK(c, data) } else { if data.Exception.Unauthorized { ResponseFAIL(c, 401, data.Exception) } else if data.Exception.BadRequest { ResponseFAIL(c, 400, data.Exception) } else if data.Exception.DataNotFound { ResponseFAIL(c, 404, data.Exception) } else if data.Exception.InternalServerError { ResponseFAIL(c, 500, data.Exception) } else { ResponseFAIL(c, 403, data.Exception) } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364651234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package controller
import (
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"api.qobiltu.id/utils"
"github.com/gin-gonic/gin"
)
type (
Controllers interface {
RequestJSON(c *gin.Context)
Response(c *gin.Context)
}
Controller[T1 any, T2 any, T3 any] struct {
AccountData models.AccountData
Request T1
Service *services.Service[T2, T3]
}
)
func (controller *Controller[T1, T2, T3]) 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 {
controller.AccountData = cParam.(models.AccountData)
}
errBinding := c.ShouldBindJSON(&controller.Request)
if errBinding != nil {
utils.ResponseFAIL(c, 400, models.Exception{
BadRequest: true,
Message: "Invalid Request!, recheck your request, there's must be some problem about required parameter or type parameter",
})
return
} else {
act()
controller.Response(c)
}
}
func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) {
switch {
case controller.Service.Error != nil:
utils.LogError(controller.Service.Error)
utils.ResponseFAIL(c, 500, models.Exception{
InternalServerError: true,
Message: "Internal Server Error",
})
case controller.Service.Exception.DataDuplicate:
utils.ResponseFAIL(c, 400, controller.Service.Exception)
case controller.Service.Exception.Unauthorized:
utils.ResponseFAIL(c, 401, controller.Service.Exception)
case controller.Service.Exception.DataNotFound:
utils.ResponseFAIL(c, 404, controller.Service.Exception)
case controller.Service.Exception.Message != "":
utils.ResponseFAIL(c, 400, controller.Service.Exception)
default:
utils.ResponseOK(c, controller.Service.Result)
}
}package controller
import ( "api.qobiltu.id/models" "api.qobiltu.id/services" "api.qobiltu.id/utils" "github.com/gin-gonic/gin")
type ( Controllers interface { RequestJSON(c *gin.Context) Response(c *gin.Context) } Controller[T1 any, T2 any, T3 any] struct { AccountData models.AccountData Request T1 Service *services.Service[T2, T3] })
func (controller *Controller[T1, T2, T3]) 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 { controller.AccountData = cParam.(models.AccountData) } errBinding := c.ShouldBindJSON(&controller.Request) if errBinding != nil { ResponseFAIL(c, 400, models.Exception{ BadRequest: true, Message: "Invalid Request!, recheck your request, there's must be some problem about required parameter or type parameter", }) return } else { act() controller.Response(c) }}func (controller *Controller[T1, T2, T3]) Response(c *gin.Context) { switch { case controller.Service.Error != nil: utils.LogError(controller.Service.Error) ResponseFAIL(c, 500, models.Exception{ InternalServerError: true, Message: "Internal Server Error", }) case controller.Service.Exception.DataDuplicate: ResponseFAIL(c, 400, controller.Service.Exception) case controller.Service.Exception.Unauthorized: ResponseFAIL(c, 401, controller.Service.Exception) case controller.Service.Exception.DataNotFound: ResponseFAIL(c, 404, controller.Service.Exception) case controller.Service.Exception.Message != "": ResponseFAIL(c, 400, controller.Service.Exception) default: ResponseOK(c, controller.Service.Result) }}123456789101112131415161718192021123456789101112131415161718192021package controller
import (
"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[models.CreateVerifyEmailRequest, models.EmailVerification, models.EmailVerification]{
Service: &emailVerification.Service,
}
emailVerificationController.HeaderParse(c, func() {
emailVerificationController.Service.Constructor.AccountID = uint(emailVerificationController.AccountData.UserID)
emailVerification.Create()
emailVerificationController.Response(c)
})
}package controller
import ( "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[models.CreateVerifyEmailRequest, models.EmailVerification, models.EmailVerification]{ Service: &emailVerification.Service, } emailVerificationController.HeaderParse(c, func() { emailVerificationController.Service.Constructor.AccountID = emailVerificationController.AccountData.UserID emailVerification.Create() emailVerificationController.Response(c) })
}123456789101112131415161718version: '3.8'
services: db: image: postgres:15 container_name: postgres-db environment: POSTGRES_USER: ${DB_USER:-qobiltu} POSTGRES_PASSWORD: ${DB_PASSWORD:-qobiltu} POSTGRES_DB: ${DB_NAME:-qobiltu} ports: - "5432:5432" volumes: - db-data:/var/lib/postgresql/data restart: always
volumes: db-data:8 unmodified lines91011121314151610 unmodified lines272829303132333435363738394041424344454647484950515253548 unmodified lines env_file: .env ports: - "8080:8080" networks: - qobiltu-network # volumes: # - ./logs:/app/logs # - /home/qobiltu/api-qobiltu:/app10 unmodified lines - "5432:5432" volumes: - /home/qobiltu/postgres-data:/var/lib/postgresql/data networks: - qobiltu-network restart: always
redis: image: redis/redis-stack:7.2.0-v11 container_name: redis-db environment: REDIS_ARGS: "--requirepass ${REDIS_PASSWORD:-qobiltu}" ports: - "8001:8001" - "6379:6379" volumes: - /home/qobiltu/redis-data:/data networks: - qobiltu-network restart: always
volumes: db-data: redis-data:
networks: qobiltu-network: driver: bridge5 unmodified lines67891011121314157 unmodified lines2324252627282930314 unmodified lines3637383940414210 unmodified lines53545556575859607 unmodified lines686970717273745 unmodified lines github.com/gin-gonic/gin v1.10.0 github.com/golang-jwt/jwt/v5 v5.2.1 github.com/gosimple/slug v1.15.0 github.com/hibiken/asynq v0.25.1 github.com/joho/godotenv v1.5.1 github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible github.com/redis/go-redis/v9 v9.7.0 github.com/satori/go.uuid v1.2.0 golang.org/x/crypto v0.36.0 google.golang.org/api v0.228.07 unmodified lines cloud.google.com/go/compute/metadata v0.6.0 // indirect github.com/bytedance/sonic v1.13.1 // indirect github.com/bytedance/sonic/loader v0.2.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.5 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect github.com/gin-contrib/sse v1.0.0 // indirect4 unmodified lines github.com/go-playground/validator/v10 v10.25.0 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect github.com/gosimple/unidecode v1.0.1 // indirect10 unmodified lines github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/spf13/cast v1.7.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect7 unmodified lines golang.org/x/sync v0.12.0 // indirect golang.org/x/sys v0.31.0 // indirect golang.org/x/text v0.23.0 // indirect golang.org/x/time v0.11.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect google.golang.org/grpc v1.71.0 // indirect google.golang.org/protobuf v1.36.6 // indirect3 unmodified lines456789101112131415161718192021222324252627282930313234 unmodified lines67686970717273748 unmodified lines838485868788899017 unmodified lines10810911011111211311411511611711811912012112212326 unmodified lines1501511521531541551561573 unmodified linescloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I=cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg=github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=github.com/bytedance/sonic v1.13.1 h1:Jyd5CIvdFnkOWuKXr+wm4Nyk2h0yAFsr8ucJgEasO3g=github.com/bytedance/sonic v1.13.1/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=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=34 unmodified linesgithub.com/gosimple/slug v1.15.0/go.mod h1:UiRaFH+GEilHstLUmcBgWcI42viBN7mAb818JrYOeFQ=github.com/gosimple/unidecode v1.0.1 h1:hZzFTMMqSswvf0LBJZCZgThIZrpDHFXux9KeGmn6T/o=github.com/gosimple/unidecode v1.0.1/go.mod h1:CP0Cr1Y1kogOtx0bJblKzsVWrqYaqfNOnHzpgWw4Awc=github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw=github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg=github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=8 unmodified linesgithub.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=17 unmodified linesgithub.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=26 unmodified linesgo.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=golang.org/x/arch v0.15.0 h1:QtOrQd0bTUnhNVNndMpLHNWrDmYzZ2KDqSrEymqInZw=golang.org/x/arch v0.15.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE=golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=12345678package mail
type Sender interface { Send(recipient, subject string, htmlContent string, data any) error}
// EmailSender is a global variable to hold the email sendervar EmailSender Sender1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package mail
import ( "errors" "fmt" "github.com/jordan-wright/email" "net/mail" "net/smtp")
var ( ErrEmailEmpty = errors.New("mail is empty") ErrEmailInvalid = errors.New("invalid email"))
// Config menyimpan pengaturan untuk koneksi SMTP.type Config struct { Host string Port string Username string Password string From string}
// SMTP adalah implementasi Sender untuk mengirim mail melalui SMTPtype SMTP struct { name string fromEmailAddress string smtpServerAddress string smtpAuthAddress smtp.Auth}
// New membuat instance baru SMTP dengan konfigurasi.func New(cfg *Config) (Sender, error) { if err := validateEmail(cfg.From); err != nil { return nil, fmt.Errorf("invalid from address: %w", err) }
return &SMTP{ name: cfg.From, fromEmailAddress: cfg.From, smtpServerAddress: fmt.Sprintf("%s:%s", cfg.Host, cfg.Port), smtpAuthAddress: smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host), }, nil}
// Send mengirim mail ke penerima dengan subjek, konten HTML, dan data lainnya.func (s *SMTP) Send(recipient, subject string, htmlContent string, data any) error { e := email.NewEmail() e.From = s.fromEmailAddress e.To = []string{recipient} e.Subject = subject e.HTML = []byte(htmlContent) return s.sendEmail(e)}
func (s *SMTP) sendEmail(e *email.Email) error { return e.Send(s.smtpServerAddress, s.smtpAuthAddress)}
func validateEmail(email string) error { if email == "" { return ErrEmailEmpty }
if _, err := mail.ParseAddress(email); err != nil { return ErrEmailInvalid }
return nil}12345678910111213141234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package main
import (
"fmt"
"api.qobiltu.id/config"
"api.qobiltu.id/router"
)
func main() {
fmt.Println("Server started on ", config.TCP_ADDRESS, ", port :", config.HOST_PORT)
router.StartService()
}package main
import ( "api.qobiltu.id/config" "api.qobiltu.id/controller/health_check" "api.qobiltu.id/mail" "api.qobiltu.id/repositories" "api.qobiltu.id/router" "api.qobiltu.id/services/health_check_service" "api.qobiltu.id/utils" "api.qobiltu.id/worker" "github.com/hibiken/asynq" "log/slog" "net" "strconv")
func main() {
// setup email sender emailConfig := mail.Config{ Host: config.SMTP_HOST, Port: config.SMTP_PORT, From: config.SMTP_SENDER_EMAIL, Username: config.SMTP_SENDER_EMAIL, Password: config.SMTP_SENDER_PASSWORD, }
emailSender, err := mail.New(&emailConfig) utils.FatalIfErr("failed to setup email sender", err) mail.EmailSender = emailSender
// setup redis task distributor and processor asynqRedisOpt := asynq.RedisClientOpt{ Addr: net.JoinHostPort(config.REDIS_HOST, strconv.Itoa(config.REDIS_PORT)), Password: config.REDIS_PASSWORD, DB: config.REDIS_DB, }
taskDistributor := worker.NewRedisTaskDistributor(asynqRedisOpt) taskProcessor := worker.NewRedisTaskProcessor(asynqRedisOpt, emailSender) worker.AsyncTaskDistributor = taskDistributor
// setup repo, service, and controller healthCheckRepository := repositories.NewHealthCheckRepository(config.DB) healthCheckService := health_check_service.NewHealthCheckService(healthCheckRepository) healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)
// start task processor err = taskProcessor.Start() utils.FatalIfErr("failed to start task processor", err) slog.Info("Task processor started")
// create server s, err := router.NewServer(healthCheckController) utils.FatalIfErr("failed to create server", err)
// run server slog.Info("Starting server", "address", config.TCP_ADDRESS, "port", config.HOST_PORT) err = s.Start(config.TCP_ADDRESS) utils.FatalIfErr("failed to start server", err)}1234567891011121314151617181920212223242526272829303132333435363712345678910111213141516171819202122232425262728293031323334353637// auth/auth.go
package middleware
import (
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"api.qobiltu.id/utils"
"github.com/gin-gonic/gin"
)
func AuthUser(c *gin.Context) {
var currAccData models.AccountData
if c.Request.Header["Authorization"] != nil {
token := c.Request.Header["Authorization"]
currAccData.UserID, currAccData.VerifyStatus, currAccData.ErrVerif = services.VerifyToken(token[0])
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!"})
c.Abort()
return
} else {
c.Set("accountData", currAccData)
c.Next()
}
} else {
currAccData.UserID = 0
currAccData.VerifyStatus = "no-token"
currAccData.ErrVerif = nil
utils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "You have to login first!"})
c.Abort()
return
}
}// auth/auth.go
package middleware
import ( "api.qobiltu.id/controller" "api.qobiltu.id/models" "api.qobiltu.id/services" "github.com/gin-gonic/gin")
func AuthUser(c *gin.Context) { var currAccData models.AccountData if c.Request.Header["Authorization"] != nil { token := c.Request.Header["Authorization"]
currAccData.UserID, currAccData.VerifyStatus, currAccData.ErrVerif = services.VerifyToken(token[0])
if currAccData.VerifyStatus == "invalid-token" || currAccData.VerifyStatus == "expired" { currAccData.UserID = 0 controller.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 controller.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "You have to login first!"}) c.Abort() return }
}123456789101112131415161718192021222324123456789101112131415161718192021222324252627package router
import (
"log"
"api.qobiltu.id/config"
"api.qobiltu.id/controller"
"github.com/gin-gonic/gin"
)
func StartService() {
router := gin.Default()
router.GET("/", controller.HomeController)
AuthRoute(router)
UserRoute(router)
EmailRoute(router)
OptionsRoute(router)
AcademyRoute(router)
QuizRoute(router)
err := router.Run(config.TCP_ADDRESS)
if err != nil {
log.Fatalf("Failed to run server: %v", err)
}
}package router
import ( "log"
"api.qobiltu.id/config" "api.qobiltu.id/controller" "github.com/gin-gonic/gin")
func StartService() { router := gin.Default() router.Use(gin.Recovery())
router.GET("/", controller.HomeController) AuthRoute(router) UserRoute(router) EmailRoute(router) OptionsRoute(router) AcademyRoute(router) QuizRoute(router)
err := router.Run(config.TCP_ADDRESS) if err != nil { log.Fatalf("Failed to run server: %v", err) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package services
import (
"crypto/tls"
"fmt"
"log"
"math/rand/v2"
"net/smtp"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
uuid "github.com/satori/go.uuid"
)
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)
token := uint(rand.IntN(999999-100000) + 100000)
s.Constructor.UUID = uuid.NewV4()
repo := repositories.CreateEmailVerification(s.Constructor.UUID, s.Constructor.AccountID, dueTime, token)
s.Error = repo.RowsError
s.Result = repo.Result
// ⬇ Kirim token ke email user menggunakan SMTP
go func(toEmail string, token uint) {
env := config.ENV
from := config.SMTP_SENDER_EMAIL
password := config.SMTP_SENDER_PASSWORD
smtpHost := config.SMTP_HOST
smtpPort := config.SMTP_PORT
to := []string{toEmail}
subject := "Verification token"
body := fmt.Sprintf("Your verification token is: %06d\nPlease use it before it expires.", token)
msg := []byte(fmt.Sprintf("From: %s\r\n", from) +
fmt.Sprintf("To: %s\r\n", toEmail) +
fmt.Sprintf("Subject: %s\r\n", subject) +
"\r\n" + body)
// 1. Connect to the server
conn, err := tls.Dial("tcp", fmt.Sprintf("[%s]:%s", smtpHost, smtpPort), &tls.Config{
InsecureSkipVerify: env != "production", // ⚠️ set false di production
ServerName: smtpHost,
})
// conn, err := net.Dial("tcp", fmt.Sprintf("[%s]:%s", smtpHost, smtpPort))
if err != nil {
s.Error = err
log.Printf("Error sending verification email: %v", err)
return
}
c, err := smtp.NewClient(conn, smtpHost)
if err != nil {
s.Error = err
log.Printf("Error create new client mail: %v", err)
return
}
// 2. Auth
auth := smtp.PlainAuth("", from, password, smtpHost)
if err = c.Auth(auth); err != nil {
s.Error = err
log.Printf("Error auth mail: %v", err)
return
}
// 3. Set From and To
if err = c.Mail(from); err != nil {
s.Error = err
log.Printf("Error set mail from to: %v", err)
return
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
s.Error = err
log.Printf("Error receipt addr: %v", err)
return
}
}
// 4. Send message
wc, err := c.Data()
if err != nil {
s.Error = err
log.Printf("Error data Send Message: %v", err)
return
}
_, err = wc.Write(msg)
if err != nil {
s.Error = err
log.Printf("Error write Send Message: %v", err)
return
}
err = wc.Close()
if err != nil {
s.Error = err
log.Printf("Error close Send Message: %v", err)
return
}
c.Quit()
fmt.Println("Email sent successfully!")
// auth := smtp.PlainAuth("", from, password, smtpHost)
// subject := "Email Verification Token"
// body := fmt.Sprintf("Your verification token is: %06d\nPlease use it before it expires.", token)
// msg := []byte("To: " + toEmail + "\r\n" +
// "Subject: " + subject + "\r\n" +
// "\r\n" +
// body + "\r\n")
// err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, []string{toEmail}, msg)
// if err != nil {
// s.Error = err
// log.Printf("Error sending verification email: %v", err)
// return
// } else {
// log.Printf("Successfully sending verification email: %v", err)
// }
}(accountRepo.Result.Email, token)
// s.Result.Token = 0
}
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
}
if repo.Result.ExpiredAt.Before(time.Now()) {
s.Exception.Unauthorized = true
s.Exception.Message = "Token has expired!"
repositories.UpdateExpiredEmailVerification(s.Constructor.UUID)
s.Delete()
return
}
account := repositories.GetAccountById(repo.Result.AccountID)
account.Result.IsEmailVerified = true
repositories.UpdateAccount(account.Result)
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
}package services
import ( "api.qobiltu.id/utils" "api.qobiltu.id/worker" "context" "github.com/hibiken/asynq" "strconv" "time"
"api.qobiltu.id/config" "api.qobiltu.id/models" "api.qobiltu.id/repositories" uuid "github.com/satori/go.uuid")
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 }
token, err := utils.GenerateToken() if err != nil { s.Error = err s.Exception.InternalServerError = true s.Exception.Message = "failed to generate token for email verification" return }
remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.Hour dueTime := CalculateDueTime(remainingTime) s.Constructor.UUID = uuid.NewV4() repo := repositories.CreateEmailVerification(s.Constructor.UUID, s.Constructor.AccountID, dueTime, uint(token)) s.Error = repo.RowsError s.Result = repo.Result if s.Error != nil { return }
err = worker.AsyncTaskDistributor.DistributeTaskSendVerifyEmail( context.Background(), &worker.PayloadSendVerifyEmail{ EmailAddress: accountRepo.Result.Email, VerificationCode: strconv.Itoa(int(token)), ExpirationInMinutes: int(remainingTime.Minutes()), Subject: worker.TaskSendVerifyEmailSubject, }, []asynq.Option{ asynq.MaxRetry(worker.TaskSendVerifyEmailMaxRetry), asynq.Queue(worker.Critical), }...) if err != nil { s.Error = err s.Exception.InternalServerError = true s.Exception.Message = "failed to send email verification" return }}
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 }
if repo.Result.ExpiredAt.Before(time.Now()) { s.Exception.Unauthorized = true s.Exception.Message = "Token has expired!" repositories.UpdateExpiredEmailVerification(s.Constructor.UUID) s.Delete() return } account := repositories.GetAccountById(repo.Result.AccountID) account.Result.IsEmailVerified = true
repositories.UpdateAccount(account.Result) 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}112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211323456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114package servicespackage services
import (
"fmt"
"log"
"math/rand/v2"
"net/smtp"
"time"
"api.qobiltu.id/config"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
uuid "github.com/satori/go.uuid"
)
type ForgotPasswordService struct {
Service[models.ForgotPassword, models.ForgotPassword]
}
func (s *ForgotPasswordService) Create(email string) {
if email == "" {
s.Exception.BadRequest = true
s.Exception.Message = "Email is required!"
return
}
accountRepo := repositories.GetAccountbyEmail(email)
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)
token := uint(rand.IntN(999999-100000) + 100000)
s.Constructor.UUID = uuid.NewV4()
s.Constructor.ExpiredAt = dueTime
s.Constructor.AccountID = accountRepo.Result.Id
s.Constructor.Token = token
repo := repositories.CreateForgotPassword(s.Constructor)
s.Error = repo.RowsError
s.Result = repo.Result
// ⬇ Kirim token ke email user menggunakan SMTP
go func(toEmail string, token uint) {
from := config.SMTP_SENDER_EMAIL
password := config.SMTP_SENDER_PASSWORD
smtpHost := config.SMTP_HOST
smtpPort := config.SMTP_PORT
auth := smtp.PlainAuth("", from, password, smtpHost)
subject := "Forgot Password Token"
body := fmt.Sprintf("Your Forgot Password token is: %06d\nPlease use it before it expires.", token)
msg := []byte("To: " + toEmail + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
body + "\r\n")
err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, []string{toEmail}, msg)
if err != nil {
s.Error = err
log.Printf("Error sending verification email: %v", err)
return
}
}(accountRepo.Result.Email, token)
// s.Result.Token = 0
}
func (s *ForgotPasswordService) Validate(newPassword *string) {
fgPasswordRepo := repositories.GetForgotPasswordByToken(s.Constructor.Token)
s.Error = fgPasswordRepo.RowsError
if fgPasswordRepo.NoRecord {
s.Exception.DataNotFound = true
s.Exception.Message = "There is no forgot password data with given credentials!"
return
}
if fgPasswordRepo.Result.ExpiredAt.Before(time.Now()) {
s.Exception.Unauthorized = true
s.Exception.Message = "Token has expired!"
return
}
accountRepo := repositories.GetAccountById(fgPasswordRepo.Result.AccountID)
if accountRepo.NoRecord {
s.Error = accountRepo.RowsError
s.Exception.DataNotFound = true
s.Exception.Message = "There is no account data with given credentials!"
return
}
s.Result = fgPasswordRepo.Result
if newPassword == nil {
return
}
// fmt.Println("Previous Account", accountRepo.Result)
// fmt.Println("New password", *newPassword)
hashed_password, _ := HashPassword(*newPassword)
accountRepo.Result.Password = hashed_password
changePassword := repositories.UpdateAccount(accountRepo.Result)
// fmt.Println("New Account", changePassword.Result)
if changePassword.RowsError != nil {
s.Error = changePassword.RowsError
s.Exception.QueryError = true
s.Exception.Message = "Failed to update password!"
return
}
// fgPasswordRepo.Result.Token = 0
}
import ( "api.qobiltu.id/utils" "api.qobiltu.id/worker" "context" "github.com/hibiken/asynq" "strconv" "time"
"api.qobiltu.id/config" "api.qobiltu.id/models" "api.qobiltu.id/repositories" uuid "github.com/satori/go.uuid")
type ForgotPasswordService struct { Service[models.ForgotPassword, models.ForgotPassword]}
func (s *ForgotPasswordService) Create(email string) { if email == "" { s.Exception.BadRequest = true s.Exception.Message = "Email is required!" return } accountRepo := repositories.GetAccountbyEmail(email) if accountRepo.NoRecord { s.Error = accountRepo.RowsError s.Exception.DataNotFound = true s.Exception.Message = "There is no account data with given credentials!" return }
token, err := utils.GenerateToken() if err != nil { s.Error = err s.Exception.InternalServerError = true s.Exception.Message = "failed to generate token for email verification" return }
remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.Hour dueTime := CalculateDueTime(remainingTime)
s.Constructor.UUID = uuid.NewV4() s.Constructor.ExpiredAt = dueTime s.Constructor.AccountID = accountRepo.Result.Id s.Constructor.Token = uint(token) repo := repositories.CreateForgotPassword(s.Constructor) s.Error = repo.RowsError s.Result = repo.Result
err = worker.AsyncTaskDistributor.DistributeTaskSendForgotPasswordEmail( context.Background(), &worker.PayloadSendForgotPasswordEmail{ EmailAddress: accountRepo.Result.Email, ResetToken: strconv.Itoa(int(token)), ExpirationInMinutes: int(remainingTime.Minutes()), Subject: worker.TaskSendForgotPasswordEmailSubject, }, []asynq.Option{ asynq.MaxRetry(worker.TaskSendForgotPasswordEmailMaxRetry), asynq.Queue(worker.Critical), }...) if err != nil { s.Error = err s.Exception.InternalServerError = true s.Exception.Message = "failed to send email verification for forgot password request" return }}
func (s *ForgotPasswordService) Validate(newPassword *string) {
fgPasswordRepo := repositories.GetForgotPasswordByToken(s.Constructor.Token) s.Error = fgPasswordRepo.RowsError if fgPasswordRepo.NoRecord { s.Exception.DataNotFound = true s.Exception.Message = "There is no forgot password data with given credentials!" return } if fgPasswordRepo.Result.ExpiredAt.Before(time.Now()) { s.Exception.Unauthorized = true s.Exception.Message = "Token has expired!" return }
accountRepo := repositories.GetAccountById(fgPasswordRepo.Result.AccountID) if accountRepo.NoRecord { s.Error = accountRepo.RowsError s.Exception.DataNotFound = true s.Exception.Message = "There is no account data with given credentials!" return } s.Result = fgPasswordRepo.Result if newPassword == nil { return } // fmt.Println("Previous Account", accountRepo.Result) // fmt.Println("New password", *newPassword) hashed_password, _ := HashPassword(*newPassword) accountRepo.Result.Password = hashed_password changePassword := repositories.UpdateAccount(accountRepo.Result) // fmt.Println("New Account", changePassword.Result) if changePassword.RowsError != nil { s.Error = changePassword.RowsError s.Exception.QueryError = true s.Exception.Message = "Failed to update password!" return } // fgPasswordRepo.Result.Token = 0
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package services
import (
"errors"
"unicode"
"api.qobiltu.id/models"
"api.qobiltu.id/repositories"
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
)
type RegisterService struct {
Service[models.Account, models.Account]
}
func ValidatePassword(password string) models.Exception {
var (
hasMinLen = false
hasUpper = false
hasLower = false
hasNumber = false
hasSpecial = false
)
if len(password) >= 8 {
hasMinLen = true
}
for _, char := range password {
switch {
case unicode.IsUpper(char):
hasUpper = true
break
case unicode.IsLower(char):
hasLower = true
break
case unicode.IsDigit(char):
hasNumber = true
break
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
break
}
}
approve := hasMinLen && hasUpper && hasLower && hasNumber && hasSpecial
if !approve {
return models.Exception{
BadRequest: true,
Message: "Password must contain at least 8 characters, including uppercase, lowercase, number, and special character!",
}
}
return models.Exception{}
}
func (s *RegisterService) Create() {
validatePassword := ValidatePassword(s.Constructor.Password)
if validatePassword.BadRequest {
s.Exception = validatePassword
return
}
hashed_password, err_hash := HashPassword(s.Constructor.Password)
s.Error = err_hash
s.Constructor.Password = hashed_password
s.Constructor.UUID = uuid.NewV4()
accountCreated := repositories.CreateAccount(s.Constructor)
if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {
s.Exception.DataDuplicate = true
s.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"
return
} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {
s.Exception.BadRequest = true
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"
}package services
import ( "errors" "unicode"
"api.qobiltu.id/models" "api.qobiltu.id/repositories" uuid "github.com/satori/go.uuid" "gorm.io/gorm")
type RegisterService struct { Service[models.Account, models.Account]}
func ValidatePassword(password string) models.Exception { var ( hasMinLen = false hasUpper = false hasLower = false hasNumber = false )
if len(password) >= 8 { hasMinLen = true }
for _, char := range password { switch { case unicode.IsUpper(char): hasUpper = true break case unicode.IsLower(char): hasLower = true break case unicode.IsDigit(char): hasNumber = true break } } approve := hasMinLen && hasUpper && hasLower && hasNumber if !approve { return models.Exception{ BadRequest: true, Message: "Password must contain at least 8 characters, including uppercase, lowercase, and number!", } } return models.Exception{}}
func (s *RegisterService) Create() { validatePassword := ValidatePassword(s.Constructor.Password) if validatePassword.BadRequest { s.Exception = validatePassword return }
hashedPassword, err := HashPassword(s.Constructor.Password) s.Error = err s.Constructor.Password = hashedPassword s.Constructor.UUID = uuid.NewV4() accountCreated := repositories.CreateAccount(s.Constructor)
if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) { s.Exception.DataDuplicate = true s.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!" return } else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) { s.Exception.BadRequest = true 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"}177 unmodified lines178179180181182183184181182183184185186187177 unmodified lines IsCorrect bool `json:"is_correct"`
}
type QuizResult struct {
QuizAttemptID uint `gorm:"column:quiz_attempt_id"`
TotalQuestions int `gorm:"column:total_questions"`
CorrectAnswers int `gorm:"column:correct_answers"`
AverageScore float64 `gorm:"column:average_score"`
QuizAttemptID uint `gorm:"column:quiz_attempt_id" json:"quiz_attempt_id"`
TotalQuestions int `gorm:"column:total_questions" json:"total_questions"`
CorrectAnswers int `gorm:"column:correct_answers" json:"correct_answers"`
AverageScore float64 `gorm:"column:average_score" json:"average_score"`
}
// Gorm table name settings7 unmodified lines8910111112137 unmodified lines "api.qobiltu.id/models"
"api.qobiltu.id/repositories"
)
type AttemptQuizService struct {
Service[models.Quiz, models.QuizAttempt]
}137 unmodified lines13813914014114114214314417 unmodified lines1621631641651651661671682 unmodified lines171172173174174175176177137 unmodified lines ProvinceID uint `json:"province_id"`
}
type Answer struct {
ID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey" json:"id"`
QuestionID uint `json:"question_id"`
Content string `json:"content"`
IsCorrect bool `json:"-"`17 unmodified lines}
type QuizAttempt struct {
ID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey" json:"id"`
AccountID uint `json:"user_id"`
QuizID uint `json:"quiz_id"`
StartedAt time.Time `json:"started_at"`2 unmodified lines Score float64 `json:"score"`
}
type UserAnswer struct {
ID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey" json:"id"`
QuizAttemptID uint `json:"quiz_attempt_id"`
QuestionID uint `json:"question_id"`
SelectedAnswer uint `json:"selected_answer"`16 unmodified lines171819202021222316 unmodified lines questionQuizController.HeaderParse(c, func() {
quizId, _ := strconv.Atoi(c.Param("quiz_id"))
academyId, _ := strconv.Atoi(c.Param("academy_id"))
questionNo, _ := strconv.Atoi(c.Query("question_no"))
questionNo, _ := strconv.Atoi(c.Query("question_no"))
questionQuizController.Service.Constructor.ID = uint(quizId)
questionQuizController.Service.Constructor.AcademyID = uint(academyId)
questionQuiz.Retrieve(questionQuizController.AccountData.UserID, questionNo)143 unmodified lines144145146147147148149150143 unmodified lines IsCorrect bool `json:"-"`
}
type Question struct {
ID uint `gorm:"primaryKey"`
ID uint `gorm:"primaryKey" json:"id"`
QuizID uint `json:"quiz_id"`
Content string `json:"content"`
Order int `json:"order"`16 unmodified lines171819202021222323242516 unmodified lines quizAnswerController.RequestJSON(c, func() {
quizId, _ := strconv.Atoi(c.Param("quiz_id"))
academyId, _ := strconv.Atoi(c.Param("academy_id"))
questionNo, _ := strconv.Atoi(c.Query("question_no"))
quizAnswerController.Service.Constructor.ID = uint(quizId)
quizAnswerController.Service.Constructor.AcademyID = uint(academyId)
quizAnswer.Update(quizAnswerController.AccountData.UserID, questionNo, quizAnswerController.Request.Answer)
quizAnswer.Update(quizAnswerController.AccountData.UserID, quizAnswerController.Request.QuestionNo, quizAnswerController.Request.Answer)
})
}10 unmodified lines111213141415161717181920212222232425262710 unmodified lines
func Question(c *gin.Context) {
questionQuiz := services.QuestionQuizService{}
questionQuizController := controller.Controller[models.QuestionQuizRequest, models.Quiz, models.QuestionResponse]{
questionQuizController := controller.Controller[any, models.Quiz, models.QuestionResponse]{
Service: &questionQuiz.Service,
}
questionQuizController.RequestJSON(c, func() {
questionQuizController.HeaderParse(c, func() {
quizId, _ := strconv.Atoi(c.Param("quiz_id"))
academyId, _ := strconv.Atoi(c.Param("academy_id"))
questionNo, _ := strconv.Atoi(c.Query("question_no"))
questionQuizController.Service.Constructor.ID = uint(quizId)
questionQuizController.Service.Constructor.AcademyID = uint(academyId)
questionQuiz.Retrieve(questionQuizController.AccountData.UserID, questionQuizController.Request.QuestionNo)
questionQuiz.Retrieve(questionQuizController.AccountData.UserID, questionNo)
questionQuizController.Response(c)
})
}16 unmodified lines1718192021222223242516 unmodified lines quizAnswerController.RequestJSON(c, func() {
quizId, _ := strconv.Atoi(c.Param("quiz_id"))
academyId, _ := strconv.Atoi(c.Param("academy_id"))
questionNo, _ := strconv.Atoi(c.Query("question_no"))
quizAnswerController.Service.Constructor.ID = uint(quizId)
quizAnswerController.Service.Constructor.AcademyID = uint(academyId)
quizAnswer.Update(quizAnswerController.AccountData.UserID, quizAnswerController.Request.QuestionNo, quizAnswerController.Request.Answer)
quizAnswer.Update(quizAnswerController.AccountData.UserID, questionNo, quizAnswerController.Request.Answer)
})
}13 unmodified lines1415161717181920212223242513 unmodified lines attemptQuizController := controller.Controller[any, models.Quiz, models.QuizAttempt]{
Service: &attemptQuiz.Service,
}
attemptQuizController.RequestJSON(c, func() {
attemptQuizController.HeaderParse(c, func() {
quizId, _ := strconv.Atoi(c.Param("quiz_id"))
academyId, _ := strconv.Atoi(c.Param("academy_id"))
attemptQuizController.Service.Constructor.ID = uint(quizId)
attemptQuizController.Service.Constructor.AcademyID = uint(academyId)
attemptQuiz.Create(attemptQuizController.AccountData.UserID)
attemptQuizController.Response(c)
})
}1234567891011121314151617181920212223package controller
import (
"strconv"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func Submit(c *gin.Context) {
submitQuiz := services.SubmitQuizService{}
submitQuizController := controller.Controller[any, models.QuizAttempt, models.QuizResultResponse]{
Service: &submitQuiz.Service,
}
submitQuizController.HeaderParse(c, func() {
quizId, _ := strconv.Atoi(c.Param("attempt_id"))
submitQuizController.Service.Constructor.ID = uint(quizId)
submitQuiz.Create(submitQuizController.AccountData.UserID)
submitQuizController.Response(c)
})
}176 unmodified lines177178179180181182183184185186187188176 unmodified lines SelectedAnswer uint `json:"selected_answer"`
IsCorrect bool `json:"is_correct"`
}
type QuizResult struct {
QuizAttemptID uint `gorm:"column:quiz_attempt_id"`
TotalQuestions int `gorm:"column:total_questions"`
CorrectAnswers int `gorm:"column:correct_answers"`
AverageScore float64 `gorm:"column:average_score"`
}
// Gorm table name settings
func (Account) TableName() string { return "account" }53 unmodified lines545556575859606153 unmodified lines Answer []Answer `json:"answer_options"`
UserAnswer int `json:"current_user_answer"`
}
type QuizResultResponse struct {
QuizAttempt QuizAttempt `json:"quiz_attempt"`
Result QuizResult `json:"result"`
}.github/workflows/main.yml+1
apperror/apperror.goAdded+168
config/database_connection_config.go+80-79
config/tx.goAdded+34
controller/health_check/health_check_controller.goAdded+31
main.go+16-1
models/exception_model.go+17-15
models/health_check_model.goAdded+10
repositories/health_check_repository.goAdded+41
response/paging.goAdded+58
response/response.goAdded+152
router/health_check_route.goAdded+5
router/router.go+12-19
router/server.goAdded+32
services/health_check_service/health_check_service.goAdded+15
services/health_check_service/health_check_service_check.goAdded+21
services/register_service.go+66-66
space/.gitignore+2-1
space/MakefileAdded+7
space/assets/efs.goAdded+13
space/assets/emails/email-confirmation.tmplAdded+55
space/assets/emails/email-forgot-password.tmplAdded+56
space/config/config.go+63-36
space/controller/api_response.goAdded+53
space/controller/controller.go+65-65
space/controller/email/email_create_verification_controller.go+21-21
space/docker-compose.dev.ymlAdded+18
space/docker-compose.yml+23
space/go.mod+9
space/go.sum+22
space/mail/sender.goAdded+8
space/mail/smtp.goAdded+71
space/main.go+62-14
space/middleware/authentication_middleware.go+37-37
space/router/router.go+27-24
space/services/email_verification_service.go+101-181
space/services/forgot_password_service.go+114-113
space/services/register_service.go+86-86
space/space/models/database_orm_model.go+4-4
space/space/services/academy_quiz_service.go-1
space/space/space/models/database_orm_model.go+3-3
space/space/space/space/controller/quiz/question_quiz_controller.go+1-1
space/space/space/space/models/database_orm_model.go+1-1
space/space/space/space/space/controller/quiz/answer_quiz_controller.go+2-2
space/space/space/space/space/controller/quiz/question_quiz_controller.go+5-3
space/space/space/space/space/space/controller/quiz/answer_quiz_controller.go+2-1
space/space/space/space/space/space/space/controller/quiz/attempt_quiz_controller.go+2-1
space/space/space/space/space/space/space/controller/quiz/submit_quiz_controller.goAdded+23
space/space/space/space/space/space/space/models/database_orm_model.go+6
space/space/space/space/space/space/space/models/response_model.go+5