Mercurial > gemma
view auth/session.go @ 315:3ef0521609f5
Limit is not needed when fetching an email for a user.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Thu, 02 Aug 2018 10:03:54 +0200 |
parents | f345edb409b2 |
children | a7b2db8b3d18 |
line wrap: on
line source
package auth import ( "crypto/rand" "encoding/base64" "io" "time" ) type Session struct { ExpiresAt int64 `json:"expires"` User string `json:"user"` Password string `json:"password"` Roles []string `json:"roles"` } 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 := binWriter{w: w} wr.write(s.ExpiresAt) wr.writeString(s.User) wr.writeString(s.Password) wr.write(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 := binReader{r: r} rd.read(&x.ExpiresAt) rd.readString(&x.User) rd.readString(&x.Password) rd.read(&n) x.Roles = make([]string, 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(GenerateRandomKey(sessionKeyLength)) } func GenerateRandomKey(length int) []byte { k := make([]byte, length) if _, err := io.ReadFull(rand.Reader, k); err != nil { return nil } return k } 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 }