aboutsummaryrefslogtreecommitdiff
path: root/auth/controller.go
diff options
context:
space:
mode:
authorVidhu Kant Sharma <vidhukant@vidhukant.com>2023-10-04 21:33:42 +0530
committerVidhu Kant Sharma <vidhukant@vidhukant.com>2023-10-04 21:33:42 +0530
commitd8c1d5fedfac65a79490120195e273b5d5fc75e9 (patch)
tree7b2b4c6042c693cdd4c827ea9989cfc1bd82ca5d /auth/controller.go
parenta0613bfd790b27f313470bddc08371bcbf54968d (diff)
added basic token refreshingv0.0.10
Diffstat (limited to 'auth/controller.go')
-rw-r--r--auth/controller.go53
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,
+ })
+}