package main import ( "log" "math/rand" "net/http" glws "git.alfi.li/gamelang/frontend/webserver" gamelangpb "git.alfi.li/gamelang/protobuf/gamelang" "github.com/labstack/echo/v4" ) func userEndpoints(jg *JeopardyGameServer) []glws.Endpoint { endpoints := []glws.Endpoint{} endpoints = append(endpoints, glws.Endpoint{"GET", "/user", func(ctx echo.Context) error { log.Print("/user: get") log.Print("/user: sending register form") return ctx.Render(http.StatusOK, "registerform", "") }}) // POST to /user creates a user endpoints = append(endpoints, glws.Endpoint{"POST", "/user", func(ctx echo.Context) error { username := ctx.FormValue("username") password := ctx.FormValue("password") log.Printf("new user request: %v", username) newUser := gamelangpb.User{Name: username, Password: []byte(password)} id := rand.Uint32() name := newUser.GetName() _, err := jg.um.Create(id, name, password) //user, err := jg.userclient.CreateUser(context.Background(), &newUser) if err != nil { return ctx.String(501, "user creation failed") } jg.webserver.NewSession(newUser, ctx) log.Printf("new user created: %v", username) return ctx.Redirect(302, "/") }}) endpoints = append(endpoints, glws.Endpoint{"GET", "/login", func(ctx echo.Context) error { log.Print("/login: get") // check if the login page was called with failed parameter (set by /login POST) failedBefore := false if value := ctx.FormValue("failed"); value == "1" { failedBefore = true } ok, user := jg.webserver.CheckSess(ctx) if ok { // logged in log.Printf("/login: user %v logged in", user.Name) return ctx.String(http.StatusOK, "hello, "+user.Name+"\nyou are logged in.") } // not logged in log.Print("/login: not logged in") return ctx.Render(http.StatusOK, "loginform", failedBefore) }}) endpoints = append(endpoints, glws.Endpoint{"POST", "/login", func(ctx echo.Context) error { log.Print("/login: post") username := ctx.FormValue("username") password := ctx.FormValue("password") // if the session is already set, the user is already logged in ok, _ := jg.webserver.CheckSess(ctx) if ok { return ctx.String(http.StatusOK, "you are already logged in.") } log.Printf("user login attempt: %v", username) //checkuser := gamelangpb.User{Name: username, Password: []byte(password)} user, ok := jg.um.CheckUser(username, password) //jg.userclient.CheckUser(context.Background(), &checkuser) if ok { //err == nil { jg.webserver.NewSession(user, ctx) log.Printf("user login suceeded: %v", username) return ctx.String(http.StatusOK, "hello, "+username+"\nyou are now logged in.") } log.Printf("user login failed: %v\n%s", username) return ctx.Redirect(302, "/login?failed=1") }}) return endpoints }