Mercurial > gemma
comparison 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 |
comparison
equal
deleted
inserted
replaced
413:a9440a4826aa | 414:c1047fd04a3a |
---|---|
1 package auth | |
2 | |
3 import ( | |
4 "encoding/base64" | |
5 "io" | |
6 "time" | |
7 | |
8 "gemma.intevation.de/gemma/pkg/common" | |
9 "gemma.intevation.de/gemma/pkg/misc" | |
10 ) | |
11 | |
12 type Roles []string | |
13 | |
14 type Session struct { | |
15 ExpiresAt int64 `json:"expires"` | |
16 User string `json:"user"` | |
17 Password string `json:"password"` | |
18 Roles Roles `json:"roles"` | |
19 } | |
20 | |
21 func (r Roles) Has(role string) bool { | |
22 for _, x := range r { | |
23 if x == role { | |
24 return true | |
25 } | |
26 } | |
27 return false | |
28 } | |
29 | |
30 const ( | |
31 sessionKeyLength = 20 | |
32 maxTokenValid = time.Hour * 3 | |
33 ) | |
34 | |
35 func NewSession(user, password string, roles []string) *Session { | |
36 | |
37 // Create the Claims | |
38 return &Session{ | |
39 ExpiresAt: time.Now().Add(maxTokenValid).Unix(), | |
40 User: user, | |
41 Password: password, | |
42 Roles: roles, | |
43 } | |
44 } | |
45 | |
46 func (s *Session) serialize(w io.Writer) error { | |
47 wr := misc.BinWriter{w, nil} | |
48 wr.WriteBin(s.ExpiresAt) | |
49 wr.WriteString(s.User) | |
50 wr.WriteString(s.Password) | |
51 wr.WriteBin(uint32(len(s.Roles))) | |
52 for _, role := range s.Roles { | |
53 wr.WriteString(role) | |
54 } | |
55 return wr.Err | |
56 } | |
57 | |
58 func (s *Session) deserialize(r io.Reader) error { | |
59 var x Session | |
60 var n uint32 | |
61 rd := misc.BinReader{r, nil} | |
62 rd.ReadBin(&x.ExpiresAt) | |
63 rd.ReadString(&x.User) | |
64 rd.ReadString(&x.Password) | |
65 rd.ReadBin(&n) | |
66 x.Roles = make(Roles, n) | |
67 for i := uint32(0); n > 0 && i < n; i++ { | |
68 rd.ReadString(&x.Roles[i]) | |
69 } | |
70 if rd.Err == nil { | |
71 *s = x | |
72 } | |
73 return rd.Err | |
74 } | |
75 | |
76 func GenerateSessionKey() string { | |
77 return base64.URLEncoding.EncodeToString( | |
78 common.GenerateRandomKey(sessionKeyLength)) | |
79 } | |
80 | |
81 func GenerateSession(user, password string) (string, *Session, error) { | |
82 roles, err := AllOtherRoles(user, password) | |
83 if err != nil { | |
84 return "", nil, err | |
85 } | |
86 token := GenerateSessionKey() | |
87 session := NewSession(user, password, roles) | |
88 ConnPool.Add(token, session) | |
89 return token, session, nil | |
90 } |