aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/browser_password.go (2091B)


      1 package main
      2 
      3 import (
      4 	"crypto/rand"
      5 	"database/sql"
      6 	"net/http"
      7 	"unicode/utf8"
      8 )
      9 
     10 func validNewPassword(password string) bool {
     11 	return utf8.RuneCountInString(password) >= 5 && len(password) <= 1024
     12 }
     13 
     14 func (server *server) changeBrowserPassword(w http.ResponseWriter, r *http.Request) {
     15 	r.Body = http.MaxBytesReader(w, r.Body, 4096)
     16 	if err := r.ParseForm(); err != nil || !validNewPassword(r.PostForm.Get("password")) {
     17 		http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest)
     18 		return
     19 	}
     20 	credential := browserCredential(r)
     21 	id, err := server.browserPlayerID(credential)
     22 	if err != nil {
     23 		http.Error(w, err.Error(), http.StatusInternalServerError)
     24 		return
     25 	}
     26 	if id == 0 {
     27 		http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
     28 		return
     29 	}
     30 
     31 	var adopted bool
     32 	err = server.db.QueryRow("SELECT length(password_hash)>0 FROM characters WHERE id=?", id).Scan(&adopted)
     33 	if err != nil {
     34 		http.Error(w, err.Error(), http.StatusInternalServerError)
     35 		return
     36 	}
     37 	if !adopted {
     38 		http.Error(w, "Adopt this visitor before changing its password.", http.StatusConflict)
     39 		return
     40 	}
     41 
     42 	// Derive the new credential without blocking the game simulation.
     43 	salt := make([]byte, 16)
     44 	if _, err := rand.Read(salt); err != nil {
     45 		http.Error(w, err.Error(), http.StatusInternalServerError)
     46 		return
     47 	}
     48 	hash := server.browserPassword(r.PostForm.Get("password"), salt)
     49 
     50 	// Recheck the credential in the atomic write after hashing. A concurrent
     51 	// login or replacement must not let an old cookie change the password.
     52 	var savedID uint32
     53 	err = server.db.QueryRow("UPDATE characters SET password_salt=?, password_hash=? WHERE id=? AND browser_token_hash=? AND length(password_hash)>0 RETURNING id", salt, hash, id, credential).Scan(&savedID)
     54 	if err == sql.ErrNoRows {
     55 		http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
     56 		return
     57 	}
     58 	if err != nil {
     59 		http.Error(w, err.Error(), http.StatusInternalServerError)
     60 		return
     61 	}
     62 	w.WriteHeader(http.StatusNoContent)
     63 }