comparison pkg/auth/session.go @ 447:62c909dd3098

Only allow log in if user has at least one of the roles 'sys_admin', 'waterway_admin', 'waterway_user'.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Tue, 21 Aug 2018 18:29:34 +0200
parents c1047fd04a3a
children b2dc9c2f69e0
comparison
equal deleted inserted replaced
446:659c04feb2dc 447:62c909dd3098
1 package auth 1 package auth
2 2
3 import ( 3 import (
4 "encoding/base64" 4 "encoding/base64"
5 "errors"
5 "io" 6 "io"
6 "time" 7 "time"
7 8
8 "gemma.intevation.de/gemma/pkg/common" 9 "gemma.intevation.de/gemma/pkg/common"
9 "gemma.intevation.de/gemma/pkg/misc" 10 "gemma.intevation.de/gemma/pkg/misc"
25 } 26 }
26 } 27 }
27 return false 28 return false
28 } 29 }
29 30
31 func (r Roles) HasAny(roles ...string) bool {
32 for _, y := range roles {
33 if r.Has(y) {
34 return true
35 }
36 }
37 return false
38 }
39
30 const ( 40 const (
31 sessionKeyLength = 20 41 sessionKeyLength = 20
32 maxTokenValid = time.Hour * 3 42 maxTokenValid = time.Hour * 3
33 ) 43 )
34 44
35 func NewSession(user, password string, roles []string) *Session { 45 func NewSession(user, password string, roles Roles) *Session {
36 46
37 // Create the Claims 47 // Create the Claims
38 return &Session{ 48 return &Session{
39 ExpiresAt: time.Now().Add(maxTokenValid).Unix(), 49 ExpiresAt: time.Now().Add(maxTokenValid).Unix(),
40 User: user, 50 User: user,
76 func GenerateSessionKey() string { 86 func GenerateSessionKey() string {
77 return base64.URLEncoding.EncodeToString( 87 return base64.URLEncoding.EncodeToString(
78 common.GenerateRandomKey(sessionKeyLength)) 88 common.GenerateRandomKey(sessionKeyLength))
79 } 89 }
80 90
91 var ErrInvalidRole = errors.New("Invalid role")
92
81 func GenerateSession(user, password string) (string, *Session, error) { 93 func GenerateSession(user, password string) (string, *Session, error) {
82 roles, err := AllOtherRoles(user, password) 94 roles, err := AllOtherRoles(user, password)
83 if err != nil { 95 if err != nil {
84 return "", nil, err 96 return "", nil, err
97 }
98 if !roles.HasAny("sys_admin", "waterway_admin", "waterway_user") {
99 return "", nil, ErrInvalidRole
85 } 100 }
86 token := GenerateSessionKey() 101 token := GenerateSessionKey()
87 session := NewSession(user, password, roles) 102 session := NewSession(user, password, roles)
88 ConnPool.Add(token, session) 103 ConnPool.Add(token, session)
89 return token, session, nil 104 return token, session, nil