package main import "net/http" func isMethodAllowed(response *http.ResponseWriter, request *http.Request) bool { if request.Method != http.MethodPost { http.Error(*response, "POST only", http.StatusMethodNotAllowed) return false } return true } func RegisterHandler(response http.ResponseWriter, request *http.Request) { if !isMethodAllowed(&response, request) { return } ctx := request.Context() username := request.FormValue("username") if len(username) < 4 { http.Error(response, "no or short username", http.StatusBadRequest) return } password := request.FormValue("password") if len(password) < 8 { http.Error(response, "no or short password", http.StatusBadRequest) return } newClient := Client{ Name: username, PasswordHash: password, } err := CreateClient(ctx, &newClient) if err != nil { http.Error(response, "taken", http.StatusBadRequest) return } response.Write([]byte("registered")) } func LoginHandler(response http.ResponseWriter, request *http.Request) { if !isMethodAllowed(&response, request) { return } ctx := request.Context() username := request.FormValue("username") if len(username) < 4 { http.Error(response, "no or short username", http.StatusBadRequest) return } password := request.FormValue("password") if len(password) < 8 { http.Error(response, "no or short password", http.StatusBadRequest) return } id, err := GetIdFromClientName(ctx, username) if err != nil { http.Error(response, "bad login", http.StatusBadRequest) } err = CheckPassword(ctx, id, password) if err != nil { http.Error(response, "bad login", http.StatusBadRequest) } token, err := GetToken(id) if err != nil { http.Error(response, "Internal error", http.StatusInternalServerError) } response.Write([]byte(token)) }