summaryrefslogtreecommitdiff
path: root/auth/jwt_middleware.go
diff options
context:
space:
mode:
Diffstat (limited to 'auth/jwt_middleware.go')
-rw-r--r--auth/jwt_middleware.go30
1 files changed, 25 insertions, 5 deletions
diff --git a/auth/jwt_middleware.go b/auth/jwt_middleware.go
index 22d1fd7..8dd77b8 100644
--- a/auth/jwt_middleware.go
+++ b/auth/jwt_middleware.go
@@ -18,9 +18,13 @@
package auth
import (
- "net/http"
+ "github.com/MikunoNaka/OpenBills-server/user"
+ "go.mongodb.org/mongo-driver/bson/primitive"
+ "go.mongodb.org/mongo-driver/bson"
"github.com/golang-jwt/jwt/v4"
"github.com/gin-gonic/gin"
+ "net/http"
+ "context"
)
func Authorize() gin.HandlerFunc {
@@ -51,11 +55,27 @@ func verifyRefreshToken() gin.HandlerFunc {
token, err := jwt.ParseWithClaims(refreshToken, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(refreshSecret), nil
})
- if err != nil {
+ if err != nil { // invalid token
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"})
- } else {
- ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer)
- ctx.Next()
+ } else { // valid token
+ // convert id from string to ObjectID
+ id, _ := primitive.ObjectIDFromHex(token.Claims.(*jwt.StandardClaims).Issuer)
+
+ // check if user exists
+ var u user.User
+ if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil {
+ ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"message": "user not found"})
+ } else {
+ // check if this refreshToken is in DB
+ for _, i := range u.Sessions {
+ if i.Token == refreshToken {
+ ctx.Set("user", u)
+ ctx.Next()
+ } else {
+ ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"})
+ }
+ }
+ }
}
} else {
// invalid Authorization header