diff options
author | GrailFinder <wohilas@gmail.com> | 2024-04-28 07:03:36 +0300 |
---|---|---|
committer | GrailFinder <wohilas@gmail.com> | 2024-04-28 07:03:36 +0300 |
commit | 8d66ec58e2256412a2fd50ad9e651c09af1ea8cc (patch) | |
tree | 23ad5c78ba2b2da32628e9004fe932e6fa63e26b /internal/handlers/auth.go | |
parent | b33be53ea9c0be523988a9412fd8e3f6a24782b3 (diff) |
Feat: auth middleware; login [wip]
Diffstat (limited to 'internal/handlers/auth.go')
-rw-r--r-- | internal/handlers/auth.go | 55 |
1 files changed, 44 insertions, 11 deletions
diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go index 435f8ff..5ec1c80 100644 --- a/internal/handlers/auth.go +++ b/internal/handlers/auth.go @@ -3,7 +3,7 @@ package handlers import ( "apjournal/internal/models" "apjournal/pkg/utils" - "fmt" + "encoding/json" "html/template" "net/http" "strings" @@ -32,21 +32,32 @@ func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) { return } cleanName := utils.RemoveSpacesFromStr(username) - // allNames := h.s.CacheGetAllNames() - allNames := []string{} - if utils.StrInSlice(cleanName, allNames) { - err := fmt.Errorf("name: %s already taken", cleanName) - h.log.Error("already taken", "error", err) - abortWithError(w, err.Error()) - return - } cookie, err := h.makeCookie(cleanName, r.RemoteAddr) if err != nil { h.log.Error("failed to login", "error", err) abortWithError(w, err.Error()) + return } http.SetCookie(w, cookie) - http.Redirect(w, r, "/", 302) + // http.Redirect(w, r, "/", 302) + tmpl, err := template.ParseGlob("components/*.html") + if err != nil { + panic(err) + } + userScore, err := h.repo.DBUserScoreGet(cleanName) + if err != nil { + h.log.Warn("got db err", "err", err) + if err := h.repo.DBUserScoreCreate(&us); err != nil { + panic(err) + } + tmpl.ExecuteTemplate(w, "main", nil) + return + } + userScore.Actions, err = h.repo.DBActionList(cleanName) + if err != nil { + panic(err) + } + tmpl.ExecuteTemplate(w, "main", userScore) } func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, error) { @@ -72,10 +83,32 @@ func (h *Handlers) makeCookie(username string, remote string) (*http.Cookie, err "remote", remote, "session", session) if strings.Contains(remote, "192.168.0") { // no idea what is going on - // domainName = "192.168.0.101" cookie.Domain = "192.168.0.101" } // set ctx? // c.Set("username", username) return cookie, nil } + +func (h *Handlers) cacheGetSession(key string) (*models.Session, error) { + userSessionB, err := h.mc.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 (h *Handlers) cacheSetSession(key string, session *models.Session) error { + sesb, err := json.Marshal(session) + if err != nil { + return err + } + h.mc.Set(key, sesb) + // expire in 10 min + h.mc.Expire(key, 10*60) + return nil +} |