forked from WEB-IMB-WS2526/lab-development-imb
86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type UserData struct {
|
|
Username string `json:"username"`
|
|
Nickname string `json:"nickname"`
|
|
Admin bool `json:"admin"`
|
|
}
|
|
|
|
var (
|
|
sessions = make(map[string]UserData)
|
|
mu sync.Mutex
|
|
)
|
|
|
|
func checkSessionID(r *http.Request) (string, error) {
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
return "", errors.New("keine session-ID")
|
|
}
|
|
return cookie.Value, nil
|
|
}
|
|
|
|
func getSessionID(w http.ResponseWriter, r *http.Request) string {
|
|
sessionID, err := checkSessionID(r)
|
|
if err != nil {
|
|
newID := uuid.New().String()
|
|
newCookie := http.Cookie{
|
|
Name: "session_id",
|
|
Value: newID,
|
|
}
|
|
http.SetCookie(w, &newCookie)
|
|
|
|
mu.Lock()
|
|
sessions[newID] = UserData{}
|
|
mu.Unlock()
|
|
|
|
return newID
|
|
}
|
|
return sessionID
|
|
}
|
|
|
|
func signup(w http.ResponseWriter, r *http.Request) {
|
|
sessionID := getSessionID(w, r)
|
|
var user UserData
|
|
err := json.NewDecoder(r.Body).Decode(&user)
|
|
if err != nil {
|
|
http.Error(w, "Daten konnten nicht verarbeitet werden.", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if user.Nickname == "" || user.Username == "" {
|
|
http.Error(w, "Daten unvollständig.", http.StatusBadRequest)
|
|
return
|
|
}
|
|
sessions[sessionID] = user
|
|
}
|
|
|
|
func whoami(w http.ResponseWriter, r *http.Request) {
|
|
sessionID, err := checkSessionID(r)
|
|
if err != nil {
|
|
fmt.Fprintf(w, "Du bist noch niemand.")
|
|
} else {
|
|
user := sessions[sessionID]
|
|
fmt.Fprintf(w, "Hallo %s!\n", user.Nickname)
|
|
if user.Admin {
|
|
fmt.Fprintln(w, "Du bist als Admin registriert.")
|
|
} else {
|
|
fmt.Fprintln(w, "Du bist nicht als Admin registriert.")
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/signup", signup)
|
|
http.HandleFunc("/whoami", whoami)
|
|
http.ListenAndServe("localhost:8080", nil)
|
|
}
|