summaryrefslogtreecommitdiff
path: root/store/user.go
blob: 7f9eabdb8df7c0275d5ace2d22888c319ef3d5a9 (plain)
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
package store

import (
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"os"
)

// User represents metadata of a user.
type User struct {
	Secret     string `json:"secret"`
	Privileged bool   `json:"privileged"`
	Snowflake  string `json:"snowflake"`
	Username   string `json:"username"`
}

// user parses user metadata file.
func (s *Store) user(path string) User {
	if payload, err := os.ReadFile(path); err != nil {
		s.fatalClose(fmt.Sprintf("Error reading user metadata %s, %s", path, err))
	} else {
		var info User
		if err = json.Unmarshal(payload, &info); err != nil {
			s.fatalClose(fmt.Sprintf("Error parsing user metadata %s, %s", path, err))
		} else {
			return info
		}
	}
	return User{}
}

// User returns user information with specific snowflake.
func (s *Store) User(flake string) User {
	if !s.flake(flake) || !s.file(s.UserPath(flake)) {
		return User{}
	}

	s.getLock(flake).RLock()
	defer s.getLock(flake).RUnlock()
	return s.user(s.UserMetadataPath(flake))
}

// Users returns a slice of user snowflakes.
func (s *Store) Users() []string {
	var users []string
	if entries, err := os.ReadDir(s.UsersDir()); err != nil {
		s.fatalClose(fmt.Sprintf("Error reading users, %s", err))
	} else {
		for _, entry := range entries {
			if entry.IsDir() {
				users = append(users, entry.Name())
			}
		}
	}
	return users
}

// UserMetadata sets user metadata.
func (s *Store) UserMetadata(info User) {
	if payload, err := json.Marshal(info); err != nil {
		s.fatalClose(fmt.Sprintf("Error updating user %s metadata, %s", info.Snowflake, err))
	} else {
		if err = os.WriteFile(s.UserMetadataPath(info.Snowflake), payload, s.PermissionFile); err != nil {
			s.fatalClose(fmt.Sprintf("Error writing user %s metadata, %s", info.Snowflake, err))
		}
	}
}

// UserAdd creates a user.
func (s *Store) UserAdd(username string, privileged bool, password string) User {
	if len(username) > 64 || !nameRegex.MatchString(username) || s.file(s.UsernamePath(username)) {
		return User{}
	}

	info := User{
		Secret:     s.SecretNew(),
		Privileged: privileged,
		Snowflake:  userNode.Generate().String(),
		Username:   username,
	}
	// Create user directory and images
	if err := os.MkdirAll(s.UserImagesPath(info.Snowflake), s.PermissionDir); err != nil {
		s.fatalClose(fmt.Sprintf("Error creating user %s directory, %s", info.Snowflake, err))
	}
	s.getLock(info.Snowflake).Lock()
	defer s.getLock(info.Snowflake).Unlock()
	// Save user metadata
	s.UserMetadata(info)
	// Associate new user secret
	s.SecretAssociate(info.Secret, info.Snowflake)
	// Associate username
	s.userUsernameAssociate(info.Snowflake, info.Username)
	// Set password
	s.userPasswordUpdate(s.UserPath(info.Snowflake), password)

	log.Infof("User %s added with username %s privilege %v secret %s.", info.Snowflake, info.Username, info.Privileged, info.Secret)
	return info
}

// UserPrivileged sets privileged status of user with specific snowflake.
func (s *Store) UserPrivileged(flake string, privileged bool) {
	if !s.flake(flake) {
		return
	}

	s.getLock(flake).Lock()
	defer s.getLock(flake).Unlock()

	info := s.user(s.UserMetadataPath(flake))
	if info.Snowflake != flake {
		return
	}
	info.Privileged = privileged
	s.UserMetadata(info)
	log.Infof("User %s privileged %v", flake, privileged)
}

// UserUsernameUpdate updates username of user with specific snowflake.
func (s *Store) UserUsernameUpdate(flake, username string) bool {
	if !s.flake(flake) || !nameRegex.MatchString(username) || s.file(s.UsernamePath(username)) {
		return false
	}

	s.getLock(flake).Lock()
	defer s.getLock(flake).Unlock()

	info := s.user(s.UserMetadataPath(flake))
	if info.Snowflake != flake {
		return false
	}
	// Lock old username
	s.getLock(info.Username).Lock()
	defer s.getLock(info.Username).Unlock()
	// Disassociate old username and associate new
	if info.Username != "" {
		s.userUsernameDisassociate(info.Username)
	}
	s.userUsernameAssociate(flake, username)
	// Set username in metadata
	info.Username = username
	s.UserMetadata(info)

	log.Infof("User %s username updated to %s.", flake, username)
	return true
}

// UserSecretRegen regenerates secret of user with specific snowflake.
func (s *Store) UserSecretRegen(flake string) string {
	if !s.flake(flake) {
		return ""
	}

	s.getLock(flake).Lock()
	defer s.getLock(flake).Unlock()

	info := s.user(s.UserMetadataPath(flake))
	// Check if obtained info is valid
	if info.Snowflake != flake {
		return ""
	}
	// Disassociate old user
	s.SecretDisassociate(info.Secret)
	// Generate new secret
	info.Secret = s.SecretNew()
	// Write metadata
	s.UserMetadata(info)
	// Associate new secret
	s.SecretAssociate(info.Secret, info.Snowflake)
	// Log the event
	log.Infof("User %s secret reset to %s.", flake, info.Secret)
	return info.Secret
}

// UserUsername returns user via username.
func (s *Store) UserUsername(username string) User {
	if !nameRegex.MatchString(username) || !s.file(s.UsernamePath(username)) {
		return User{}
	}
	s.getLock(username).RLock()
	user := s.user(s.readlink(s.UsernamePath(username)) + "/" + infoJson)
	s.getLock(username).RUnlock()
	return user
}

// userUsernameAssociate associates user snowflake with specific username.
func (s *Store) userUsernameAssociate(flake, username string) {
	s.link("../users/"+flake, s.UsernamePath(username))
}

// userUsernameDisassociate disassociates specific username.
func (s *Store) userUsernameDisassociate(username string) {
	if err := os.Remove(s.UsernamePath(username)); err != nil {
		s.fatalClose(fmt.Sprintf("Error disassociating username %s, %s", username, err))
	}
}

// userPassword returns password of user from path to user directory.
func (s *Store) userPassword(path string) string {
	if payload, err := os.ReadFile(path + "/passwd"); err != nil {
		if os.IsNotExist(err) {
			return ""
		}
		s.fatalClose(fmt.Sprintf("Error reading password from user directory %s, %s", path, err))
	} else {
		return string(payload)
	}
	return ""
}

// userPasswordUpdate updates user password of user from path to user directory.
func (s *Store) userPasswordUpdate(path, password string) bool {
	if len(password) > 1024 {
		return false
	}
	if err := os.WriteFile(path+"/passwd", []byte(password), s.PermissionFile); err != nil {
		s.fatalClose(fmt.Sprintf("Error setting password for user directory %s, %s", path, err))
	} else {
		return true
	}
	return false
}

// UserPasswordValidate validates password of specified user.
func (s *Store) UserPasswordValidate(flake, password string) bool {
	if !s.flake(flake) || !s.file(s.UserPath(flake)) {
		return false
	}

	s.getLock(flake).RLock()
	defer s.getLock(flake).RUnlock()

	// Check password is not empty and matches
	if password != "" && password == s.userPassword(s.UserPath(flake)) {
		return true
	}

	return false
}

// UserUsernamePasswordValidate validates password of specified user from username.
func (s *Store) UserUsernamePasswordValidate(username, password string) bool {
	if !nameRegex.MatchString(username) || !s.file(s.UsernamePath(username)) {
		return false
	}

	s.getLock(username).RLock()
	defer s.getLock(username).RUnlock()

	if password != "" && password == s.userPassword(s.readlink(s.UsernamePath(username))) {
		return true
	}

	return false
}

// UserPasswordUpdate updates password of specified user.
func (s *Store) UserPasswordUpdate(flake, password string) bool {
	if !s.flake(flake) {
		return false
	}

	s.getLock(flake).Lock()
	defer s.getLock(flake).Unlock()

	return s.userPasswordUpdate(s.UserPath(flake), password)
}

// UserDestroy destroys a user with specific snowflake.
func (s *Store) UserDestroy(flake string) {
	if !s.flake(flake) {
		return
	}
	if !s.dir(s.UserPath(flake)) {
		return
	}

	s.getLock(flake).Lock()
	defer s.getLock(flake).Unlock()

	info := s.User(flake)
	// Check if info correct
	if info.Snowflake != flake {
		return
	}
	// Disassociate secret
	s.SecretDisassociate(info.Snowflake)
	// Remove user data directory
	if err := os.RemoveAll(s.UserPath(flake)); err != nil {
		s.fatalClose(fmt.Sprintf("Error destroying user %s data directory, %s", flake, err))
	}
	log.Infof("User %s username %s destroyed.", info.Snowflake, info.Username)
}

// UserImages returns slice of a user's images.
func (s *Store) UserImages(flake string) []string {
	if !s.flake(flake) {
		return nil
	}
	if !s.dir(s.UserImagesPath(flake)) {
		return nil
	}

	var images []string
	if entries, err := os.ReadDir(s.UserImagesPath(flake)); err != nil {
		s.fatalClose(fmt.Sprintf("Error reading user %s images, %s", flake, err))
	} else {
		for _, entry := range entries {
			images = append(images, entry.Name())
		}
	}
	return images
}