Skip to content

Commit

Permalink
Jwt completed access and refresh token
Browse files Browse the repository at this point in the history
Signed-off-by: PratikforCoding <kotalpratik@gmail.com>
  • Loading branch information
PratikforCoding committed Oct 4, 2023
1 parent db3be15 commit e507ba4
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 4 deletions.
54 changes: 51 additions & 3 deletions auth/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,22 @@ func MakeRefreshToken(id string, jwtSecret string, expiresIn time.Duration) (str
return token.SignedString(signingKey)
}

func GetTokenFromCookie(r *http.Request) (string, error) {
func GetTokenFromCookie(r *http.Request, tokenSecret string) (string, error) {
// Get access_token from cookie
cookie, err := r.Cookie("access_token")
if err != nil {
if err == http.ErrNoCookie {
// If the cookie is not set, return an unauthorized status
return "", errors.New("no cookie included in request")
cookie, err = r.Cookie("refresh_token")
if err != nil {
if err == http.ErrNoCookie {
return "", errors.New("no refreshcookie included in request")
}
}
newAccessToken, err := RefreshToken(cookie.Value, tokenSecret)
if err != nil {
return "", err
}
return newAccessToken, nil
}

return "", errors.New("couldn't get cookie from request")
Expand Down Expand Up @@ -78,3 +87,42 @@ func ValidateJWT(tokenString, tokenSecret string) (string, error) {
return userIDString, nil
}

func RefreshToken(tokenString, tokenSecret string) (string, error) {
claimsStruct := jwt.RegisteredClaims{}
token, err := jwt.ParseWithClaims(
tokenString,
&claimsStruct,
func(token *jwt.Token) (interface{}, error) { return []byte(tokenSecret), nil },
)
if err != nil {
return "", err
}

userIDString, err := token.Claims.GetSubject()
if err != nil {
return "", err
}

issuer, err := token.Claims.GetIssuer()
if err != nil {
return "", err
}
if issuer != "busofact-refresh" {
return "", errors.New("invalid issuer")
}

if err != nil {
return "", err
}

newToken, err := MakeAccessToken(
userIDString,
tokenSecret,
time.Hour,
)
if err != nil {
return "", err
}

return newToken, nil
}
2 changes: 1 addition & 1 deletion controllers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (apiCfg *APIConfig)HandlerAddBuses(w http.ResponseWriter, r *http.Request)
StopageName string `json:"stopageName"`
}

token, err := auth.GetTokenFromCookie(r)
token, err := auth.GetTokenFromCookie(r, apiCfg.jwtSecret)
if err != nil {
reply.RespondWtihError(w, http.StatusUnauthorized, "Couldn't get token from request")
return
Expand Down
Binary file modified out
Binary file not shown.

0 comments on commit e507ba4

Please sign in to comment.