server/admin_player_password.go (2663B)
1 package main 2 3 import ( 4 "crypto/rand" 5 "database/sql" 6 "fmt" 7 "html" 8 "net/http" 9 "strconv" 10 ) 11 12 func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Request) { 13 id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) 14 if err != nil { 15 http.NotFound(w, r) 16 return 17 } 18 var name string 19 var adopted bool 20 err = server.db.QueryRow("SELECT name, length(password_hash)>0 FROM characters WHERE id=? AND id<1000000", id).Scan(&name, &adopted) 21 if err == sql.ErrNoRows { 22 http.NotFound(w, r) 23 return 24 } 25 if err != nil { 26 http.Error(w, err.Error(), http.StatusInternalServerError) 27 return 28 } 29 if !adopted { 30 w.Header().Set("Content-Type", "text/html; charset=utf-8") 31 w.WriteHeader(http.StatusConflict) 32 server.adminPageStart(w, "Change player password", "Players") 33 fmt.Fprintf(w, "<section><h1>Change password</h1><p>This player has not been adopted.</p><a href='admin/players/%d'>Back to player</a></section></main></body></html>", id) 34 return 35 } 36 37 message := "" 38 if r.Method == http.MethodPost { 39 r.Body = http.MaxBytesReader(w, r.Body, 8192) 40 if err := r.ParseForm(); err != nil || !validNewPassword(r.PostForm.Get("password")) { 41 message = "Use a password of at least 5 characters and at most 1024 bytes." 42 } else { 43 // Password changes preserve the player's current game session. 44 salt := make([]byte, 16) 45 if _, err := rand.Read(salt); err != nil { 46 http.Error(w, err.Error(), http.StatusInternalServerError) 47 return 48 } 49 hash := server.browserPassword(r.PostForm.Get("password"), salt) 50 var savedID uint32 51 err = server.db.QueryRow("UPDATE characters SET password_salt=?, password_hash=? WHERE id=? AND length(password_hash)>0 RETURNING id", salt, hash, id).Scan(&savedID) 52 if err != nil { 53 http.Error(w, err.Error(), http.StatusInternalServerError) 54 return 55 } 56 http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d?password=saved", server.baseURL, id), http.StatusSeeOther) 57 return 58 } 59 } 60 w.Header().Set("Content-Type", "text/html; charset=utf-8") 61 if message != "" { 62 w.WriteHeader(http.StatusBadRequest) 63 } 64 server.adminPageStart(w, "Change player password", "Players") 65 fmt.Fprintf(w, "<section class='login'><h1>Change password</h1><p>%s</p>", html.EscapeString(name)) 66 if message != "" { 67 fmt.Fprintf(w, "<p class='error' role='alert'>%s</p>", message) 68 } 69 fmt.Fprintf(w, "<form method='post' action='admin/players/%d/password'><label>New password<input name='password' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label><button>Save password</button> <a href='admin/players/%d'>Cancel</a></form></section></main></body></html>", id, id) 70 }