Skip to content

Commit

Permalink
⚡️ codeCacheへのRaceCondition対策
Browse files Browse the repository at this point in the history
  • Loading branch information
Shion1305 committed Feb 23, 2024
1 parent 9dcb727 commit 757124b
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions pkg/token/issuer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"google.golang.org/appengine/v2/log"
"strconv"
"sync"
"time"
"ynufes-mypage-backend/pkg/jwt"
)
Expand All @@ -16,23 +17,26 @@ type Issuer struct {
issuer string
maxAge time.Duration
codeCache map[string]credit
lock sync.RWMutex // lock for codeCache, prevents race condition
}

type credit struct {
id string
time int64
}

func NewTokenIssuer(jwtSecret string, issuer string, maxAge time.Duration) Issuer {
return Issuer{
func NewTokenIssuer(jwtSecret string, issuer string, maxAge time.Duration) *Issuer {
return &Issuer{
jwtSecret: jwtSecret,
issuer: issuer,
maxAge: maxAge,
codeCache: make(map[string]credit),
}
}

func (v Issuer) IssueNewCode(id string) (string, error) {
func (v *Issuer) IssueNewCode(id string) (string, error) {
v.lock.Lock()
defer v.lock.Unlock()
cnt := 0
newCode, err := v.generateSecret()
if err != nil {
Expand All @@ -53,6 +57,8 @@ func (v Issuer) IssueNewCode(id string) (string, error) {
}

func (v Issuer) IssueToken(code string) (string, error) {
v.lock.Lock()
defer v.lock.Unlock()
credit, ok := v.codeCache[code]
if !ok {
return "", fmt.Errorf("code not found")
Expand All @@ -72,6 +78,8 @@ func (v Issuer) IssueToken(code string) (string, error) {
}

func (v Issuer) RevokeOldCodes() {
v.lock.Lock()
defer v.lock.Unlock()
for s, t := range v.codeCache {
// If the code is older than 5 seconds, delete it
if time.Now().UnixMilli()-t.time > 5000 {
Expand Down

0 comments on commit 757124b

Please sign in to comment.