diff options
author | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2023-10-04 21:33:42 +0530 |
---|---|---|
committer | Vidhu Kant Sharma <vidhukant@vidhukant.com> | 2023-10-04 21:33:42 +0530 |
commit | d8c1d5fedfac65a79490120195e273b5d5fc75e9 (patch) | |
tree | 7b2b4c6042c693cdd4c827ea9989cfc1bd82ca5d /auth/controller.go | |
parent | a0613bfd790b27f313470bddc08371bcbf54968d (diff) |
added basic token refreshingv0.0.10
Diffstat (limited to 'auth/controller.go')
-rw-r--r-- | auth/controller.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/auth/controller.go b/auth/controller.go index 5b18b64..7e3346e 100644 --- a/auth/controller.go +++ b/auth/controller.go @@ -25,6 +25,7 @@ import ( "vidhukant.com/openbills/user" "net/http" "time" + "vidhukant.com/openbills/errors" ) var ( @@ -127,3 +128,55 @@ func handleSignIn (ctx *gin.Context) { "data": u, }) } + +func handleRefresh (ctx *gin.Context) { + var req RefreshReq + ctx.Bind(&req) + + tk, _ := jwt.ParseWithClaims(req.RefreshToken, &AuthClaims{}, func (token *jwt.Token) (interface{}, error) { + return []byte(REFRESH_KEY), nil + }) + + claims, ok := tk.Claims.(*AuthClaims) + if !ok { + ctx.Error(errors.ErrUnauthorized) + ctx.Abort() + return + } + + if !tk.Valid { + eat := claims.ExpiresAt.Unix() + if eat != 0 && eat < time.Now().Unix() { + ctx.Error(errors.ErrSessionExpired) + } else { + ctx.Error(errors.ErrUnauthorized) + } + + ctx.Abort() + return + } + + // TODO: if token is valid, check if user even exists before generating authToken + + authToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, + AuthClaims { + jwt.RegisteredClaims { + IssuedAt: jwt.NewNumericDate(time.Now()), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 2)), + }, + claims.UserID, + }, + ).SignedString(AUTH_KEY) + if err != nil { + // TODO: handle potential errors + ctx.Error(err) + ctx.Abort() + return + } + + ctx.JSON(http.StatusOK, gin.H{ + "auth_token": authToken, + "message": "success", + //"data": u, + }) +} |