Mercurial > gemma
view auth/session.go @ 412:21fb992b1f5a
merge
author | Thomas Junk <thomas.junk@intevation.de> |
---|---|
date | Wed, 15 Aug 2018 16:54:49 +0200 |
parents | ac23905e64b1 |
children |
line wrap: on
line source
package auth import ( "encoding/base64" "io" "time" "gemma.intevation.de/gemma/common" "gemma.intevation.de/gemma/misc" ) type Roles []string type Session struct { ExpiresAt int64 `json:"expires"` User string `json:"user"` Password string `json:"password"` Roles Roles `json:"roles"` } func (r Roles) Has(role string) bool { for _, x := range r { if x == role { return true } } return false } const ( sessionKeyLength = 20 maxTokenValid = time.Hour * 3 ) func NewSession(user, password string, roles []string) *Session { // Create the Claims return &Session{ ExpiresAt: time.Now().Add(maxTokenValid).Unix(), User: user, Password: password, Roles: roles, } } func (s *Session) serialize(w io.Writer) error { wr := misc.BinWriter{w, nil} wr.WriteBin(s.ExpiresAt) wr.WriteString(s.User) wr.WriteString(s.Password) wr.WriteBin(uint32(len(s.Roles))) for _, role := range s.Roles { wr.WriteString(role) } return wr.Err } func (s *Session) deserialize(r io.Reader) error { var x Session var n uint32 rd := misc.BinReader{r, nil} rd.ReadBin(&x.ExpiresAt) rd.ReadString(&x.User) rd.ReadString(&x.Password) rd.ReadBin(&n) x.Roles = make(Roles, n) for i := uint32(0); n > 0 && i < n; i++ { rd.ReadString(&x.Roles[i]) } if rd.Err == nil { *s = x } return rd.Err } func GenerateSessionKey() string { return base64.URLEncoding.EncodeToString( common.GenerateRandomKey(sessionKeyLength)) } func GenerateSession(user, password string) (string, *Session, error) { roles, err := AllOtherRoles(user, password) if err != nil { return "", nil, err } token := GenerateSessionKey() session := NewSession(user, password, roles) ConnPool.Add(token, session) return token, session, nil }