comparison auth/session.go @ 149:83d798ea9f58

Rename token.go to session.go because its more fitting.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 02 Jul 2018 11:14:46 +0200
parents auth/token.go@0c56c56a1c44
children 1585c334e8a7
comparison
equal deleted inserted replaced
148:0116aae1071b 149:83d798ea9f58
1 package auth
2
3 import (
4 "crypto/rand"
5 "encoding/base64"
6 "io"
7 "time"
8 )
9
10 type Session struct {
11 ExpiresAt int64 `json:"expires"`
12 User string `json:"user"`
13 Password string `json:"password"`
14 Roles []string `json:"roles"`
15 }
16
17 const (
18 sessionKeyLength = 20
19 maxTokenValid = time.Hour * 3
20 )
21
22 func NewSession(user, password string, roles []string) *Session {
23
24 // Create the Claims
25 return &Session{
26 ExpiresAt: time.Now().Add(maxTokenValid).Unix(),
27 User: user,
28 Password: password,
29 Roles: roles,
30 }
31 }
32
33 func GenerateSessionKey() string {
34 return base64.URLEncoding.EncodeToString(GenerateRandomKey(sessionKeyLength))
35 }
36
37 func GenerateRandomKey(length int) []byte {
38 k := make([]byte, length)
39 if _, err := io.ReadFull(rand.Reader, k); err != nil {
40 return nil
41 }
42 return k
43 }
44
45 func GenerateSession(user, password string) (string, *Session, error) {
46 roles, err := AllOtherRoles(user, password)
47 if err != nil {
48 return "", nil, err
49 }
50 token := GenerateSessionKey()
51 session := NewSession(user, password, roles)
52 ConnPool.Add(token, session)
53 return token, session, nil
54 }