Skip to content

Commit 83d0d98

Browse files
committed
validating jwt
1 parent 52c666d commit 83d0d98

File tree

4 files changed

+64
-9
lines changed

4 files changed

+64
-9
lines changed

.http

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,46 @@
11
### Variables
22
@apiurl = http://localhost:8080
3+
@accesstoken = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZ2UiOjY2LCJlbWFpbCI6InRlc3Q2NjZAdGVzdC5jb20iLCJleHAiOjE3MTkzNjExOTcsImlkIjoiNjY3OWY3YzExZmIwMzIyOTEzNGU4ZWIyIiwibmFtZSI6InRlc3Q2NjYifQ.u9vyc2TceclEPQWjZC55PdRojse9hbooq1WWN5bUPLg
34

45
### GET users
56
GET {{apiurl}}/users HTTP/1.1
67

78
### GET user by ID
8-
GET {{apiurl}}/getUserById/6679d7f7b2743187285959d0 HTTP/1.1
9+
GET {{apiurl}}/getUserById/667a12494c2b72ef58316a20 HTTP/1.1
10+
Authorization: Bearer {{accesstoken}}
911

1012
### GET user by EMAIL
1113
GET {{apiurl}}/getUserByEmail/test3@test.com HTTP/1.1
1214

1315
### UPDATE user by ID
14-
PATCH {{apiurl}}/updateUser/6679d7f7b2743187285959d0 HTTP/1.1
16+
PATCH {{apiurl}}/updateUser/667a12494c2b72ef58316a20 HTTP/1.1
1517
Content-Type: application/json
16-
Authorization: Bearer ACCESS-TOKEN
18+
Authorization: Bearer {{accesstoken}}
1719

1820
{
1921
"name":"test000000",
2022
"age":111
2123
}
2224

2325
### DELETE user by ID
24-
DELETE {{apiurl}}/deleteUser/6679d7f7b2743187285959d0 HTTP/1.1
26+
DELETE {{apiurl}}/deleteUser/667a12494c2b72ef58316a20 HTTP/1.1
2527

2628
### POST users
2729
POST {{apiurl}}/createUser HTTP/1.1
2830
Content-Type: application/json
29-
Authorization: Bearer ACCESS-TOKEN
31+
Authorization: Bearer {{accesstoken}}
3032

3133
{
32-
"email":"test666@test.com",
34+
"email":"test77@test.com",
3335
"password":"test@123",
34-
"name":"test666",
35-
"age":66
36+
"name":"test77",
37+
"age":77
3638
}
3739

3840
### LOGIN user
3941
POST {{apiurl}}/login HTTP/1.1
4042
Content-Type: application/json
41-
Authorization: Bearer ACCESS-TOKEN
43+
Authorization: Bearer {{accesstoken}}
4244

4345
{
4446
"email":"test666@test.com",

src/config/rest_err/rest_err.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,11 @@ func NewForbiddenErrorfunc(message string) *RestErr {
6767
Code: http.StatusBadRequest,
6868
}
6969
}
70+
71+
func NewUnauthorizedErrorfunc(message string) *RestErr {
72+
return &RestErr{
73+
Message: message,
74+
Err: "unauthorized",
75+
Code: http.StatusUnauthorized,
76+
}
77+
}

src/controller/find_user.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
11
package controller
22

33
import (
4+
"fmt"
45
"net/http"
56
"net/mail"
67

78
"github.com/gin-gonic/gin"
9+
"github.com/murillolamego/golang-basic/src/config/logger"
810
"github.com/murillolamego/golang-basic/src/config/rest_err"
11+
"github.com/murillolamego/golang-basic/src/model"
912
"github.com/murillolamego/golang-basic/src/view"
1013
"go.mongodb.org/mongo-driver/bson/primitive"
1114
)
1215

1316
func (uc *userControllerInterface) FindUserByID(c *gin.Context) {
17+
18+
user, err := model.VerifyToken(c.Request.Header.Get("Authorization"))
19+
if err != nil {
20+
c.JSON(err.Code, err.Message)
21+
return
22+
}
23+
24+
logger.Info(fmt.Sprintf("User authenticated: %v", user))
25+
1426
userId := c.Param("userId")
1527

1628
if _, err := primitive.ObjectIDFromHex(userId); err != nil {

src/model/user_token_domain.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package model
22

33
import (
44
"os"
5+
"strings"
56
"time"
67

78
"github.com/golang-jwt/jwt/v5"
@@ -32,3 +33,35 @@ func (ud *userDomain) GenerateToken() (string, *rest_err.RestErr) {
3233

3334
return tokenString, nil
3435
}
36+
37+
func RemoveBearerPrefix(token string) string {
38+
return strings.TrimPrefix(token, "Bearer ")
39+
}
40+
41+
func VerifyToken(tokenValue string) (UserDomainInterface, *rest_err.RestErr) {
42+
secret := os.Getenv(JWT_SECRET_KEY)
43+
44+
token, err := jwt.Parse(RemoveBearerPrefix(tokenValue), func(token *jwt.Token) (interface{}, error) {
45+
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
46+
return []byte(secret), nil
47+
}
48+
49+
return nil, rest_err.NewBadRequestError("invalid token 1")
50+
})
51+
52+
if err != nil {
53+
return nil, rest_err.NewUnauthorizedErrorfunc("invalid token 2")
54+
}
55+
56+
claims, ok := token.Claims.(jwt.MapClaims)
57+
if !ok || !token.Valid {
58+
return nil, rest_err.NewUnauthorizedErrorfunc("invalid token 3")
59+
}
60+
61+
return &userDomain{
62+
id: claims["id"].(string),
63+
email: claims["email"].(string),
64+
name: claims["name"].(string),
65+
age: int8(claims["age"].(float64)),
66+
}, nil
67+
}

0 commit comments

Comments
 (0)