2024-10-26 21:19:11 +02:00
|
|
|
package handler
|
2024-10-25 23:31:57 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/finchrelia/chirpy-server/internal/auth"
|
|
|
|
)
|
|
|
|
|
2024-10-26 21:19:11 +02:00
|
|
|
func (cfg *APIConfig) RefreshToken(w http.ResponseWriter, r *http.Request) {
|
2024-10-25 23:31:57 +02:00
|
|
|
token, err := auth.GetBearerToken(r.Header)
|
|
|
|
if err != nil {
|
2024-10-26 21:19:11 +02:00
|
|
|
log.Printf("Error extracting token: %v", err)
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2024-10-25 23:31:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
dbUser, err := cfg.DB.GetUserFromRefreshToken(r.Context(), token)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error getting user: %v", err)
|
2024-10-26 21:19:11 +02:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2024-10-25 23:31:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
newToken, err := auth.MakeJWT(dbUser, cfg.JWT)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error creating new JWT: %v", err)
|
2024-10-26 21:19:11 +02:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2024-10-25 23:31:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
type tokenResponse struct {
|
|
|
|
AccessToken string `json:"token"`
|
|
|
|
}
|
2024-10-26 21:19:11 +02:00
|
|
|
JsonResponse(w, http.StatusOK, tokenResponse{
|
2024-10-25 23:31:57 +02:00
|
|
|
AccessToken: newToken,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-10-26 21:19:11 +02:00
|
|
|
func (cfg *APIConfig) RevokeToken(w http.ResponseWriter, r *http.Request) {
|
2024-10-25 23:31:57 +02:00
|
|
|
token, err := auth.GetBearerToken(r.Header)
|
|
|
|
if err != nil {
|
2024-10-26 21:19:11 +02:00
|
|
|
log.Printf("Error extracting token: %v", err)
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2024-10-25 23:31:57 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
err = cfg.DB.RevokeRefreshToken(r.Context(), token)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error revoking token in database: %v", err)
|
2024-10-26 21:19:11 +02:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2024-10-25 23:31:57 +02:00
|
|
|
return
|
|
|
|
}
|
2024-10-26 21:19:11 +02:00
|
|
|
w.WriteHeader(http.StatusNoContent)
|
2024-10-25 23:31:57 +02:00
|
|
|
}
|