-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwts.go
69 lines (61 loc) · 2.07 KB
/
jwts.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
package vbdb
import (
"fmt"
"time"
"github.com/vikebot/vbcore"
"go.uber.org/zap"
)
// JwtIsBlacklistedCtx checks whether the passed `jti` (JWT ID) is already
// blacklisted or not
func JwtIsBlacklistedCtx(jti string, ctx *zap.Logger) (blacklisted bool, success bool) {
var valid int
exists, err := s.SelectExists("SELECT id FROM jwts WHERE jti=? AND valid=1",
[]interface{}{jti},
[]interface{}{&valid})
if err != nil {
ctx.Error("vbdb.JwtIsBlacklistedCtx",
zap.String("jti", jti),
zap.Error(err))
return false, false
}
// If the JWT exists ether increase iuc (invalid-usage-count) or vuc
// (valid-usage-count)
if exists {
column := vbcore.TernaryOperatorA(valid == 0, "iuc", "vuc")
err = s.Exec(fmt.Sprintf("UPDATE jwts SET %s = %s + 1 WHERE jti=?", column, column), jti)
if err != nil {
ctx.Error("jti exists but increasing iuc or vuc failed", zap.Error(err))
return false, false
}
}
ctx.Debug("vbdb.JwtIsBlacklistedCtx",
zap.String("jti", jti),
zap.Bool("blacklisted", valid == 0))
return valid == 0, true
}
// JwtIsBlacklisted is the same as `JwtIsBlacklistedCtx` but uses the
// `defaultCtx` as logger.
func JwtIsBlacklisted(jti string) (blacklisted bool, success bool) {
return JwtIsBlacklistedCtx(jti, defaultCtx)
}
// JwtAddCtx adds the passed `jti` (JWT ID), `exp` and `userID` into the
// `jwts` table as valid entries. Can later be modified to invalid
// (e.g. blacklisted)
func JwtAddCtx(jti string, exp time.Time, userID int, iat time.Time, ip string, ctx *zap.Logger) (success bool) {
err := s.Exec("INSERT INTO jwts (jti, exp, user_id, iat, ip) VALUES(?, ?, ?, ?, ?)", jti, exp, userID, iat, ip)
if err != nil {
ctx.Error("vbdb.JwtAdd",
zap.String("jti", jti),
zap.Time("exp", exp),
zap.Int("user_id", userID),
zap.Time("iat", iat),
zap.String("ip", ip),
zap.Error(err))
return false
}
return true
}
// JwtAdd is the same as `JwtAddCtx` but uses the `defaultCtx` as logger.
func JwtAdd(jti string, exp time.Time, userID int, iat time.Time, ip string) (success bool) {
return JwtAddCtx(jti, exp, userID, iat, ip, defaultCtx)
}