Skip to content

Commit

Permalink
Merge pull request #15 from minusno0708/feat/validate-token-exp
Browse files Browse the repository at this point in the history
トークンの有効期限による認証を追加
  • Loading branch information
minusno0708 authored Mar 8, 2024
2 parents a241183 + 925e501 commit 29a93f0
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
13 changes: 13 additions & 0 deletions domain/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,16 @@ func (t *Token) UUID() string {
func (t *Token) UserID() string {
return t.value.Claims.(jwt.MapClaims)["user_id"].(string)
}

func (t *Token) Exp() int64 {
exp, ok := t.value.Claims.(jwt.MapClaims)["exp"].(int64)
if !ok {
exp = int64(t.value.Claims.(jwt.MapClaims)["exp"].(float64))
}
return exp

}

func (t *Token) IsExpired() bool {
return time.Now().Unix() > int64(t.Exp())
}
21 changes: 20 additions & 1 deletion domain/token_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package domain

import "testing"
import (
"testing"
)

func TestDomainToken(t *testing.T) {
userID := "test_user"
Expand All @@ -24,3 +26,20 @@ func TestDomainToken(t *testing.T) {
t.Error("UUID is empty")
}
}

func TestDomainTokenExpired(t *testing.T) {
userID := "test_user"
token := NewToken(userID)
if token.IsExpired() {
t.Error("Token is expired")
}

tokenString, err := token.ToString()
if err != nil {
t.Error("Error while generating token")
}
parsedToken, _ := ParseToken(tokenString)
if parsedToken.IsExpired() {
t.Error("Token is expired")
}
}
4 changes: 4 additions & 0 deletions usecase/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ func (tu tokenUseCase) ValidateToken(tokenString string) (string, error) {
return "", err
}

if token.IsExpired() {
return "", errors.New("token is expired")
}

userID := token.UserID()
tokenUUID, err := tu.tokenRepository.ValidateToken(userID)
if err != nil {
Expand Down

0 comments on commit 29a93f0

Please sign in to comment.