Skip to content

Commit

Permalink
bugfix: fix verify-token API not working
Browse files Browse the repository at this point in the history
  • Loading branch information
cho4036 committed Jan 17, 2024
1 parent 11a79f9 commit 73a8637
Show file tree
Hide file tree
Showing 6 changed files with 13 additions and 11 deletions.
1 change: 1 addition & 0 deletions internal/delivery/http/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ func (h *AuthHandler) PingToken(w http.ResponseWriter, r *http.Request) {
// @Summary verify token
// @Description verify token
// @Success 200 {object} nil
// @Failure 401 {object} nil
// @Router /auth/verify-token [get]

func (h *AuthHandler) VerifyToken(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion internal/middleware/auth/authenticator/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (a *defaultAuthenticator) WithAuthentication(handler http.Handler) http.Han
resp, ok, err := a.auth.AuthenticateRequest(r)
if !ok {
log.Error(err)
internalHttp.ErrorJSON(w, r, httpErrors.NewUnauthorizedError(err, "", ""))
internalHttp.ErrorJSON(w, r, err)
return
}
r = r.WithContext(request.WithUser(r.Context(), resp.User))
Expand Down
15 changes: 8 additions & 7 deletions internal/middleware/auth/authenticator/keycloak/keycloak.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keycloak

import (
"fmt"
"github.com/openinfradev/tks-api/pkg/httpErrors"
"net/http"
"strings"

Expand Down Expand Up @@ -50,21 +51,21 @@ func (a *keycloakAuthenticator) AuthenticateRequest(r *http.Request) (*authentic
func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string) (*authenticator.Response, bool, error) {
parsedToken, _, err := new(jwtWithouKey.Parser).ParseUnverified(token, jwtWithouKey.MapClaims{})
if err != nil {
return nil, false, err
return nil, false, httpErrors.NewUnauthorizedError(err, "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.")
}

organizationId, ok := parsedToken.Claims.(jwtWithouKey.MapClaims)["organization"].(string)
if !ok {
return nil, false, fmt.Errorf("organization is not found in token")
return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("organization is not found in token"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.")
}

isActive, err := a.kc.VerifyAccessToken(token, organizationId)
if err != nil {
log.Errorf("failed to verify access token: %v", err)
return nil, false, err
return nil, false, httpErrors.NewUnauthorizedError(err, "C_INTERNAL_ERROR", "")
}
if !isActive {
return nil, false, fmt.Errorf("token is not active")
return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("token is deactivated"), "A_EXPIRED_TOKEN", "토큰이 만료되었습니다.")
}

roleProjectMapping := make(map[string]string)
Expand All @@ -73,7 +74,7 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string)
if len(slice) != 2 {
log.Errorf("invalid tks-role format: %v", role)

return nil, false, fmt.Errorf("invalid tks-role format")
return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("invalid tks-role format"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.")
}
// key is projectName and value is roleName
roleProjectMapping[slice[1]] = slice[0]
Expand All @@ -82,11 +83,11 @@ func (a *keycloakAuthenticator) AuthenticateToken(r *http.Request, token string)
if err != nil {
log.Errorf("failed to verify access token: %v", err)

return nil, false, err
return nil, false, httpErrors.NewUnauthorizedError(err, "C_INTERNAL_ERROR", "")
}
requestSessionId, ok := parsedToken.Claims.(jwtWithouKey.MapClaims)["sid"].(string)
if !ok {
return nil, false, fmt.Errorf("session id is not found in token")
return nil, false, httpErrors.NewUnauthorizedError(fmt.Errorf("session id is not found in token"), "A_INVALID_TOKEN", "토큰이 유효하지 않습니다.")
}

userInfo := &user.DefaultInfo{
Expand Down
2 changes: 1 addition & 1 deletion internal/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func SetupRouter(db *gorm.DB, argoClient argowf.ArgoClient, kc keycloak.IKeycloa
r.HandleFunc(API_PREFIX+API_VERSION+"/auth/find-password/verification", authHandler.FindPassword).Methods(http.MethodPost)
r.HandleFunc(API_PREFIX+API_VERSION+"/auth/find-id/code", authHandler.VerifyIdentityForLostId).Methods(http.MethodPost)
r.HandleFunc(API_PREFIX+API_VERSION+"/auth/find-password/code", authHandler.VerifyIdentityForLostPassword).Methods(http.MethodPost)
r.HandleFunc(API_PREFIX+API_VERSION+"/auth/verify-token", authHandler.VerifyToken).Methods(http.MethodGet)
r.Handle(API_PREFIX+API_VERSION+"/auth/verify-token", authMiddleware.Handle(http.HandlerFunc(authHandler.VerifyToken))).Methods(http.MethodGet)
//r.HandleFunc(API_PREFIX+API_VERSION+"/cookie-test", authHandler.CookieTest).Methods(http.MethodPost)
//r.HandleFunc(API_PREFIX+API_VERSION+"/auth/callback", authHandler.CookieTestCallback).Methods(http.MethodGet)

Expand Down
3 changes: 1 addition & 2 deletions internal/usecase/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,11 +398,10 @@ func (u *AuthUsecase) VerifyToken(token string) (bool, error) {

isActive, err := u.kc.VerifyAccessToken(token, org)
if err != nil {
log.Errorf("failed to verify access token: %v", err)
return false, err
}
if !isActive {
return false, fmt.Errorf("token is not active")
return false, nil
}

return true, nil
Expand Down
1 change: 1 addition & 0 deletions pkg/httpErrors/errorCode.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var errorMap = map[ErrorCode]string{
"A_INVALID_PASSWORD": "비밀번호가 일치하지 않습니다.",
"A_SAME_OLD_PASSWORD": "기존 비밀번호와 동일합니다.",
"A_INVALID_TOKEN": "사용자 토큰 오류",
"A_EXPIRED_TOKEN": "사용자 토큰 만료",
"A_INVALID_USER_CREDENTIAL": "비밀번호가 일치하지 않습니다.",
"A_INVALID_ORIGIN_PASSWORD": "기존 비밀번호가 일치하지 않습니다.",
"A_INVALID_CODE": "인증번호가 일치하지 않습니다.",
Expand Down

0 comments on commit 73a8637

Please sign in to comment.