-
Notifications
You must be signed in to change notification settings - Fork 59
/
register.go
318 lines (283 loc) · 8.16 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package uadmin
import (
"io/ioutil"
"net/http"
"os"
"reflect"
"strings"
"github.com/jinzhu/inflection"
"github.com/uadmin/uadmin/helper"
)
// HideInDashboarder used to check if a model should be hidden in
// dashboard
type HideInDashboarder interface {
HideInDashboard() bool
}
// CustomTranslation is where you can register custom translation files.
// To register a custom translation file, always assign it with it's key
// in the this format "category/name". For example:
//
// uadmin.CustomTranslation = append(uadmin.CustomTranslation, "ui/billing")
//
// This will register the file and you will be able to use it if `uadmin.Tf`.
// By default there is only one registed custom translation wich is "uadmin/system".
var CustomTranslation = []string{
"uadmin/system",
}
var modelList []interface{}
// 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{},
Setting{},
SettingCategory{},
Approval{},
ABTest{},
ABTestValue{},
//Builder{},
//BuilderField{},
}
}
// 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)
var modelExists bool
cat := ""
Schema = map[string]ModelSchema{}
for i := range modelList {
modelExists = false
t := reflect.TypeOf(modelList[i])
name := strings.ToLower(t.Name())
models[name] = modelList[i]
// Get Hidden model status
hideItem := false
if hider, ok := modelList[i].(HideInDashboarder); ok {
hideItem = hider.HideInDashboard()
}
// Register Dashboard menu
// First check if the model is already in dashboard
dashboardIndex := 0
for index, val := range dashboardMenus {
if name == val.URL {
modelExists = true
dashboardIndex = index
break
}
}
// If not in dashboard, then add it
if !modelExists {
// Check if the model is a system model
if i < SMCount {
cat = "System"
} else {
cat = ""
}
dashboard := DashboardMenu{
MenuName: inflection.Plural(strings.Join(helper.SplitCamelCase(t.Name()), " ")),
URL: name,
Hidden: hideItem,
Cat: cat,
}
Save(&dashboard)
} else {
// If model exists, synchnorize it if changed
if hideItem != dashboardMenus[dashboardIndex].Hidden {
dashboardMenus[dashboardIndex].Hidden = hideItem
Save(&dashboardMenus[dashboardIndex])
}
}
}
// 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
adminUsername := "admin"
adminPassword := "admin"
if os.Getenv("UADMIN_USER") != "" {
adminUsername = os.Getenv("UADMIN_USER")
}
if os.Getenv("UADMIN_PASS") != "" {
adminPassword = os.Getenv("UADMIN_PASS")
}
if Count(&users, "") == 0 {
admin := User{
FirstName: "System",
LastName: "Admin",
Username: adminUsername,
Password: hashPass(adminPassword),
Admin: true,
RemoteAccess: true,
Active: true,
}
admin.Save()
Trail(INFO, "Auto generated admin user. Username:%s, Password:%s.", adminUsername, adminPassword)
}
// Register admin inlines
RegisterInlines(UserGroup{}, map[string]string{
"GroupPermission": "UserGroupID",
})
RegisterInlines(User{}, map[string]string{
"UserPermission": "UserID",
})
RegisterInlines(ABTest{}, map[string]string{
"ABTestValue": "ABTestID",
})
for k, v := range models {
Schema[k], _ = getSchema(v)
}
// Register JS
s := Schema["abtest"]
s.IncludeFormJS = []string{"/static/uadmin/js/abtest_form.js"}
Schema["abtest"] = s
// Register Limit Choices To
s = Schema["abtest"]
s.FieldByName("ModelName").LimitChoicesTo = loadModels
s.FieldByName("Field").LimitChoicesTo = loadFields
Schema["abtest"] = s
// Load Session data
if CacheSessions {
loadSessions()
}
// Load Permission data
if CachePermissions {
loadPermissions()
}
// Check if there are active ABTests
abTestCount = Count([]ABTest{}, "active = ?", true)
// 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())] = GetDB().Config.NamingStrategy.ColumnName("", v)
// Check if the field name is in the struct
if t.Kind() != reflect.Struct {
Trail(ERROR, "Unable to register inline for (%s) inline %s.%s. Please pass a struct as key.", reflect.TypeOf(model).Name(), t.Name(), v)
continue
}
if _, ok := t.FieldByName(v); !ok {
Trail(ERROR, "Unable to register inline for (%s) inline %s.%s. Field name is not in struct.", 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
}
if !DisableAdminUI {
// Handler for uAdmin, static and media
http.HandleFunc(RootURL, Handler(mainHandler))
http.HandleFunc("/static/", Handler(StaticHandler))
http.HandleFunc("/media/", Handler(mediaHandler))
// api handler
http.HandleFunc(RootURL+"revertHandler/", Handler(revertLogHandler))
}
// dAPI handler
http.HandleFunc(RootURL+"api/", Handler(apiHandler))
handlersRegistered = true
}