2025-03-13 08:25:39 +01:00
|
|
|
package store
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2025-03-15 01:49:52 +01:00
|
|
|
"crypto/sha1"
|
2025-03-13 08:25:39 +01:00
|
|
|
"fmt"
|
|
|
|
"gorm.io/driver/sqlite"
|
|
|
|
"gorm.io/gorm"
|
2025-03-15 01:49:52 +01:00
|
|
|
"os"
|
2025-03-13 08:25:39 +01:00
|
|
|
"sonarqube-badge/config"
|
2025-03-15 01:49:52 +01:00
|
|
|
"sonarqube-badge/security/aes"
|
|
|
|
"time"
|
2025-03-13 08:25:39 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func CreateDatabase(ctx context.Context) context.Context {
|
|
|
|
cfg := ctx.Value("config").(config.Config)
|
|
|
|
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("%s/sqbadge.db", cfg.DataPath)), &gorm.Config{})
|
|
|
|
if err != nil {
|
|
|
|
panic("failed to open database")
|
|
|
|
}
|
|
|
|
|
2025-03-15 01:49:52 +01:00
|
|
|
err = db.AutoMigrate(&Project{})
|
|
|
|
if err != nil {
|
|
|
|
panic("failed to migrate database Project")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = db.AutoMigrate(&User{})
|
2025-03-13 08:25:39 +01:00
|
|
|
if err != nil {
|
2025-03-15 01:49:52 +01:00
|
|
|
panic("failed to migrate database User")
|
2025-03-13 08:25:39 +01:00
|
|
|
}
|
|
|
|
|
2025-03-15 01:49:52 +01:00
|
|
|
provideDefaultUser(cfg, db)
|
|
|
|
|
2025-03-13 08:25:39 +01:00
|
|
|
return context.WithValue(ctx, "db", db)
|
|
|
|
}
|
2025-03-15 01:49:52 +01:00
|
|
|
|
|
|
|
func provideDefaultUser(cfg config.Config, db *gorm.DB) {
|
|
|
|
password := aes.EncryptAES(cfg.Secret, time.Now().String())
|
|
|
|
sha1Hash := sha1.Sum([]byte(password))
|
|
|
|
user := User{
|
|
|
|
Username: "admin",
|
|
|
|
// Random Password
|
|
|
|
Password: fmt.Sprintf("%x", sha1Hash),
|
|
|
|
Email: "admin@example.com",
|
|
|
|
}
|
|
|
|
|
|
|
|
if db.First(&user).Error != nil {
|
|
|
|
_, _ = fmt.Fprintf(os.Stderr, "Default User: \n\t- %s\n\t- %s\n", user.Email, password)
|
|
|
|
db.Create(&user)
|
|
|
|
}
|
|
|
|
}
|