Skip to content

Commit ee93cdf

Browse files
committed
Remove dups from token usage history
1 parent 02b363b commit ee93cdf

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

auth-handler.go

+7-4
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ func handleLogout(w http.ResponseWriter, req *http.Request) {
6666
tokenInfo := tmp.(Token_Info)
6767
log.Printf(blue("User `%s` logged out. Token: %s"), tokenInfo.username, cookie.Value)
6868
tokens.Delete(cookie.Value)
69+
// Important information, save now
70+
go saveTokens()
6971
}
7072
}
7173
// MaxAge: -1 mean deleting cookie
@@ -248,13 +250,14 @@ func buildAuthHandler(handler http.Handler) http.Handler {
248250
}
249251
// Check useragent and IP address change
250252
ip := strings.Split(req.RemoteAddr, ":")[0]
251-
lastEntry := tokenInfo.history[len(tokenInfo.history)-1]
252-
if (lastEntry.ip != ip) || (lastEntry.useragent != req.UserAgent()) {
253-
tokenInfo.history = append(tokenInfo.history, Token_Usage_History{
253+
history_key := ip + " " + req.UserAgent()
254+
_, history_found := tokenInfo.history[history_key]
255+
if !history_found {
256+
tokenInfo.history[history_key] = Token_Usage_History{
254257
time: time.Now().Unix(),
255258
ip: ip,
256259
useragent: req.UserAgent(),
257-
})
260+
}
258261
tokens.Store(token, tokenInfo)
259262
// Important information, save now
260263
go saveTokens()

tokens.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ type Token_Info struct {
1717
// Updated to the maximum(cfg.MaxNonActiveTime) value on any use of the token
1818
countdown int
1919
username string
20-
history []Token_Usage_History
20+
history map[string]Token_Usage_History
2121
}
2222

2323
type Token_Usage_History struct {
24-
time int64
24+
time int64 // First usage
2525
ip string
2626
useragent string
2727
}
@@ -70,7 +70,8 @@ func newToken(username string, ip string, useragent string) string {
7070
ip: ip,
7171
useragent: useragent,
7272
}
73-
history := []Token_Usage_History{hEntry}
73+
history_key := ip + " " + useragent
74+
history := map[string]Token_Usage_History{history_key: hEntry}
7475
tokenInfo := Token_Info{
7576
username: username,
7677
countdown: cfg.MaxNonActiveTime,
@@ -158,7 +159,7 @@ func loadTokens() error {
158159
log.Fatal(err)
159160
}
160161
// Parse token history. Each entry starts with tab
161-
history := []Token_Usage_History{}
162+
history := map[string]Token_Usage_History{}
162163
var hEntry Token_Usage_History
163164
for (i+1 < len(lines)) && (len(lines[i+1]) > 0) && (lines[i+1][0] == '\t') {
164165
i += 1
@@ -174,7 +175,8 @@ func loadTokens() error {
174175
}
175176
hEntry.ip = parts[2]
176177
hEntry.useragent = parts[3]
177-
history = append(history, hEntry)
178+
history_key := hEntry.ip + " " + hEntry.useragent
179+
history[history_key] = hEntry
178180
}
179181
// Drop token for deleted user
180182
in_tg := false

0 commit comments

Comments
 (0)