MCPcopy Index your code
hub / github.com/PatchMon/PatchMon / SetupAdmin

Method SetupAdmin

server-source-code/internal/handler/auth.go:1297–1369  ·  view source on GitHub ↗

SetupAdmin handles POST /auth/setup-admin (first-time admin creation).

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

1295
1296// SetupAdmin handles POST /auth/setup-admin (first-time admin creation).
1297func (h *AuthHandler) SetupAdmin(w http.ResponseWriter, r *http.Request) {
1298 if h.log != nil {
1299 h.log.Debug("auth request", "method", r.Method, "path", r.URL.Path)
1300 }
1301 var req struct {
1302 FirstName string `json:"firstName"`
1303 LastName string `json:"lastName"`
1304 Username string `json:"username"`
1305 Email string `json:"email"`
1306 Password string `json:"password"`
1307 }
1308 if err := decodeJSON(r, &req); err != nil {
1309 Error(w, http.StatusBadRequest, "Invalid request body")
1310 return
1311 }
1312 if req.FirstName == "" || req.LastName == "" || req.Username == "" || req.Email == "" || req.Password == "" {
1313 Error(w, http.StatusBadRequest, "All fields are required")
1314 return
1315 }
1316 if err := ValidatePasswordPolicy(h.resolved, req.Password); err != nil {
1317 Error(w, http.StatusBadRequest, err.Error())
1318 return
1319 }
1320
1321 count, err := h.users.CountAdmins(r.Context())
1322 if err != nil || count > 0 {
1323 Error(w, http.StatusBadRequest, "Admin users already exist. This endpoint is only for first-time setup.")
1324 return
1325 }
1326
1327 exists, _ := h.users.ExistsByUsernameOrEmail(r.Context(), req.Username, req.Email, "")
1328 if exists {
1329 Error(w, http.StatusBadRequest, "Username or email already exists")
1330 return
1331 }
1332
1333 hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), 12)
1334 if err != nil {
1335 Error(w, http.StatusInternalServerError, "Failed to create admin")
1336 return
1337 }
1338 hashStr := string(hash)
1339
1340 u := &models.User{
1341 Username: req.Username,
1342 Email: req.Email,
1343 PasswordHash: &hashStr,
1344 Role: "superadmin",
1345 IsActive: true,
1346 FirstName: &req.FirstName,
1347 LastName: &req.LastName,
1348 }
1349 if err := h.users.Create(r.Context(), u); err != nil {
1350 Error(w, http.StatusInternalServerError, "Failed to create admin")
1351 return
1352 }
1353 AutoSubscribeIfHosted(h.cfg != nil && h.cfg.AdminMode, h.users, h.log, u)
1354

Callers

nothing calls this directly

Calls 13

createTokenMethod · 0.95
buildUserResponseMethod · 0.95
decodeJSONFunction · 0.85
ErrorFunction · 0.85
ValidatePasswordPolicyFunction · 0.85
AutoSubscribeIfHostedFunction · 0.85
ErrorMethod · 0.80
JSONFunction · 0.70
CountAdminsMethod · 0.65

Tested by

no test coverage detected