-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.go
325 lines (253 loc) · 7.54 KB
/
users.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
319
320
321
322
323
324
325
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
// User def
type User struct {
Username string `json:"username"`
Password string `json:"password"`
GroupName string `json:"group_name"`
ExpireTime int64 `json:"expire_time"`
CreateTime int64 `json:"create_time"`
CreateBy string `json:"create_by"`
}
// UserDB def
type UserDB struct {
Username string
Password string
GroupID int64
ExpireTime int64
CreateTime int64
CreateBy string
}
// PrepareNewUser - returns new User
func (s *server) PrepareNewUser(createBy string, groupName string) (UserDB, error) {
// Check group exists
GroupDB, err := s.GetGroup(groupName)
userDB := UserDB{}
if err != nil {
return userDB, fmt.Errorf("Group %s not found: %s", groupName, err)
}
cipherKey := []byte(s.env.ekey)
password := fmt.Sprintf(randSeq(12))
encryptedPassword, err := encryptHash(cipherKey, password)
if err != nil {
return userDB, fmt.Errorf("Error while encryptHash password: %s", err)
}
// DEBUG
// log.Printf("Pepare user, password: %s", password)
userDB.Username = fmt.Sprintf("%s-%s-%s", createBy, GroupDB.GroupName, randSeq(8))
userDB.Password = encryptedPassword
userDB.ExpireTime = time.Now().Unix() + int64(GroupDB.LeaseTime*60) // lease time x minutes
userDB.GroupID = GroupDB.id
userDB.CreateTime = time.Now().Unix()
userDB.CreateBy = createBy
return userDB, nil
}
// ForceExpireUsersInGroup - Expire current users in group
func (s *server) ExpireUsersInGroup(groupID int64, createBy string) error {
update, err := s.db.Prepare("UPDATE users SET expire_time = 1 WHERE group_id=$1 AND create_by=$2;")
if err != nil {
return errors.New("Could not prepare statement")
}
_, err = update.Exec(groupID, createBy)
if err != nil {
return errors.New("Could not update db")
}
return nil
}
var letters = []rune("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func (s *server) CreateUser(w http.ResponseWriter, r *http.Request) {
// Get session user
var LDAPUser, err = s.getLDAPUser(r)
if err != nil {
render.Status(r, 401)
render.JSON(w, r, nil)
return
}
var u User
// Get URL group name
u.GroupName = chi.URLParam(r, "GroupName")
UserDB, err := s.PrepareNewUser(LDAPUser.Username, u.GroupName)
if err != nil {
log.Printf("User error: %+v", err)
render.Status(r, 404)
render.JSON(w, r, nil)
return
}
// before insert then expire current users in this group
err = s.ExpireUsersInGroup(UserDB.GroupID, LDAPUser.Username)
if err != nil {
log.Printf("ERROR: Cannot delete current users")
render.Status(r, 500)
render.JSON(w, r, u)
}
// insert
insert, err := s.db.Prepare("INSERT INTO users (username, password, group_id, expire_time, create_time, create_by) values(?,?,?,?,?,?)")
if err != nil {
// handle this error better than this
log.Printf("ERROR: preparing insert statement %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
decryptedPassword, _ := decryptHash([]byte(s.env.ekey), UserDB.Password)
if err != nil {
// handle this error better than this
log.Printf("ERROR: DecryptedPassword %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
u.Username = UserDB.Username
u.Password = UserDB.Password
u.ExpireTime = UserDB.ExpireTime
u.CreateTime = UserDB.CreateTime
u.CreateBy = UserDB.CreateBy
_, err = insert.Exec(u.Username, u.Password, UserDB.GroupID, u.ExpireTime, u.CreateTime, u.CreateBy)
if err != nil {
// handle this error better than this
log.Printf("ERROR: Inserting into DB %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
// Send decrypted pass
u.Password = decryptedPassword
render.Status(r, 201)
render.JSON(w, r, u)
}
func (s *server) GetAllUsers(w http.ResponseWriter, r *http.Request) {
var users []User
// get ssession user
var LDAPUser, err = s.getLDAPUser(r)
rows, err := s.db.Query("SELECT users.username, users.password, groups.group_name, users.expire_time, users.create_time, users.create_by FROM users LEFT JOIN GROUPS ON users.group_id = groups.id WHERE groups.deleted=0 and users.create_by=$1 AND users.expire_time > $2;", LDAPUser.Username, time.Now().Unix())
if err != nil {
// handle this error better than this
log.Printf("ERROR: connecting to DB: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
for rows.Next() {
var username string
var password string
var groupName string
var expireTime int64
var createTime int64
var createBy string
err = rows.Scan(&username, &password, &groupName, &expireTime, &createTime, &createBy)
if err != nil {
// handle this error better than this
log.Printf("ERROR: looping through DB rows: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
// TODO delete logging
cipherKey := []byte(s.env.ekey)
decryptedPassword, _ := decryptHash(cipherKey, password)
if err != nil {
log.Printf("ERROR: Decryption %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
users = append(users, User{
Username: username,
Password: decryptedPassword,
GroupName: groupName,
ExpireTime: expireTime,
CreateTime: createTime,
CreateBy: createBy,
})
}
// get any error encountered during iteration
err = rows.Err()
if err != nil {
// handle this error better than this
log.Printf("ERROR: handling DB rows: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
render.JSON(w, r, users)
return
}
func (s *server) GetAllGroupUsers(w http.ResponseWriter, r *http.Request) {
var users = []User{}
g, err := s.GetGroup(chi.URLParam(r, "GroupName"))
if err != nil {
render.Status(r, 404)
render.JSON(w, r, nil)
return
}
// Get all users in a specific group
log.Printf("Get users for group=%d, and expire_time > %d", g.id, time.Now().Unix())
rows, err := s.db.Query("SELECT users.username, users.password, groups.group_name, users.expire_time, users.create_time, users.create_by FROM users LEFT JOIN GROUPS ON users.group_id = groups.id WHERE groups.deleted=0 AND groups.id=$1 AND users.expire_time > $2;", g.id, time.Now().Unix())
if err != nil {
// handle this error better than this
log.Printf("ERROR: connecting to DB: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
for rows.Next() {
var username string
var password string
var groupName string
var expireTime int64
var createTime int64
var createBy string
err = rows.Scan(&username, &password, &groupName, &expireTime, &createTime, &createBy)
if err != nil {
// handle this error better than this
log.Printf("ERROR: looping through DB rows: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
decryptedPassword, _ := decryptHash([]byte(s.env.ekey), password)
if err != nil {
// handle this error better than this
log.Printf("ERROR: decryption failed: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
users = append(users, User{
Username: username,
Password: decryptedPassword,
GroupName: groupName,
ExpireTime: expireTime,
CreateTime: createTime,
CreateBy: createBy,
})
}
// get any error encountered during iteration
err = rows.Err()
if err != nil {
// handle this error better than this
log.Printf("ERROR: handling DB rows: %+v", err)
render.Status(r, 500)
render.JSON(w, r, nil)
return
}
render.Status(r, 200)
render.JSON(w, r, users)
return
}