Skip to content

feat: add refresh token endpoint and related configurations #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/api/handler/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/naeemaei/golang-clean-web-api/api/dto"
"github.com/naeemaei/golang-clean-web-api/api/helper"
"github.com/naeemaei/golang-clean-web-api/config"
"github.com/naeemaei/golang-clean-web-api/constant"
"github.com/naeemaei/golang-clean-web-api/dependency"
"github.com/naeemaei/golang-clean-web-api/usecase"
)
Expand Down Expand Up @@ -48,6 +49,9 @@ func (h *UsersHandler) LoginByUsername(c *gin.Context) {
return
}

// Set the refresh token in a cookie
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's better to set sameSite attribute for CSRF protection

Suggested change
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
http.SetCookie(c.Writer, &http.Cookie{
Name: constant.RefreshTokenCookieName,
Value: token.RefreshToken,
MaxAge: int(h.config.JWT.RefreshTokenExpireDuration * 60),
Path: "/",
Domain: h.config.Server.Domain,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})


c.JSON(http.StatusCreated, helper.GenerateBaseResponse(token, true, helper.Success))
}

Expand Down Expand Up @@ -106,6 +110,9 @@ func (h *UsersHandler) RegisterLoginByMobileNumber(c *gin.Context) {
return
}

// Set the refresh token in a cookie
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
http.SetCookie(c.Writer, &http.Cookie{
Name: constant.RefreshTokenCookieName,
Value: token.RefreshToken,
MaxAge: int(h.config.JWT.RefreshTokenExpireDuration * 60),
Path: "/",
Domain: h.config.Server.Domain,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})


c.JSON(http.StatusCreated, helper.GenerateBaseResponse(token, true, helper.Success))
}

Expand Down Expand Up @@ -137,3 +144,25 @@ func (h *UsersHandler) SendOtp(c *gin.Context) {
// TODO: Call internal SMS service
c.JSON(http.StatusCreated, helper.GenerateBaseResponse(nil, true, helper.Success))
}

// RefreshToken godoc
// @Summary RefreshToken
// @Description RefreshToken
// @Tags Users
// @Accept json
// @Produce json
// @Success 200 {object} helper.BaseHttpResponse "Success"
// @Failure 400 {object} helper.BaseHttpResponse "Failed"
// @Failure 401 {object} helper.BaseHttpResponse "Failed"
// @Router /v1/users/refresh-token [get]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that we are requesting a new token in refresh-token and not retrieving a persistent resource. so it's better to set method POST

Suggested change
// @Router /v1/users/refresh-token [get]
// @Router /v1/users/refresh-token [post]

func (h *UsersHandler) RefreshToken(c *gin.Context) {
token, err := h.tokenUsecase.RefreshToken(c)
if err != nil {
c.AbortWithStatusJSON(helper.TranslateErrorToStatusCode(err),
helper.GenerateBaseResponseWithError(nil, false, helper.InternalError, err))
return
}
// Set the refresh token in a cookie
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as previous changes

Suggested change
c.SetCookie(constant.RefreshTokenCookieName, token.RefreshToken, int(h.config.JWT.RefreshTokenExpireDuration*60), "/", h.config.Server.Domin, true, true)
http.SetCookie(c.Writer, &http.Cookie{
Name: constant.RefreshTokenCookieName,
Value: token.RefreshToken,
MaxAge: int(h.config.JWT.RefreshTokenExpireDuration * 60),
Path: "/",
Domain: h.config.Server.Domain,
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})

c.JSON(http.StatusOK, helper.GenerateBaseResponse(token, true, helper.Success))
}
1 change: 1 addition & 0 deletions src/api/router/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ func User(router *gin.RouterGroup, cfg *config.Config) {
router.POST("/login-by-username", h.LoginByUsername)
router.POST("/register-by-username", h.RegisterByUsername)
router.POST("/login-by-mobile", h.RegisterLoginByMobileNumber)
router.GET("/refresh-token", h.RefreshToken)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based previous comment

Suggested change
router.GET("/refresh-token", h.RefreshToken)
router.POST("/refresh-token", h.RefreshToken)

}
1 change: 1 addition & 0 deletions src/config/config-development.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ server:
internalPort: 5005
externalPort: 5005
runMode: debug
domin: localhost
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
domin: localhost
domain: localhost

logger:
filePath: ../logs/
encoding: json
Expand Down
1 change: 1 addition & 0 deletions src/config/config-docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ server:
internalPort: 5000
externalPort: 0
runMode: release
domin: localhost
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
domin: localhost
domain: localhost

logger:
filePath: /app/logs/
encoding: json
Expand Down
1 change: 1 addition & 0 deletions src/config/config-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ server:
internalPort: 5010
externalPort: 5010
runMode: release
domin: localhost
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
domin: localhost
domain: localhost

logger:
filePath: logs/
encoding: json
Expand Down
11 changes: 6 additions & 5 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ type Config struct {
}

type ServerConfig struct {
InternalPort string
ExternalPort string
RunMode string
InternalPort string
ExternalPort string
RunMode string
Domin string
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Domin string
Domain string

}

type LoggerConfig struct {
Expand Down Expand Up @@ -93,10 +94,10 @@ func GetConfig() *Config {

cfg, err := ParseConfig(v)
envPort := os.Getenv("PORT")
if envPort != ""{
if envPort != "" {
cfg.Server.ExternalPort = envPort
log.Printf("Set external port from environment -> %s", cfg.Server.ExternalPort)
}else{
} else {
cfg.Server.ExternalPort = cfg.Server.InternalPort
log.Printf("Set external port from environment -> %s", cfg.Server.ExternalPort)
}
Expand Down
3 changes: 3 additions & 0 deletions src/constant/constanst.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@ const (
MobileNumberKey string = "MobileNumber"
RolesKey string = "Roles"
ExpireTimeKey string = "Exp"

// JWT
RefreshTokenCookieName string = "refresh_token"
)
35 changes: 35 additions & 0 deletions src/docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4661,6 +4661,41 @@ const docTemplate = `{
}
}
},
"/v1/users/refresh-token": {
"get": {
"description": "RefreshToken",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Users"
],
"summary": "RefreshToken",
"responses": {
"200": {
"description": "Success",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
},
"400": {
"description": "Failed",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
},
"401": {
"description": "Failed",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
}
}
}
},
"/v1/users/register-by-username": {
"post": {
"description": "RegisterByUsername",
Expand Down
35 changes: 35 additions & 0 deletions src/docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -4650,6 +4650,41 @@
}
}
},
"/v1/users/refresh-token": {
"get": {
"description": "RefreshToken",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Users"
],
"summary": "RefreshToken",
"responses": {
"200": {
"description": "Success",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
},
"400": {
"description": "Failed",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
},
"401": {
"description": "Failed",
"schema": {
"$ref": "#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse"
}
}
}
}
},
"/v1/users/register-by-username": {
"post": {
"description": "RegisterByUsername",
Expand Down
23 changes: 23 additions & 0 deletions src/docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3821,6 +3821,29 @@ paths:
summary: LoginByUsername
tags:
- Users
/v1/users/refresh-token:
get:
consumes:
- application/json
description: RefreshToken
produces:
- application/json
responses:
"200":
description: Success
schema:
$ref: '#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse'
"400":
description: Failed
schema:
$ref: '#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse'
"401":
description: Failed
schema:
$ref: '#/definitions/github_com_naeemaei_golang-clean-web-api_api_helper.BaseHttpResponse'
summary: RefreshToken
tags:
- Users
/v1/users/register-by-username:
post:
consumes:
Expand Down
18 changes: 10 additions & 8 deletions src/pkg/service_errors/error_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@ package service_errors

const (
// Token
UnExpectedError = "Expected error"
ClaimsNotFound = "Claims not found"
TokenRequired = "token required"
TokenExpired = "token expired"
TokenInvalid = "token invalid"
UnExpectedError = "Expected error"
ClaimsNotFound = "Claims not found"
TokenRequired = "token required"
TokenExpired = "token expired"
TokenInvalid = "token invalid"
InvalidRefreshToken = "invalid refresh token"

// OTP
OptExists = "Otp exists"
OtpUsed = "Otp used"
OtpNotValid = "Otp invalid"

// User
EmailExists = "Email exists"
UsernameExists = "Username exists"
PermissionDenied = "Permission denied"
EmailExists = "Email exists"
UsernameExists = "Username exists"
PermissionDenied = "Permission denied"
UsernameOrPasswordInvalid = "username or password invalid"
InvalidRolesFormat = "invalid roles format"

// DB
RecordNotFound = "record not found"
Expand Down
49 changes: 49 additions & 0 deletions src/usecase/token_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package usecase
import (
"time"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/naeemaei/golang-clean-web-api/config"
"github.com/naeemaei/golang-clean-web-api/constant"
Expand Down Expand Up @@ -62,6 +63,12 @@ func (u *TokenUsecase) GenerateToken(token tokenDto) (*dto.TokenDetail, error) {
rtc := jwt.MapClaims{}

rtc[constant.UserIdKey] = token.UserId
rtc[constant.FirstNameKey] = token.FirstName
rtc[constant.LastNameKey] = token.LastName
rtc[constant.UsernameKey] = token.Username
rtc[constant.EmailKey] = token.Email
rtc[constant.MobileNumberKey] = token.MobileNumber
rtc[constant.RolesKey] = token.Roles
rtc[constant.ExpireTimeKey] = td.RefreshTokenExpireTime

rt := jwt.NewWithClaims(jwt.SigningMethodHS256, rtc)
Expand Down Expand Up @@ -105,3 +112,45 @@ func (u *TokenUsecase) GetClaims(token string) (claimMap map[string]interface{},
}
return nil, &service_errors.ServiceError{EndUserMessage: service_errors.ClaimsNotFound}
}

func (s *TokenUsecase) RefreshToken(c *gin.Context) (*dto.TokenDetail, error) {
refreshToken, err := c.Cookie(constant.RefreshTokenCookieName)
if err != nil {
return nil, &service_errors.ServiceError{EndUserMessage: service_errors.InvalidRefreshToken}
}

claims, err := s.GetClaims(refreshToken)
if err != nil {
return nil, err
}

// Convert roles to []string
rolesInterface, ok := claims[constant.RolesKey].([]interface{})
if !ok {
return nil, &service_errors.ServiceError{EndUserMessage: service_errors.InvalidRolesFormat}
}

roles := make([]string, len(rolesInterface))
for i, role := range rolesInterface {
roles[i], ok = role.(string)
if !ok {
return nil, &service_errors.ServiceError{EndUserMessage: service_errors.InvalidRolesFormat}
}
}

tokenDto := tokenDto{
UserId: int(claims[constant.UserIdKey].(float64)),
FirstName: claims[constant.FirstNameKey].(string),
LastName: claims[constant.LastNameKey].(string),
Username: claims[constant.UsernameKey].(string),
MobileNumber: claims[constant.MobileNumberKey].(string),
Email: claims[constant.EmailKey].(string),
Roles: roles,
}
newTokenDetail, err := s.GenerateToken(tokenDto)
if err != nil {
return nil, err
}

return newTokenDetail, nil
}