diff options
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, + }) +} |