Files
go-socket/http.go
T
2026-03-11 19:46:37 +01:00

78 lines
1.9 KiB
Go

package main
import (
"log"
"net/http"
"golang.org/x/crypto/bcrypt"
)
func RegisterHandler(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodPost {
http.Error(response, "POST only", http.StatusMethodNotAllowed)
return
}
ctx := request.Context()
username := request.FormValue("username")
password := request.FormValue("password")
if len(username) < 2 {
http.Error(response, "short username", http.StatusBadRequest)
return
}
if len(password) < 8 {
http.Error(response, "short password", http.StatusBadRequest)
return
}
if _, err := GetUserDataByName(ctx, username); err == nil {
http.Error(response, "User already exists", http.StatusBadRequest)
return
}
if _, err := AddNewUser(ctx, User{0, username, password, "xxx", false}); err != nil {
http.Error(response, "Internal server error", http.StatusInternalServerError)
log.Fatal(err)
return
}
response.WriteHeader(http.StatusCreated)
_, err := response.Write([]byte("registered"))
if err != nil {
http.Error(response, "Internal server error", http.StatusInternalServerError)
return
}
}
func LoginHandler(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodPost {
http.Error(response, "POST only", http.StatusMethodNotAllowed)
}
ctx := request.Context()
username := request.FormValue("username")
password := request.FormValue("password")
if len(username) < 2 {
http.Error(response, "short username", http.StatusBadRequest)
return
}
user, err := GetUserDataByName(ctx, username)
if err != nil {
http.Error(response, "Bad login", http.StatusBadRequest)
return
}
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) == nil {
token, err := GetToken(user)
if err != nil {
http.Error(response, "Internal server error", http.StatusInternalServerError)
return
}
if _, err = response.Write([]byte(token)); err != nil {
return
}
}
}