chirpy_server/internal/handler/token.go

53 lines
1.3 KiB
Go
Raw Permalink Normal View History

package handler
2024-10-25 23:31:57 +02:00
import (
"log"
"net/http"
"github.com/finchrelia/chirpy-server/internal/auth"
)
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 {
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)
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)
w.WriteHeader(http.StatusInternalServerError)
2024-10-25 23:31:57 +02:00
return
}
type tokenResponse struct {
AccessToken string `json:"token"`
}
JsonResponse(w, http.StatusOK, tokenResponse{
2024-10-25 23:31:57 +02:00
AccessToken: newToken,
})
}
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 {
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)
w.WriteHeader(http.StatusInternalServerError)
2024-10-25 23:31:57 +02:00
return
}
w.WriteHeader(http.StatusNoContent)
2024-10-25 23:31:57 +02:00
}