-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
102 lines (88 loc) · 1.97 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package bunker
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"time"
"github.com/glebarez/sqlite"
"github.com/yankeguo/bunker/model"
"github.com/yankeguo/bunker/model/dao"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
"gorm.io/gorm"
)
func InitializeUsers(
log *zap.SugaredLogger,
dir DataDir,
_db *gorm.DB,
) (err error) {
buf, _ := os.ReadFile(filepath.Join(dir.String(), "users.yaml"))
buf = bytes.TrimSpace(buf)
if len(buf) == 0 {
return
}
type InitialUser struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
IsAdmin bool `yaml:"is_admin"`
UpdateExisting bool `yaml:"update_existing"`
}
db := dao.Use(_db)
dec := yaml.NewDecoder(bytes.NewReader(buf))
for {
var iu InitialUser
if err = dec.Decode(&iu); err != nil {
break
}
var user *model.User
if user, err = db.User.Where(db.User.ID.Eq(iu.Username)).First(); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.With("username", iu.Username).Info("user created")
user = &model.User{
ID: iu.Username,
CreatedAt: time.Now(),
VisitedAt: time.Now(),
IsAdmin: iu.IsAdmin,
}
user.SetPassword(iu.Password)
if err = db.User.Create(user); err != nil {
return
}
} else {
return
}
} else if iu.UpdateExisting {
log.With("username", iu.Username).Info("user updated")
user.SetPassword(iu.Password)
if _, err = db.User.Where(
db.User.ID.Eq(iu.Username),
).UpdateSimple(
db.User.PasswordDigest.Value(user.PasswordDigest),
db.User.IsAdmin.Value(iu.IsAdmin),
); err != nil {
return
}
}
}
if errors.Is(err, io.EOF) {
err = nil
}
return
}
func CreateDatabase(dir DataDir) (db *gorm.DB, err error) {
if db, err = gorm.Open(
sqlite.Open(filepath.Join(dir.String(), "database.sqlite3")),
&gorm.Config{},
); err != nil {
return
}
if err = db.AutoMigrate(model.All...); err != nil {
return
}
if Debug("db") {
db = db.Debug()
}
return
}