From d8c1d5fedfac65a79490120195e273b5d5fc75e9 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Wed, 4 Oct 2023 21:33:42 +0530 Subject: added basic token refreshing --- auth/controller.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) (limited to 'auth/controller.go') 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, + }) +} -- cgit v1.2.3