From fe932de37e377c31446f05720fa3d6396d83ec4f Mon Sep 17 00:00:00 2001 From: Evan Reichard Date: Tue, 12 Jan 2021 17:06:27 -0500 Subject: [PATCH] Reorganize & Add DB Bootstrapping --- cmd/cmd.go | 11 ++--------- imagini.db | Bin 69632 -> 69632 bytes internal/auth/local.go | 22 +--------------------- internal/context/context.go | 4 ++-- internal/models/db.go | 2 +- internal/query/{db.go => query.go} | 28 ++++++++++++++++++++++++---- internal/query/users.go | 22 +++++++++++++++++++--- 7 files changed, 49 insertions(+), 40 deletions(-) rename internal/query/{db.go => query.go} (86%) diff --git a/cmd/cmd.go b/cmd/cmd.go index ced6e2b..7d11b7d 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,11 +1,12 @@ package cmd import ( + "net/http" + "reichard.io/imagini/routes" "reichard.io/imagini/internal/context" "github.com/urfave/cli/v2" - "net/http" log "github.com/sirupsen/logrus" ) @@ -16,19 +17,11 @@ var CmdServe = cli.Command{ Action: serveWeb, } -// var CmdDBTest = cli.Command{ -// Name: "test", -// Aliases: []string{"t"}, -// Usage: "test db.", -// Action: testDatabase, -// } - func serveWeb(cliCtx *cli.Context) error { log.Info("Serving Web") ctx := context.NewImaginiContext() routes.RegisterRoutes(ctx) - //listener, _ := net.Listen("tcp", ctx.Config.ListenPort) if err := http.ListenAndServe(":" + ctx.Config.ListenPort, nil); err != nil { log.Fatal(err) diff --git a/imagini.db b/imagini.db index 5e3b750da73635f3f93388fe134edab6f7d34b7e..7def2e9d05b99a62a5c3dd2d8355f70076dda3e5 100644 GIT binary patch delta 266 zcmZozz|ydQWkQzH7Y2S6zUjPbd?|dEJcqc;xPEa(a(?7U;oQM~l0B343%ki?L4gd` z&2L$a**OK6*~P`h8Jp`TYw|wdEY9~{ktLUbKNqMXnZLeKfRTs6+na$`oR?R;k=4k+ z$WYh7P}k5%!O+~wz{JYXNYBFD*uqTLz|_jXfPi#jN^WMJPkwS@j*3yDilKpuS)f-| zd1g{Zutk29UPMGtqHC11OKD+BK#5zjiA$7!xQL~(g?nje0>?TrA1}M8(EDEj0|-R40R0+6$~w`OwFx~P4x^c4UEk!bq!3d3=9a# zmlmfM8JRhxmL=xt6_h500=b4p#vm#vH8VLQu_(nSKRGc+#VAq5&_Kl^(>5nEJUKnX zB`>QiCB-|@yTH#k(?6`zI5;RGJit4|JHyY*$1v2--POq0$=%e|KPW$4kBfnUfsr2= nDsO>ac+4*=#H`JUW-mm^R|fvCKqasFxw)97IiYS@l&}E+u*PA4 diff --git a/internal/auth/local.go b/internal/auth/local.go index 080584e..5fc1b0d 100644 --- a/internal/auth/local.go +++ b/internal/auth/local.go @@ -1,17 +1,14 @@ package auth import ( - "errors" - "gorm.io/gorm" "golang.org/x/crypto/bcrypt" log "github.com/sirupsen/logrus" - "reichard.io/imagini/internal/query" "reichard.io/imagini/internal/models" ) func authenticateLocalUser(user models.User, pw string) bool { bPassword :=[]byte(pw) - err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), bPassword) + err := bcrypt.CompareHashAndPassword([]byte(user.Password), bPassword) if err == nil { log.Info("[auth] Authentication successfull: ", user.Username) return true @@ -19,20 +16,3 @@ func authenticateLocalUser(user models.User, pw string) bool { log.Warn("[auth] Authentication failed: ", user.Username) return false } - -func CreateUser(db *gorm.DB, user models.User, pw string) error { - log.Info("[auth] Creating user: ", user.Username) - _, err := query.User(db, user) - if !errors.Is(err, gorm.ErrRecordNotFound) { - log.Warn("[auth] User already exists: ", user.Username) - return errors.New("User already exists") - } - - hashedPassword, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost) - if err != nil { - log.Error(err) - return err - } - user.HashedPassword = string(hashedPassword) - return query.CreateUser(db, user) -} diff --git a/internal/context/context.go b/internal/context/context.go index 8243c5d..b3ae793 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -13,9 +13,9 @@ type ImaginiContext struct { func NewImaginiContext() *ImaginiContext { c := config.NewConfig() - gormDB := query.NewDB(c) + db := query.NewDB(c) return &ImaginiContext{ - DB: gormDB, + DB: db, Config: c, } } diff --git a/internal/models/db.go b/internal/models/db.go index fa6f1c1..489467b 100644 --- a/internal/models/db.go +++ b/internal/models/db.go @@ -19,7 +19,7 @@ type User struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` AuthType string `json:"auth_type"` - HashedPassword string `json:"hashed_password"` + Password string `json:"password"` } type MediaItem struct { diff --git a/internal/query/db.go b/internal/query/query.go similarity index 86% rename from internal/query/db.go rename to internal/query/query.go index fad854e..f33afd0 100644 --- a/internal/query/db.go +++ b/internal/query/query.go @@ -1,13 +1,12 @@ package query import ( - "log" "path" - // "time" "gorm.io/gorm" "gorm.io/gorm/logger" "gorm.io/driver/sqlite" + log "github.com/sirupsen/logrus" "reichard.io/imagini/internal/config" "reichard.io/imagini/internal/models" @@ -24,18 +23,39 @@ func NewDB(c *config.Config) *gorm.DB { dbLocation := path.Join(c.ConfigPath, "imagini.db") db, _ = gorm.Open(sqlite.Open(dbLocation), gormConfig) } else { - log.Fatal("ERROR: Unsupported Database") + log.Fatal("Unsupported Database") } - // Initialize Database + // Initialize database db.AutoMigrate(&models.ServerSetting{}) db.AutoMigrate(&models.User{}) db.AutoMigrate(&models.MediaItem{}) db.AutoMigrate(&models.Tag{}) db.AutoMigrate(&models.Album{}) + + // Determine whether to bootstrap + var count int64 + db.Model(&models.User{}).Count(&count) + if count == 0 { + bootstrapDatabase(db) + } + return db } +func bootstrapDatabase(db *gorm.DB) { + log.Info("[query] Bootstrapping database.") + err := CreateUser(db, models.User{ + Username: "admin", + Password: "admin", + AuthType: "Local", + }) + + if err != nil { + log.Fatal("[query] Unable to bootstrap database.") + } +} + func ItemsFromAlbum(db *gorm.DB, user models.User, album models.Album) []models.MediaItem { var mediaItems []models.MediaItem // db.Table("media_albums"). diff --git a/internal/query/users.go b/internal/query/users.go index 5fd586c..22b1d43 100644 --- a/internal/query/users.go +++ b/internal/query/users.go @@ -1,13 +1,29 @@ package query import ( + "errors" "gorm.io/gorm" + "golang.org/x/crypto/bcrypt" + log "github.com/sirupsen/logrus" + "reichard.io/imagini/internal/models" ) -func CreateUser (db *gorm.DB, user models.User) error { - err := db.Create(&user).Error - return err +func CreateUser(db *gorm.DB, user models.User) error { + log.Info("[query] Creating user: ", user.Username) + _, err := User(db, user) + if !errors.Is(err, gorm.ErrRecordNotFound) { + log.Warn("[query] User already exists: ", user.Username) + return errors.New("User already exists") + } + + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) + if err != nil { + log.Error(err) + return err + } + user.Password = string(hashedPassword) + return db.Create(&user).Error } func User (db *gorm.DB, user models.User) (models.User, error) {