/
auth.go
140 lines (104 loc) · 2.53 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
"strings"
"sync"
"time"
// "log"
)
const (
Anonymous = ""
)
type Cookie struct {
expires int64
ID string
anonymous bool
nick string
team string
}
var (
cookies = map[string]*Cookie{}
mutex = &sync.Mutex{}
)
func initAuth() {
ticker := time.NewTicker(time.Hour)
go func() {
for _ = range ticker.C {
now := time.Now().Unix()
mutex.Lock()
for k, cookie := range cookies {
if now > cookie.expires {
delete(cookies, k)
fmt.Println("Removed", k)
}
}
mutex.Unlock()
}
}()
}
func getSessionUserId(r *http.Request) *Cookie {
validSessionUserId := func(token string) *Cookie {
now := time.Now().Unix()
mutex.Lock()
defer mutex.Unlock()
if cookie, exists := cookies[token]; exists {
if now > cookie.expires {
delete(cookies, token)
return nil
}
return cookie
}
return nil
}
for _, cookie := range r.Cookies() {
if cookie.Name == "token" {
return validSessionUserId(cookie.Value)
}
}
return nil
}
func setSessionFromAnonymous(c *gin.Context) string {
r1 := rand.Uint32()
token128 := fmt.Sprintf("%x%x%x%x",
r1, rand.Uint32(), rand.Uint32(), rand.Uint32())
expires := time.Now().Unix() + 365*7*24*3600
ID := token128
names := []string{"Arbol","Pierda","Rio"}
surenames := []string{"Rojo","Verde","Azul","Amarillo","Fuerte"}
nick := names[r1%uint32(len(names))]+"-"+surenames[r1%uint32(len(surenames))]
mutex.Lock()
cookies[token128] = &Cookie{expires: expires, ID: ID, anonymous: true, nick: nick}
mutex.Unlock()
cookie := http.Cookie{Name: "token", Value: token128}
http.SetCookie(c.Writer, &cookie)
return ID
}
func setSessionFromTLS(c *gin.Context) string {
if len(c.Request.TLS.PeerCertificates) == 0 {
fmt.Println("------ user ANONIM ------")
return Anonymous
}
cn := c.Request.TLS.PeerCertificates[0].Subject.CommonName
split := strings.Split(cn, " - NIF ")
ID := "NIF" + split[1]
nick := ID
token128 := fmt.Sprintf("%x%x%x%x",
rand.Uint32(), rand.Uint32(), rand.Uint32(), rand.Uint32())
expires := time.Now().Unix() + 7*24*3600
user, err := load(ID)
if err == nil {
fmt.Printf("------ user: %v ------", user)
nick = user.PublicName
} else {
fmt.Printf("------ user: %v ------", err)
}
mutex.Lock()
cookies[token128] = &Cookie{expires: expires, ID: ID, anonymous: false, nick: nick}
mutex.Unlock()
cookie := http.Cookie{Name: "token", Value: token128}
http.SetCookie(c.Writer, &cookie)
return ID
}