summaryrefslogtreecommitdiff
path: root/handlers/admin.go
blob: a568ac548f35429037200ee59f2aa6c780416356 (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
package handlers

import (
	"auth-proxy/config"
	"auth-proxy/logging"
	"auth-proxy/middleware"
	"auth-proxy/models"
	"auth-proxy/types"
	"auth-proxy/utils"
	"auth-proxy/worker"
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"time"
)

var workerPool *types.WorkerPool

// SetWorkerPool sets the package-level worker pool instance.
func SetWorkerPool(pool *types.WorkerPool) {
	workerPool = pool
}

// AdminPageHandler serves the admin dashboard page.
func AdminPageHandler(w http.ResponseWriter, r *http.Request) {
	// Fetch all users to render on the page
	users, err := models.GetAllUsers()
	if err != nil {
		logging.AppLog.Error("Failed to retrieve users for admin page", "error", err)
		http.Error(w, "Could not load user data.", http.StatusInternalServerError)
		return
	}

	data := map[string]interface{}{
		"Paths":     config.Paths,
		"Users":     users,
		"XSRFToken": middleware.GetXSRFToken(r),
	}
	if err := templates.ExecuteTemplate(w, "admin.html", data); err != nil {
		logging.AppLog.Error("Failed to execute admin template", "error", err)
	}
}

// GetUsersHandler returns a list of all users with enriched information.
// It uses a worker pool to calculate extra information for each user in parallel.
func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
	ip := logging.GetClientIP(r)
	users, err := models.GetAllUsers()
	if err != nil {
		logging.AppLog.Error("Failed to retrieve users", "error", err, "ip", ip)
		http.Error(w, "Failed to retrieve users", http.StatusInternalServerError)
		return
	}

	enrichedUsers := make([]types.EnrichedUser, len(users))
	var wg sync.WaitGroup

	for i, user := range users {
		wg.Add(1)
		// Create copies of loop variables to avoid race conditions in the closure
		index := i
		userCopy := user

		task := func() {
			defer wg.Done()
			// Simulate some work, e.g., calculating a value or fetching related data.
			time.Sleep(5 * time.Millisecond)

			timeSinceLogin := "N/A"
			if userCopy.LastLoginAt != nil {
				timeSinceLogin = fmt.Sprintf("%.0fm ago", time.Since(*userCopy.LastLoginAt).Minutes())
			}

			enrichedUsers[index] = types.EnrichedUser{
				User:           &userCopy,
				TimeSinceLogin: timeSinceLogin,
			}
		}
		worker.Submit(workerPool, task)
	}

	wg.Wait() // Wait for all tasks to complete

	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(enrichedUsers); err != nil {
		logging.AppLog.Error("Failed to encode users to JSON", "error", err, "ip", ip)
	}
}

// UpdateUserRoleHandler updates a user's role.
func UpdateUserRoleHandler(w http.ResponseWriter, r *http.Request) {
	ip := logging.GetClientIP(r)
	// Get admin user from context
	adminUser, ok := r.Context().Value(types.SessionDataContextKey).(*types.User)
	if !ok || adminUser == nil {
		logging.AppLog.Error("Failed to get user from context for admin action", "ip", ip)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	adminUsername := adminUser.Username

	id := r.URL.Path[len(config.Paths.AdminUsersAPI+"/") : len(r.URL.Path)-len("/role")]
	if id == "" {
		logging.AppLog.Warn("Invalid user ID in request", "path", r.URL.Path, "ip", ip)
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	var req struct {
		Role string `json:"role"`
	}

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		logging.AppLog.Warn("Invalid request body for role update", "error", err, "ip", ip)
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	if req.Role != "admin" && req.Role != "user" {
		logging.AppLog.Warn("Invalid role provided for update", "role", req.Role, "ip", ip)
		http.Error(w, "Invalid role", http.StatusBadRequest)
		return
	}

	if err := models.UpdateUserRole(id, req.Role); err != nil {
		logging.AppLog.Error("Failed to update user role in database", "error", err, "target_user_id", id, "ip", ip)
		http.Error(w, "Failed to update role", http.StatusInternalServerError)
		return
	}

	logging.SecurityLog.Info("ADMIN ACTION", "action", "update_role", "performed_by", adminUsername, "target_user_id", id, "new_role", req.Role, "ip", ip)
	w.WriteHeader(http.StatusOK)
}

// DeleteUserHandler deletes a user.
func DeleteUserHandler(w http.ResponseWriter, r *http.Request) {
	ip := logging.GetClientIP(r)
	// Get admin user from context
	adminUser, ok := r.Context().Value(types.SessionDataContextKey).(*types.User)
	if !ok || adminUser == nil {
		logging.AppLog.Error("Failed to get user from context for admin action", "ip", ip)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	adminUsername := adminUser.Username

	id := r.URL.Path[len(config.Paths.AdminUsersAPI+"/"):]
	if id == "" {
		logging.AppLog.Warn("Invalid user ID in request", "path", r.URL.Path, "ip", ip)
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	if err := models.DeleteUser(id); err != nil {
		logging.AppLog.Error("Failed to delete user from database", "error", err, "target_user_id", id, "ip", ip)
		http.Error(w, "Failed to delete user", http.StatusInternalServerError)
		return
	}

	logging.SecurityLog.Info("ADMIN ACTION", "action", "delete_user", "performed_by", adminUsername, "target_user_id", id, "ip", ip)
	w.WriteHeader(http.StatusOK)
}

// SetUserActiveStatusHandler updates a user's active status.
func SetUserActiveStatusHandler(w http.ResponseWriter, r *http.Request) {
	ip := logging.GetClientIP(r)
	// Get admin user from context
	adminUser, ok := r.Context().Value(types.SessionDataContextKey).(*types.User)
	if !ok || adminUser == nil {
		logging.AppLog.Error("Failed to get user from context for admin action", "ip", ip)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	adminUsername := adminUser.Username

	id := r.URL.Path[len(config.Paths.AdminUsersAPI+"/") : len(r.URL.Path)-len("/status")]
	if id == "" {
		logging.AppLog.Warn("Invalid user ID in request", "path", r.URL.Path, "ip", ip)
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	var req struct {
		IsActive bool `json:"is_active"`
	}

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		logging.AppLog.Warn("Invalid request body for status update", "error", err, "ip", ip)
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	if err := models.SetUserActiveStatus(id, req.IsActive); err != nil {
		logging.AppLog.Error("Failed to update user status in database", "error", err, "target_user_id", id, "ip", ip)
		http.Error(w, "Failed to update status", http.StatusInternalServerError)
		return
	}

	logging.SecurityLog.Info("ADMIN ACTION", "action", "set_active_status", "performed_by", adminUsername, "target_user_id", id, "new_status", req.IsActive, "ip", ip)
	w.WriteHeader(http.StatusOK)
}

// CreateUserHandler handles creating a new user by an admin.
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
	ip := logging.GetClientIP(r)

	var reqBody struct {
		Username string `json:"username"`
		Password string `json:"password"`
		Role     string `json:"role"`
	}

	if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// Default role to "user" if not provided or invalid
	if reqBody.Role != "admin" && reqBody.Role != "user" {
		reqBody.Role = "user"
	}

	// Validate password policy
	if ok, message := utils.ValidatePassword(reqBody.Password); !ok {
		http.Error(w, message, http.StatusBadRequest)
		return
	}

	existingUser, err := models.GetUserByUsername(reqBody.Username)
	if err != nil {
		logging.AppLog.Error("Error checking username during admin user creation", "error", err, "ip", ip)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}
	if existingUser != nil {
		http.Error(w, "Username is already taken", http.StatusConflict)
		return
	}

	user, err := models.CreateUser(reqBody.Username, reqBody.Password, reqBody.Role)
	if err != nil {
		logging.AppLog.Error("Failed to create user via admin API", "error", err, "username", reqBody.Username, "ip", ip)
		http.Error(w, "Failed to create user", http.StatusInternalServerError)
		return
	}

	logging.SecurityLog.Info("USER CREATED BY ADMIN", "username", user.Username, "role", user.Role, "ip", ip)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(user); err != nil {
		logging.AppLog.Error("Failed to encode user to JSON", "error", err, "ip", ip)
	}
}