Skip to content

Commit

Permalink
Merge pull request #9 from metakgp/rohan/jwt-expiry
Browse files Browse the repository at this point in the history
fix: add expiry to both jwt and cookie using env variable
  • Loading branch information
proffapt committed Jun 17, 2024
2 parents f912fc5 + 9517bdf commit f47245f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
4 changes: 2 additions & 2 deletions .env.template
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
TOTP_SECRET_KEY=
JWT_SECRET_KEY=
OTP_VALIDITY_PERIOD=600
RESEND_OTP_COOLDOWN=60
RESEND_OTP_COOLDOWN=60
JWT_EXPIRY_DAYS=90
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ services:
build: "."
restart: always
environment:
- TOTP_SECRET_KEY=${TOTP_SECRET_KEY}
- JWT_SECRET_KEY=${JWT_SECRET_KEY}
- OTP_VALIDITY_PERIOD=${OTP_VALIDITY_PERIOD}
- RESEND_OTP_COOLDOWN=${RESEND_OTP_COOLDOWN}
Expand Down
17 changes: 14 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func jwtKeyFunc(*jwt.Token) (interface{}, error) {
func generateOtp(user User) (bool, error) {
validPeriod, err := strconv.Atoi(os.Getenv("OTP_VALIDITY_PERIOD"))
if err != nil || validPeriod < 30 { // keep 30s as minimum valid period
fmt.Println("Invalid OTP_VALIDITY_PERIOD env set. Defaulting to 600 seconds (10 minutes)")
validPeriod = 600
}

Expand Down Expand Up @@ -161,6 +162,7 @@ func handleGetOtp(res http.ResponseWriter, req *http.Request) {
if ok {
cooldown, err := strconv.Atoi(os.Getenv("RESEND_OTP_COOLDOWN"))
if err != nil {
fmt.Println("Invalid RESEND_OTP_COOLDOWN env set. Defaulting to 60 seconds (1 minute)")
cooldown = 60 // keep 30s as minimum cooldown
}
cooldownDuration := time.Duration(cooldown) * time.Second
Expand Down Expand Up @@ -254,11 +256,20 @@ func handleVerifyOtp(res http.ResponseWriter, req *http.Request) {
return
}

issue_time := time.Now()
expiryDays, err := strconv.Atoi(os.Getenv("JWT_EXPIRY_DAYS"))
if err != nil || expiryDays < 1 { // keep 1 day as minimum valid period
fmt.Println("Invalid JWT_EXPIRY_DAYS env set. Defaulting to 90 days (3 months)")
expiryDays = 90 // Default to 90 days (3 months)
}

issueTime := time.Now()
expiryTime := issueTime.AddDate(0, 0, expiryDays)

claims := &LoginJwtClaims{
LoginJwtFields: LoginJwtFields{Email: user.Email},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(issue_time),
IssuedAt: jwt.NewNumericDate(issueTime),
ExpiresAt: jwt.NewNumericDate(expiryTime),
},
}

Expand All @@ -273,7 +284,7 @@ func handleVerifyOtp(res http.ResponseWriter, req *http.Request) {
cookie := http.Cookie{
Name: "jwt",
Value: tokenString,
Expires: time.Now().Add(time.Hour * 24 * 30),
Expires: expiryTime,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteNoneMode,
Expand Down

0 comments on commit f47245f

Please sign in to comment.