forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
277 lines (250 loc) · 7.06 KB
/
register.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package uadmin
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"strings"
"github.com/jinzhu/gorm"
"github.com/uadmin/uadmin/colors"
"github.com/uadmin/uadmin/helper"
)
// HideInDashboarder used to check if a model should be hidden in
// dashboard
type HideInDashboarder interface {
HideInDashboard() bool
}
// CustomTranslation !
var CustomTranslation = []string{
"uadmin/system",
}
// Register is used to register models to uadmin
func Register(m ...interface{}) {
modelList := []interface{}{}
if models == nil {
models = map[string]interface{}{}
// Initialize system models
modelList = []interface{}{
DashboardMenu{},
User{},
UserGroup{},
Session{},
UserPermission{},
GroupPermission{},
Language{},
Log{},
}
}
// System models count
SMCount := len(modelList)
// Now add user defined models
modelList = append(modelList,
m...,
)
// Inialize the Database
initializeDB(modelList...)
// Setup languages
initializeLanguage()
// Store models in Model global variable
// and initialize the dashboard
dashboardMenus := []DashboardMenu{}
All(&dashboardMenus)
modelExists := false
cat := ""
Schema = map[string]ModelSchema{}
for i := range modelList {
t := reflect.TypeOf(modelList[i])
name := strings.ToLower(t.Name())
models[name] = modelList[i]
// Register Dashboard menu
// First check if the model is already in dashboard
for _, val := range dashboardMenus {
if name == val.URL {
modelExists = true
break
}
}
// If not in dashboard, then add it
if !modelExists {
hideItem := false
if _, ok := t.MethodByName("HideInDashboard"); ok {
hider := modelList[i].(HideInDashboarder)
hideItem = hider.HideInDashboard()
}
// Check if the model is a system model
if i < SMCount {
cat = "System"
} else {
cat = ""
}
// TODO: Make the name a plural properly
dashboard := DashboardMenu{
MenuName: strings.Join(helper.SplitCamelCase(t.Name()), " ") + "s",
URL: name,
Hidden: hideItem,
Cat: cat,
}
Save(&dashboard)
}
modelExists = false
}
// Check if encrypt key is there or generate it
if _, err := os.Stat(".key"); os.IsNotExist(err) {
EncryptKey = generateByteArray(32)
ioutil.WriteFile(".key", EncryptKey, 0600)
} else {
EncryptKey, _ = ioutil.ReadFile(".key")
}
// Check if salt is there or generate it
users := []User{}
if _, err := os.Stat(".salt"); os.IsNotExist(err) {
Salt = GenerateBase64(72)
ioutil.WriteFile(".salt", []byte(Salt), 0600)
if Count(&users, "") != 0 {
recoveryPass := GenerateBase64(24)
recoverUsername := GenerateBase64(8)
for Count(&users, "username = ?", recoverUsername) != 0 {
recoverUsername = GenerateBase64(8)
}
admin := User{
FirstName: "System",
LastName: "Recovery Admin",
Username: recoverUsername,
Password: hashPass(recoveryPass),
Admin: true,
RemoteAccess: false,
Active: true,
}
admin.Save()
Trail(WARNING, "Your salt file was missing, and a new one was generated NO USERS CAN LOGIN UNTIL PASSWORDS ARE RESET.")
Trail(INFO, "uAdmin generated a recovery user for you. Username:%s Password:%s", admin.Username, recoveryPass)
}
} else {
saltBytes, _ := ioutil.ReadFile(".salt")
Salt = string(saltBytes)
}
// Create an admin user if there is no user in the system
if Count(&users, "") == 0 {
admin := User{
FirstName: "System",
LastName: "Admin",
Username: "admin",
Password: hashPass("admin"),
Admin: true,
RemoteAccess: true,
Active: true,
}
admin.Save()
Trail(INFO, "Auto generated admin user. Username:admin, Password:admin.")
}
// Register admin inlines
RegisterInlines(UserGroup{}, map[string]string{
"GroupPermission": "UserGroupID",
})
RegisterInlines(User{}, map[string]string{
"UserPermission": "UserID",
})
// Get Global Schema
stat := map[string]int{}
for _, v := range CustomTranslation {
tempStat := syncCustomTranslation(v)
for k, v := range tempStat {
stat[k] += v
}
}
for k, v := range models {
//t := reflect.TypeOf(v)
//Schema[t.Name()], _ = getSchema(v)
Schema[k], _ = getSchema(v)
tempStat := syncModelTranslation(Schema[k])
for k, v := range tempStat {
stat[k] += v
}
}
for k, v := range stat {
complete := float64(v) / float64(stat["en"])
if complete != 1 {
Trail(WARNING, "Translation of %s at %.0f%% [%d/%d]", k, complete*100, v, stat["en"])
}
}
// Mark registered as true to prevent auto registeration
registered = true
}
// RegisterInlines is a function to register a model as an inline for another model
// Parameters:
// ===========
// model (struct instance): Is the model that you want to add inlines to.
// fk (map[interface{}]string): This is a map of the inlines to be added to the model.
// The map's key is the name of the model of the inline
// and the value of the map is the foreign key field's name.
// Example:
// ========
// type Person struct {
// uadmin.Model
// Name string
// }
//
// type Card struct {
// uadmin.Model
// PersonID uint
// Person Person
// }
//
// func main() {
// ...
// uadmin.RegisterInlines(Person{}, map[string]string{
// "Card": "PersonID",
// })
// ...
// }
func RegisterInlines(model interface{}, fk map[string]string) {
// TODO: sanity check for the parameters
// Get the name of the model
modelName := strings.ToLower(reflect.TypeOf(model).Name())
if inlines == nil {
inlines = map[string][]interface{}{}
}
if foreignKeys == nil {
foreignKeys = map[string]map[string]string{}
}
inlineList := []interface{}{}
fkMap := map[string]string{}
for k, v := range fk {
kmodel, _ := NewModel(strings.ToLower(k), false)
t := reflect.TypeOf(kmodel.Interface())
fkMap[strings.ToLower(t.Name())] = gorm.ToColumnName(v)
// Check if the field name is in the struct
if t.Kind() != reflect.Struct {
fmt.Printf("%sUnable to register inline for (%s) inline %s.%s. Please pass a struct as key.\n", colors.Error, reflect.TypeOf(model).Name(), t.Name(), v)
continue
}
if _, ok := t.FieldByName(v); !ok {
fmt.Printf("%sUnable to register inline for (%s) inline %s.%s. Field name is not in struct.\n", colors.Error, reflect.TypeOf(model).Name(), t.Name(), v)
continue
}
inlineList = append(inlineList, kmodel.Interface())
}
inlines[modelName] = inlineList
inlines[reflect.TypeOf(model).Name()] = inlineList
foreignKeys[modelName] = fkMap
delete(Schema, modelName)
Schema[modelName], _ = getSchema(model)
}
func registerHandlers() {
// register static and add parameter
if !strings.HasSuffix(RootURL, "/") {
RootURL = RootURL + "/"
}
if !strings.HasPrefix(RootURL, "/") {
RootURL = "/" + RootURL
}
// Handleer for uAdmin, static and media
http.HandleFunc(RootURL, mainHandler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
http.HandleFunc("/media/", mediaHandler)
// api handler
http.HandleFunc(RootURL+"api/", apiHandler)
http.HandleFunc(RootURL+"revertHandler/", revertLogHandler)
handlersRegistered = true
}