package handlers import ( "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "golias/models" "golias/utils" "html/template" "net/http" "strings" "time" ) func abortWithError(w http.ResponseWriter, msg string) { w.WriteHeader(500) tmpl := template.Must(template.ParseGlob("components/*.html")) tmpl.ExecuteTemplate(w, "error", msg) } func HandleNameCheck(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.PostFormValue("username") if username == "" { msg := "username not provided" log.Error(msg) abortWithError(w, msg) return } cleanName := utils.RemoveSpacesFromStr(username) allNames := getAllNames() log.Info("names check", "taken_names", allNames, "trying_name", cleanName) tmpl, err := template.ParseGlob("components/*.html") if err != nil { abortWithError(w, err.Error()) return } if utils.StrInSlice(cleanName, allNames) { err := fmt.Errorf("name: %s already taken", cleanName) log.Warn("already taken", "error", err) tmpl.ExecuteTemplate(w, "namecheck", 2) return } tmpl.ExecuteTemplate(w, "namecheck", 0) } func HandleFrontLogin(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.PostFormValue("username") if username == "" { msg := "username not provided" log.Error(msg) abortWithError(w, msg) return } // make sure username does not exists cleanName := utils.RemoveSpacesFromStr(username) // TODO: create user in db // login user cookie, err := makeCookie(cleanName, r.RemoteAddr) if err != nil { log.Error("failed to login", "error", err) abortWithError(w, err.Error()) return } http.SetCookie(w, cookie) tmpl, err := template.ParseGlob("components/*.html") if err != nil { abortWithError(w, err.Error()) return } // session, ok :=r.Context().Value(models.CtxSessionKey).(*models.Session) // if !ok{ // abortWithError(w, "failed to extract session from ctx") // return // } // state := models.InitState(cleanName) state := models.MakeTestState() state.State.Username = cleanName // save state to cache saveState(cleanName, state.State) tmpl.ExecuteTemplate(w, "base", state) } func makeCookie(username string, remote string) (*http.Cookie, error) { // secret // Create a new random session token // sessionToken := xid.New().String() sessionToken := "sessionprefix_" + username expiresAt := time.Now().Add(time.Duration(cfg.SessionLifetime) * time.Second) // Set the token in the session map, along with the session information session := &models.Session{ Username: username, Expiry: expiresAt, } cookieName := "session_token" // hmac to protect cookies hm := hmac.New(sha256.New, []byte(cfg.CookieSecret)) hm.Write([]byte(cookieName)) hm.Write([]byte(sessionToken)) signature := hm.Sum(nil) // b64 enc to avoid non-ascii cookieValue := base64.URLEncoding.EncodeToString([]byte( string(signature) + sessionToken)) cookie := &http.Cookie{ Name: cookieName, Value: cookieValue, Secure: true, HttpOnly: true, SameSite: http.SameSiteNoneMode, Domain: cfg.ServerConfig.Host, } log.Info("check remote addr for cookie set", "remote", remote, "session", session) if strings.Contains(remote, "192.168.0") { cookie.Domain = "home.host" log.Info("changing cookie domain", "domain", cookie.Domain) } // set ctx? // set user in session if err := cacheSetSession(sessionToken, session); err != nil { return nil, err } return cookie, nil } func cacheGetSession(key string) (*models.Session, error) { userSessionB, err := memcache.Get(key) if err != nil { return nil, err } var us *models.Session if err := json.Unmarshal(userSessionB, &us); err != nil { return nil, err } return us, nil } func cacheSetSession(key string, session *models.Session) error { sesb, err := json.Marshal(session) if err != nil { return err } memcache.Set(key, sesb) // expire in 10 min memcache.Expire(key, 10*60) return nil } func updateRoomInSession(ctx context.Context, roomID string) (context.Context, error) { s, ok := ctx.Value("session").(models.Session) if !ok { return context.TODO(), errors.New("failed to extract session from ctx") } s.CurrentRoom = roomID return context.WithValue(ctx, "session", s), nil }