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 lines2526272824 unmodified linesgit pull origin maindocker-compose down -vdocker-compose up --build -dEOF24 unmodified lines252627282924 unmodified linesgit pull origin maindocker-compose down -vdocker-compose up --build -ddocker image prune -fEOF
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168package 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}, }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879package configimport ("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.DBvar err errorvar Salt stringfunc 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-migrationAutoMigrateAll(DB)}func AutoMigrateAll(db *gorm.DB) {// Enable logger to see SQL logsdb.Logger.LogMode(logger.Info)// Auto-migrate all modelserr := 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.")}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package configimport ("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 stringfunc 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-migrationAutoMigrateAll(DB)}func AutoMigrateAll(db *gorm.DB) {// Enable logger to see SQL logsdb.Logger.LogMode(logger.Info)// Auto-migrate all modelserr := 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 line2345678928 unmodified lines383940414243444546471 unmodified lineimport ("api.qobiltu.id/config""api.qobiltu.id/mail""api.qobiltu.id/router""api.qobiltu.id/utils""api.qobiltu.id/worker""github.com/hibiken/asynq"28 unmodified linestaskProcessor := worker.NewRedisTaskProcessor(asynqRedisOpt, emailSender)worker.AsyncTaskDistributor = taskDistributorerr = taskProcessor.Start()utils.FatalIfErr("failed to start task processor", err)slog.Info("Task processor started")slog.Info("Starting server", "address", config.TCP_ADDRESS, "port", config.HOST_PORT)router.StartService()}1 unmodified line2345678910111228 unmodified lines414243444546474849505152535455565758596061621 unmodified lineimport ("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 linestaskProcessor := worker.NewRedisTaskProcessor(asynqRedisOpt, emailSender)worker.AsyncTaskDistributor = taskDistributor// setup repo, service, and controllerhealthCheckRepository := repositories.NewHealthCheckRepository(config.DB)healthCheckService := health_check_service.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)// start task processorerr = taskProcessor.Start()utils.FatalIfErr("failed to start task processor", err)slog.Info("Task processor started")// create servers, err := router.NewServer(healthCheckController)utils.FatalIfErr("failed to create server", err)// run serverslog.Info("Starting server", "address", config.TCP_ADDRESS, "port", config.HOST_PORT)err = s.Start(config.TCP_ADDRESS)utils.FatalIfErr("failed to start server", err)}
123456789101112131415package modelstype 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"`}1234567891011121314151617package modelstype 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)}123456789101112131415161718192021222324252627package routerimport ("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)}}1234567891011121314151617181920package routerimport ("api.qobiltu.id/controller")func (s *Server) setupRoutes() {s.router.GET("/", controller.HomeController)AuthRoute(s.router)UserRoute(s.router)EmailRoute(s.router)OptionsRoute(s.router)AcademyRoute(s.router)QuizRoute(s.router)// another way to register routess.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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package servicesimport ("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 = falsehasUpper = falsehasLower = falsehasNumber = false)if len(password) >= 8 {hasMinLen = true}for _, char := range password {switch {case unicode.IsUpper(char):hasUpper = truebreakcase unicode.IsLower(char):hasLower = truebreakcase unicode.IsDigit(char):hasNumber = truebreak}}approve := hasMinLen && hasUpper && hasLower && hasNumberif !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 = validatePasswordreturn}hashedPassword, err := HashPassword(s.Constructor.Password)s.Error = errs.Constructor.Password = hashedPasswords.Constructor.UUID = uuid.NewV4()accountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}userProfile := UserProfileService{}userProfile.Constructor.AccountID = accountCreated.Result.IduserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = accountCreated.RowsErrors.Result = accountCreated.Results.Result.Password = "SECRET"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package servicesimport ("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 = falsehasUpper = falsehasLower = falsehasNumber = false)if len(password) >= 8 {hasMinLen = true}for _, char := range password {switch {case unicode.IsUpper(char):hasUpper = truebreakcase unicode.IsLower(char):hasLower = truebreakcase unicode.IsDigit(char):hasNumber = truebreak}}approve := hasMinLen && hasUpper && hasLower && hasNumberif !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 = validatePasswordreturn}hashedPassword, err := HashPassword(s.Constructor.Password)s.Error = errs.Constructor.Password = hashedPasswords.Constructor.UUID = uuid.NewV4()accountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}userProfile := UserProfileService{}userProfile.Constructor.AccountID = accountCreated.Result.IduserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = accountCreated.RowsErrors.Result = accountCreated.Results.Result.Password = "SECRET"}
3 unmodified lines45673 unmodified linesREADME.md.qodo.errorlogs/3 unmodified lines456783 unmodified linesREADME.md.qodo.errorlogs/.idea
1234567up-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}}123456789101112131415161718192021222324252627282930313233343536package configimport ("os""strconv""github.com/joho/godotenv")var ENV stringvar TCP_ADDRESS stringvar LOG_PATH stringvar HOST_ADDRESS stringvar HOST_PORT stringvar EMAIL_VERIFICATION_DURATION intvar SMTP_SENDER_EMAIL stringvar SMTP_SENDER_PASSWORD stringvar SMTP_HOST stringvar SMTP_PORT stringfunc init() {godotenv.Load()ENV = os.Getenv("ENV")HOST_ADDRESS = os.Getenv("HOST_ADDRESS")HOST_PORT = os.Getenv("HOST_PORT")TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORTLOG_PATH = os.Getenv("LOG_PATH")EMAIL_VERIFICATION_DURATION, _ = strconv.Atoi(os.Getenv("EMAIL_VERIFICATION_DURATION"))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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package configimport ("os""strconv""time""github.com/joho/godotenv")var ENV stringvar TCP_ADDRESS stringvar LOG_PATH stringvar HOST_ADDRESS stringvar HOST_PORT stringvar EMAIL_VERIFICATION_DURATION intvar SMTP_SENDER_EMAIL stringvar SMTP_SENDER_PASSWORD stringvar SMTP_HOST stringvar SMTP_PORT stringvar 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.Durationfunc init() {godotenv.Load()ENV = os.Getenv("ENV")HOST_ADDRESS = os.Getenv("HOST_ADDRESS")HOST_PORT = os.Getenv("HOST_PORT")TCP_ADDRESS = HOST_ADDRESS + ":" + HOST_PORTLOG_PATH = os.Getenv("LOG_PATH")EMAIL_VERIFICATION_DURATION, _ = strconv.Atoi(os.Getenv("EMAIL_VERIFICATION_DURATION"))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) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package controllerimport ("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.AccountDataRequest T1Service *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)}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465package controllerimport ("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.AccountDataRequest T1Service *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)}}
123456789101112131415161718192021package controllerimport ("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)})}123456789101112131415161718192021package controllerimport ("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.UserIDemailVerification.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 lines9101112131410 unmodified lines252627282930318 unmodified linesenv_file: .envports:- "8080:8080"# volumes:# - ./logs:/app/logs# - /home/qobiltu/api-qobiltu:/app10 unmodified lines- "5432:5432"volumes:- /home/qobiltu/postgres-data:/var/lib/postgresql/datarestart: alwaysvolumes:db-data:8 unmodified lines91011121314151610 unmodified lines272829303132333435363738394041424344454647484950515253548 unmodified linesenv_file: .envports:- "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/datanetworks:- qobiltu-networkrestart: alwaysredis:image: redis/redis-stack:7.2.0-v11container_name: redis-dbenvironment:REDIS_ARGS: "--requirepass ${REDIS_PASSWORD:-qobiltu}"ports:- "8001:8001"- "6379:6379"volumes:- /home/qobiltu/redis-data:/datanetworks:- qobiltu-networkrestart: alwaysvolumes:db-data:redis-data:networks:qobiltu-network:driver: bridge
5 unmodified lines67891011127 unmodified lines202122232425264 unmodified lines31323334353610 unmodified lines4748495051527 unmodified lines6061626364655 unmodified linesgithub.com/gin-gonic/gin v1.10.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/gosimple/slug v1.15.0github.com/joho/godotenv v1.5.1github.com/satori/go.uuid v1.2.0golang.org/x/crypto v0.36.0google.golang.org/api v0.228.07 unmodified linescloud.google.com/go/compute/metadata v0.6.0 // indirectgithub.com/bytedance/sonic v1.13.1 // indirectgithub.com/bytedance/sonic/loader v0.2.4 // indirectgithub.com/cloudwego/base64x v0.1.5 // indirectgithub.com/felixge/httpsnoop v1.0.4 // indirectgithub.com/gabriel-vasile/mimetype v1.4.8 // indirectgithub.com/gin-contrib/sse v1.0.0 // indirect4 unmodified linesgithub.com/go-playground/validator/v10 v10.25.0 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirectgithub.com/googleapis/gax-go/v2 v2.14.1 // indirectgithub.com/gosimple/unidecode v1.0.1 // indirect10 unmodified linesgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.2.3 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.12 // indirectgo.opentelemetry.io/auto/sdk v1.1.0 // indirect7 unmodified linesgolang.org/x/sync v0.12.0 // indirectgolang.org/x/sys v0.31.0 // indirectgolang.org/x/text v0.23.0 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirectgoogle.golang.org/grpc v1.71.0 // indirectgoogle.golang.org/protobuf v1.36.6 // indirect5 unmodified lines67891011121314157 unmodified lines2324252627282930314 unmodified lines3637383940414210 unmodified lines53545556575859607 unmodified lines686970717273745 unmodified linesgithub.com/gin-gonic/gin v1.10.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/gosimple/slug v1.15.0github.com/hibiken/asynq v0.25.1github.com/joho/godotenv v1.5.1github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatiblegithub.com/redis/go-redis/v9 v9.7.0github.com/satori/go.uuid v1.2.0golang.org/x/crypto v0.36.0google.golang.org/api v0.228.07 unmodified linescloud.google.com/go/compute/metadata v0.6.0 // indirectgithub.com/bytedance/sonic v1.13.1 // indirectgithub.com/bytedance/sonic/loader v0.2.4 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/cloudwego/base64x v0.1.5 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirectgithub.com/felixge/httpsnoop v1.0.4 // indirectgithub.com/gabriel-vasile/mimetype v1.4.8 // indirectgithub.com/gin-contrib/sse v1.0.0 // indirect4 unmodified linesgithub.com/go-playground/validator/v10 v10.25.0 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirectgithub.com/googleapis/gax-go/v2 v2.14.1 // indirectgithub.com/gosimple/unidecode v1.0.1 // indirect10 unmodified linesgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.2.3 // indirectgithub.com/robfig/cron/v3 v3.0.1 // indirectgithub.com/spf13/cast v1.7.0 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.12 // indirectgo.opentelemetry.io/auto/sdk v1.1.0 // indirect7 unmodified linesgolang.org/x/sync v0.12.0 // indirectgolang.org/x/sys v0.31.0 // indirectgolang.org/x/text v0.23.0 // indirectgolang.org/x/time v0.11.0 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirectgoogle.golang.org/grpc v1.71.0 // indirectgoogle.golang.org/protobuf v1.36.6 // indirect
3 unmodified lines4567891011121314151617181920212234 unmodified lines5758596061628 unmodified lines71727374757617 unmodified lines94959697989910010110210326 unmodified lines1301311321331341353 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/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/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/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=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/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/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/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/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=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=3 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}1234567891011121314package mainimport ("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()}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package mainimport ("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 senderemailConfig := 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 processorasynqRedisOpt := 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 controllerhealthCheckRepository := repositories.NewHealthCheckRepository(config.DB)healthCheckService := health_check_service.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)// start task processorerr = taskProcessor.Start()utils.FatalIfErr("failed to start task processor", err)slog.Info("Task processor started")// create servers, err := router.NewServer(healthCheckController)utils.FatalIfErr("failed to create server", err)// run serverslog.Info("Starting server", "address", config.TCP_ADDRESS, "port", config.HOST_PORT)err = s.Start(config.TCP_ADDRESS)utils.FatalIfErr("failed to start server", err)}
12345678910111213141516171819202122232425262728293031323334353637// auth/auth.gopackage middlewareimport ("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.AccountDataif 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 = 0utils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "Your session is expired, Please re-Login!"})c.Abort()return} else {c.Set("accountData", currAccData)c.Next()}} else {currAccData.UserID = 0currAccData.VerifyStatus = "no-token"currAccData.ErrVerif = nilutils.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "You have to login first!"})c.Abort()return}}12345678910111213141516171819202122232425262728293031323334353637// auth/auth.gopackage middlewareimport ("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.AccountDataif 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 = 0controller.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "Your session is expired, Please re-Login!"})c.Abort()return} else {c.Set("accountData", currAccData)c.Next()}} else {currAccData.UserID = 0currAccData.VerifyStatus = "no-token"currAccData.ErrVerif = nilcontroller.ResponseFAIL(c, 401, models.Exception{Unauthorized: true, Message: "You have to login first!"})c.Abort()return}}
123456789101112131415161718192021222324package routerimport ("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)}}123456789101112131415161718192021222324252627package routerimport ("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)}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181package servicesimport ("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.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := 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.RowsErrors.Result = repo.Result// ⬇ Kirim token ke email user menggunakan SMTPgo func(toEmail string, token uint) {env := config.ENVfrom := config.SMTP_SENDER_EMAILpassword := config.SMTP_SENDER_PASSWORDsmtpHost := config.SMTP_HOSTsmtpPort := config.SMTP_PORTto := []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 serverconn, err := tls.Dial("tcp", fmt.Sprintf("[%s]:%s", smtpHost, smtpPort), &tls.Config{InsecureSkipVerify: env != "production", // ⚠️ set false di productionServerName: smtpHost,})// conn, err := net.Dial("tcp", fmt.Sprintf("[%s]:%s", smtpHost, smtpPort))if err != nil {s.Error = errlog.Printf("Error sending verification email: %v", err)return}c, err := smtp.NewClient(conn, smtpHost)if err != nil {s.Error = errlog.Printf("Error create new client mail: %v", err)return}// 2. Authauth := smtp.PlainAuth("", from, password, smtpHost)if err = c.Auth(auth); err != nil {s.Error = errlog.Printf("Error auth mail: %v", err)return}// 3. Set From and Toif err = c.Mail(from); err != nil {s.Error = errlog.Printf("Error set mail from to: %v", err)return}for _, addr := range to {if err = c.Rcpt(addr); err != nil {s.Error = errlog.Printf("Error receipt addr: %v", err)return}}// 4. Send messagewc, err := c.Data()if err != nil {s.Error = errlog.Printf("Error data Send Message: %v", err)return}_, err = wc.Write(msg)if err != nil {s.Error = errlog.Printf("Error write Send Message: %v", err)return}err = wc.Close()if err != nil {s.Error = errlog.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.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}if repo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"repositories.UpdateExpiredEmailVerification(s.Constructor.UUID)s.Delete()return}account := repositories.GetAccountById(repo.Result.AccountID)account.Result.IsEmailVerified = truerepositories.UpdateAccount(account.Result)s.Result = repo.Result}func (s *EmailVerificationService) Delete() {repo := repositories.DeleteEmailVerification(s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}s.Result = repo.Result}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package servicesimport ("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.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}token, err := utils.GenerateToken()if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to generate token for email verification"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := CalculateDueTime(remainingTime)s.Constructor.UUID = uuid.NewV4()repo := repositories.CreateEmailVerification(s.Constructor.UUID, s.Constructor.AccountID, dueTime, uint(token))s.Error = repo.RowsErrors.Result = repo.Resultif 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 = errs.Exception.InternalServerError = trues.Exception.Message = "failed to send email verification"return}}func (s *EmailVerificationService) Validate() {repo := repositories.GetEmailVerification(s.Constructor.AccountID, s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}if repo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"repositories.UpdateExpiredEmailVerification(s.Constructor.UUID)s.Delete()return}account := repositories.GetAccountById(repo.Result.AccountID)account.Result.IsEmailVerified = truerepositories.UpdateAccount(account.Result)s.Result = repo.Result}func (s *EmailVerificationService) Delete() {repo := repositories.DeleteEmailVerification(s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}s.Result = repo.Result}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package servicesimport ("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 = trues.Exception.Message = "Email is required!"return}accountRepo := repositories.GetAccountbyEmail(email)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := CalculateDueTime(remainingTime)token := uint(rand.IntN(999999-100000) + 100000)s.Constructor.UUID = uuid.NewV4()s.Constructor.ExpiredAt = dueTimes.Constructor.AccountID = accountRepo.Result.Ids.Constructor.Token = tokenrepo := repositories.CreateForgotPassword(s.Constructor)s.Error = repo.RowsErrors.Result = repo.Result// ⬇ Kirim token ke email user menggunakan SMTPgo func(toEmail string, token uint) {from := config.SMTP_SENDER_EMAILpassword := config.SMTP_SENDER_PASSWORDsmtpHost := config.SMTP_HOSTsmtpPort := config.SMTP_PORTauth := 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 = errlog.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.RowsErrorif fgPasswordRepo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no forgot password data with given credentials!"return}if fgPasswordRepo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"return}accountRepo := repositories.GetAccountById(fgPasswordRepo.Result.AccountID)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}s.Result = fgPasswordRepo.Resultif newPassword == nil {return}// fmt.Println("Previous Account", accountRepo.Result)// fmt.Println("New password", *newPassword)hashed_password, _ := HashPassword(*newPassword)accountRepo.Result.Password = hashed_passwordchangePassword := repositories.UpdateAccount(accountRepo.Result)// fmt.Println("New Account", changePassword.Result)if changePassword.RowsError != nil {s.Error = changePassword.RowsErrors.Exception.QueryError = trues.Exception.Message = "Failed to update password!"return}// fgPasswordRepo.Result.Token = 0}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114package servicesimport ("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 = trues.Exception.Message = "Email is required!"return}accountRepo := repositories.GetAccountbyEmail(email)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}token, err := utils.GenerateToken()if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to generate token for email verification"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := CalculateDueTime(remainingTime)s.Constructor.UUID = uuid.NewV4()s.Constructor.ExpiredAt = dueTimes.Constructor.AccountID = accountRepo.Result.Ids.Constructor.Token = uint(token)repo := repositories.CreateForgotPassword(s.Constructor)s.Error = repo.RowsErrors.Result = repo.Resulterr = 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 = errs.Exception.InternalServerError = trues.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.RowsErrorif fgPasswordRepo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no forgot password data with given credentials!"return}if fgPasswordRepo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"return}accountRepo := repositories.GetAccountById(fgPasswordRepo.Result.AccountID)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}s.Result = fgPasswordRepo.Resultif newPassword == nil {return}// fmt.Println("Previous Account", accountRepo.Result)// fmt.Println("New password", *newPassword)hashed_password, _ := HashPassword(*newPassword)accountRepo.Result.Password = hashed_passwordchangePassword := repositories.UpdateAccount(accountRepo.Result)// fmt.Println("New Account", changePassword.Result)if changePassword.RowsError != nil {s.Error = changePassword.RowsErrors.Exception.QueryError = trues.Exception.Message = "Failed to update password!"return}// fgPasswordRepo.Result.Token = 0}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package servicesimport ("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 = falsehasUpper = falsehasLower = falsehasNumber = falsehasSpecial = false)if len(password) >= 8 {hasMinLen = true}for _, char := range password {switch {case unicode.IsUpper(char):hasUpper = truebreakcase unicode.IsLower(char):hasLower = truebreakcase unicode.IsDigit(char):hasNumber = truebreakcase unicode.IsPunct(char) || unicode.IsSymbol(char):hasSpecial = truebreak}}approve := hasMinLen && hasUpper && hasLower && hasNumber && hasSpecialif !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 = validatePasswordreturn}hashed_password, err_hash := HashPassword(s.Constructor.Password)s.Error = err_hashs.Constructor.Password = hashed_passwords.Constructor.UUID = uuid.NewV4()accountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}userProfile := UserProfileService{}userProfile.Constructor.AccountID = accountCreated.Result.IduserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = accountCreated.RowsErrors.Result = accountCreated.Results.Result.Password = "SECRET"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586package servicesimport ("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 = falsehasUpper = falsehasLower = falsehasNumber = false)if len(password) >= 8 {hasMinLen = true}for _, char := range password {switch {case unicode.IsUpper(char):hasUpper = truebreakcase unicode.IsLower(char):hasLower = truebreakcase unicode.IsDigit(char):hasNumber = truebreak}}approve := hasMinLen && hasUpper && hasLower && hasNumberif !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 = validatePasswordreturn}hashedPassword, err := HashPassword(s.Constructor.Password)s.Error = errs.Constructor.Password = hashedPasswords.Constructor.UUID = uuid.NewV4()accountCreated := repositories.CreateAccount(s.Constructor)if errors.Is(accountCreated.RowsError, gorm.ErrDuplicatedKey) {s.Exception.DataDuplicate = trues.Exception.Message = "Account with email " + s.Constructor.Email + " already exists!"return} else if errors.Is(accountCreated.RowsError, gorm.ErrModelAccessibleFieldsRequired) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidData) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidValue) || errors.Is(accountCreated.RowsError, gorm.ErrInvalidField) {s.Exception.BadRequest = trues.Exception.Message = "Bad request!"return}userProfile := UserProfileService{}userProfile.Constructor.AccountID = accountCreated.Result.IduserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = accountCreated.RowsErrors.Result = accountCreated.Results.Result.Password = "SECRET"}
177 unmodified lines178179180181182183184185186187177 unmodified linesIsCorrect 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 settings177 unmodified lines178179180181182183184185186187177 unmodified linesIsCorrect bool `json:"is_correct"`}type QuizResult struct {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 settings
7 unmodified lines8910111213147 unmodified lines"api.qobiltu.id/models""api.qobiltu.id/repositories")type AttemptQuizService struct {Service[models.Quiz, models.QuizAttempt]}7 unmodified lines89101112137 unmodified lines"api.qobiltu.id/models""api.qobiltu.id/repositories")type AttemptQuizService struct {Service[models.Quiz, models.QuizAttempt]}
137 unmodified lines13813914014114214314417 unmodified lines1621631641651661671682 unmodified lines171172173174175176177137 unmodified linesProvinceID uint `json:"province_id"`}type Answer struct {ID uint `gorm:"primaryKey"`QuestionID uint `json:"question_id"`Content string `json:"content"`IsCorrect bool `json:"-"`17 unmodified lines}type QuizAttempt struct {ID uint `gorm:"primaryKey"`AccountID uint `json:"user_id"`QuizID uint `json:"quiz_id"`StartedAt time.Time `json:"started_at"`2 unmodified linesScore float64 `json:"score"`}type UserAnswer struct {ID uint `gorm:"primaryKey"`QuizAttemptID uint `json:"quiz_attempt_id"`QuestionID uint `json:"question_id"`SelectedAnswer uint `json:"selected_answer"`137 unmodified lines13813914014114214314417 unmodified lines1621631641651661671682 unmodified lines171172173174175176177137 unmodified linesProvinceID uint `json:"province_id"`}type Answer struct {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" json:"id"`AccountID uint `json:"user_id"`QuizID uint `json:"quiz_id"`StartedAt time.Time `json:"started_at"`2 unmodified linesScore float64 `json:"score"`}type UserAnswer struct {ID uint `gorm:"primaryKey" json:"id"`QuizAttemptID uint `json:"quiz_attempt_id"`QuestionID uint `json:"question_id"`SelectedAnswer uint `json:"selected_answer"`
16 unmodified lines1718192021222316 unmodified linesquestionQuizController.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, questionNo)16 unmodified lines1718192021222316 unmodified linesquestionQuizController.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, questionNo)
143 unmodified lines144145146147148149150143 unmodified linesIsCorrect bool `json:"-"`}type Question struct {ID uint `gorm:"primaryKey"`QuizID uint `json:"quiz_id"`Content string `json:"content"`Order int `json:"order"`143 unmodified lines144145146147148149150143 unmodified linesIsCorrect bool `json:"-"`}type Question struct {ID uint `gorm:"primaryKey" json:"id"`QuizID uint `json:"quiz_id"`Content string `json:"content"`Order int `json:"order"`
16 unmodified lines17181920212223242516 unmodified linesquizAnswerController.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)})}16 unmodified lines17181920212223242516 unmodified linesquizAnswerController.RequestJSON(c, func() {quizId, _ := strconv.Atoi(c.Param("quiz_id"))academyId, _ := strconv.Atoi(c.Param("academy_id"))quizAnswerController.Service.Constructor.ID = uint(quizId)quizAnswerController.Service.Constructor.AcademyID = uint(academyId)quizAnswer.Update(quizAnswerController.AccountData.UserID, quizAnswerController.Request.QuestionNo, quizAnswerController.Request.Answer)})}
10 unmodified lines11121314151617181920212223242510 unmodified linesfunc Question(c *gin.Context) {questionQuiz := services.QuestionQuizService{}questionQuizController := controller.Controller[models.QuestionQuizRequest, models.Quiz, models.QuestionResponse]{Service: &questionQuiz.Service,}questionQuizController.RequestJSON(c, func() {quizId, _ := strconv.Atoi(c.Param("quiz_id"))academyId, _ := strconv.Atoi(c.Param("academy_id"))questionQuizController.Service.Constructor.ID = uint(quizId)questionQuizController.Service.Constructor.AcademyID = uint(academyId)questionQuiz.Retrieve(questionQuizController.AccountData.UserID, questionQuizController.Request.QuestionNo)})}10 unmodified lines111213141516171819202122232425262710 unmodified linesfunc Question(c *gin.Context) {questionQuiz := services.QuestionQuizService{}questionQuizController := controller.Controller[any, models.Quiz, models.QuestionResponse]{Service: &questionQuiz.Service,}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, questionNo)questionQuizController.Response(c)})}
16 unmodified lines171819202122232416 unmodified linesquizAnswerController.RequestJSON(c, func() {quizId, _ := strconv.Atoi(c.Param("quiz_id"))academyId, _ := strconv.Atoi(c.Param("academy_id"))quizAnswerController.Service.Constructor.ID = uint(quizId)quizAnswerController.Service.Constructor.AcademyID = uint(academyId)quizAnswer.Update(quizAnswerController.AccountData.UserID, quizAnswerController.Request.QuestionNo, quizAnswerController.Request.Answer)})}16 unmodified lines17181920212223242516 unmodified linesquizAnswerController.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)})}
13 unmodified lines141516171819202122232413 unmodified linesattemptQuizController := controller.Controller[any, models.Quiz, models.QuizAttempt]{Service: &attemptQuiz.Service,}attemptQuizController.RequestJSON(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)})}13 unmodified lines14151617181920212223242513 unmodified linesattemptQuizController := controller.Controller[any, models.Quiz, models.QuizAttempt]{Service: &attemptQuiz.Service,}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 lines177178179180181182176 unmodified linesSelectedAnswer uint `json:"selected_answer"`IsCorrect bool `json:"is_correct"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }176 unmodified lines177178179180181182183184185186187188176 unmodified linesSelectedAnswer 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 settingsfunc (Account) TableName() string { return "account" }
53 unmodified lines54555653 unmodified linesAnswer []Answer `json:"answer_options"`UserAnswer int `json:"current_user_answer"`}53 unmodified lines545556575859606153 unmodified linesAnswer []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