diff pkg/auth/session.go @ 414:c1047fd04a3a

Moved project specific Go packages to new pkg folder.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Wed, 15 Aug 2018 17:30:50 +0200
parents auth/session.go@ac23905e64b1
children 62c909dd3098
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pkg/auth/session.go	Wed Aug 15 17:30:50 2018 +0200
@@ -0,0 +1,90 @@
+package auth
+
+import (
+	"encoding/base64"
+	"io"
+	"time"
+
+	"gemma.intevation.de/gemma/pkg/common"
+	"gemma.intevation.de/gemma/pkg/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
+}