Skip to content

Commit

Permalink
Added Renew Workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
Ju-Wiluis William Rodriguez Hernandez committed Jun 2, 2024
1 parent f9b4e8d commit 8d31b07
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,9 @@

# Go workspace file
go.work

# Conf Folder
conf

# Environment files
*.env
28 changes: 28 additions & 0 deletions handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,34 @@ func ValidateHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(response)
}

func RenewHandler(w http.ResponseWriter, r *http.Request) {
// Read token from Authorization header
token := extractToken(r.Header.Get("Authorization"))
if token == "" {
writeJsonError(w, "Token not provided", http.StatusBadRequest)
return
}

// Validate token against Redis
userId, err := redis.ValidateToken(token)
if err != nil {
println("Error validating token: ", err.Error())
writeJsonError(w, "Invalid token", http.StatusUnauthorized)
return
}

token, err = redis.RenewToken(token, userId)
if err != nil {
println("Error renewing token: ", err.Error())
writeJsonError(w, "Invalid token", http.StatusConflict)
return
}

// Respond with username
response := map[string]string{"token": token}
json.NewEncoder(w).Encode(response)
}

func extractToken(authHeader string) string {
if authHeader == "" {
return authHeader
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func main() {
r.HandleFunc("/login", handlers.LoginHandler).Methods("POST")
r.HandleFunc("/register", handlers.RegisterHandler).Methods("POST")
r.HandleFunc("/validate", handlers.ValidateHandler).Methods("GET")
r.HandleFunc("/renew", handlers.RenewHandler).Methods("GET")

port := os.Getenv("SERVER_PORT")
if port == "" {
Expand Down
6 changes: 6 additions & 0 deletions redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ func GenerateToken(userId string) (string, error) {
return token, nil
}

func RenewToken(token string, userId string) (string, error) {
GetInstance().Del(context.Background(), fmt.Sprintf("auth_token:%s", token))
GetInstance().Del(context.Background(), fmt.Sprintf("auth_user:%s", userId))
return GenerateToken(userId)
}

func ValidateToken(token string) (string, error) {
val, err := GetInstance().Get(context.Background(), fmt.Sprintf("auth_token:%s", token)).Result()
if err == redis.Nil {
Expand Down

0 comments on commit 8d31b07

Please sign in to comment.