2026-08-05 06:59:14 -05:00
|
|
|
package main
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
import (
|
|
|
|
|
"context"
|
2026-08-06 19:31:58 -05:00
|
|
|
"database/sql"
|
2026-08-05 10:13:23 -05:00
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log"
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
"os/signal"
|
|
|
|
|
"slices"
|
|
|
|
|
"strings"
|
|
|
|
|
"sync/atomic"
|
|
|
|
|
"syscall"
|
|
|
|
|
"time"
|
2026-08-06 19:31:58 -05:00
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
"github.com/StevanFreeborn/chirpy/internal/auth"
|
2026-08-06 19:31:58 -05:00
|
|
|
"github.com/StevanFreeborn/chirpy/internal/database"
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"github.com/joho/godotenv"
|
|
|
|
|
_ "github.com/lib/pq"
|
2026-08-05 10:13:23 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type server struct {
|
|
|
|
|
fileServerHits atomic.Int32
|
2026-08-06 19:31:58 -05:00
|
|
|
database *database.Queries
|
|
|
|
|
platform string
|
2026-08-15 10:48:29 -05:00
|
|
|
jwtSecret []byte
|
2026-08-05 10:13:23 -05:00
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
func writeJsonResponse(w http.ResponseWriter, statusCode int, response any) {
|
|
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
|
w.Header().Add("Content-Type", "application/json")
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
encoder := json.NewEncoder(w)
|
|
|
|
|
|
|
|
|
|
if err := encoder.Encode(response); err != nil {
|
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
func decodeJsonRequest[T any](r *http.Request) (*T, error) {
|
|
|
|
|
defer r.Body.Close()
|
|
|
|
|
var data *T
|
|
|
|
|
decoder := json.NewDecoder(r.Body)
|
|
|
|
|
err := decoder.Decode(&data)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, apiError{
|
|
|
|
|
Err: "Failed to deserialize request",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
func (s *server) HandleFiles(prefix string) http.Handler {
|
|
|
|
|
fileServer := http.StripPrefix(prefix, http.FileServer(http.Dir(".")))
|
|
|
|
|
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
s.fileServerHits.Add(1)
|
|
|
|
|
fileServer.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleHealthChecks(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
w.Write([]byte("OK"))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleReset(w http.ResponseWriter, r *http.Request) {
|
2026-08-06 19:31:58 -05:00
|
|
|
if s.platform != "dev" {
|
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
s.fileServerHits.Store(0)
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
s.database.DeleteAllUsers(r.Context())
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
w.Write([]byte("OK"))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleMetrics(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
hits := s.fileServerHits.Load()
|
|
|
|
|
|
|
|
|
|
w.Header().Add("Content-Type", "text/html; charset=utf-8")
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
|
|
|
|
|
template := `
|
|
|
|
|
<html>
|
|
|
|
|
<body>
|
|
|
|
|
<h1>Welcome, Chirpy Admin</h1>
|
|
|
|
|
<p>Chirpy has been visited %d times!</p>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|
|
|
|
|
`
|
|
|
|
|
|
|
|
|
|
fmt.Fprintf(w, template, hits)
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
type apiError struct {
|
|
|
|
|
Err string `json:"error"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
func (e apiError) Error() string {
|
|
|
|
|
return e.Err
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
type createChirpRequest struct {
|
|
|
|
|
Body string `json:"body"`
|
|
|
|
|
UserId string `json:"user_id"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
type chirpResponse struct {
|
2026-08-06 19:31:58 -05:00
|
|
|
Id string `json:"id"`
|
|
|
|
|
CreatedAt string `json:"created_at"`
|
|
|
|
|
UpdatedAt string `json:"updated_at"`
|
|
|
|
|
Body string `json:"body"`
|
|
|
|
|
UserId string `json:"user_id"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleCreateChirp(w http.ResponseWriter, r *http.Request) {
|
2026-08-05 10:13:23 -05:00
|
|
|
blacklist := []string{
|
|
|
|
|
"kerfuffle",
|
|
|
|
|
"sharbert",
|
|
|
|
|
"fornax",
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
bearerToken, err := auth.GetBearerToken(r.Header)
|
2026-08-05 10:13:23 -05:00
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
unauthorizedError := apiError{
|
|
|
|
|
Err: "You are not authorized to perform this action",
|
|
|
|
|
}
|
2026-08-05 10:13:23 -05:00
|
|
|
|
|
|
|
|
if err != nil {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
requestUserId, err := auth.ValidateJWT(bearerToken, s.jwtSecret)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createChirpRequest, err := decodeJsonRequest[createChirpRequest](r)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, err)
|
2026-08-05 10:13:23 -05:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
if len(createChirpRequest.Body) > 140 {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusBadRequest, apiError{
|
2026-08-05 10:13:23 -05:00
|
|
|
Err: "Chirp is too long",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
words := strings.Split(createChirpRequest.Body, " ")
|
2026-08-05 10:13:23 -05:00
|
|
|
sanitized := []string{}
|
|
|
|
|
|
|
|
|
|
for _, word := range words {
|
|
|
|
|
if slices.Contains(blacklist, strings.ToLower(word)) {
|
|
|
|
|
sanitized = append(sanitized, "****")
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sanitized = append(sanitized, word)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cleanedBody := strings.Join(sanitized, " ")
|
|
|
|
|
|
2026-08-06 19:31:58 -05:00
|
|
|
createChirpParams := database.CreateChirpParams{
|
|
|
|
|
Body: cleanedBody,
|
2026-08-15 10:48:29 -05:00
|
|
|
UserID: requestUserId,
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createdChirp, err := s.database.CreateChirp(r.Context(), createChirpParams)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, apiError{
|
2026-08-06 19:31:58 -05:00
|
|
|
Err: "Failed to create chirp. 🤷🏻♂️",
|
|
|
|
|
})
|
2026-08-15 10:48:29 -05:00
|
|
|
return
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusCreated, chirpResponse{
|
2026-08-06 19:31:58 -05:00
|
|
|
Id: createdChirp.ID.String(),
|
|
|
|
|
CreatedAt: createdChirp.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: createdChirp.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Body: createdChirp.Body,
|
|
|
|
|
UserId: createdChirp.UserID.String(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type createUserRequest struct {
|
2026-08-15 10:48:29 -05:00
|
|
|
Email string `json:"email"`
|
|
|
|
|
Password string `json:"password"`
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type createUserResponse struct {
|
|
|
|
|
Id string `json:"id"`
|
|
|
|
|
CreatedAt string `json:"created_at"`
|
|
|
|
|
UpdatedAt string `json:"updated_at"`
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
|
2026-08-15 10:48:29 -05:00
|
|
|
createUserRequest, err := decodeJsonRequest[createUserRequest](r)
|
2026-08-06 19:31:58 -05:00
|
|
|
|
|
|
|
|
if err != nil {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusBadRequest, err)
|
|
|
|
|
return
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
trimmedEmail := strings.TrimSpace(createUserRequest.Email)
|
|
|
|
|
|
|
|
|
|
if strings.TrimSpace(trimmedEmail) == "" {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusBadRequest, apiError{
|
2026-08-06 19:31:58 -05:00
|
|
|
Err: "email is required. must be valid email address.",
|
|
|
|
|
})
|
2026-08-15 10:48:29 -05:00
|
|
|
return
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
trimmedPassword := strings.TrimSpace(createUserRequest.Password)
|
|
|
|
|
|
|
|
|
|
if strings.TrimSpace(trimmedEmail) == "" {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, apiError{
|
|
|
|
|
Err: "password is required. must be non-empty string.",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hashed_password, err := auth.HashPassword(trimmedPassword)
|
|
|
|
|
|
|
|
|
|
createUserError := apiError{
|
|
|
|
|
Err: "Uh oh we were unable to create a new user",
|
|
|
|
|
}
|
2026-08-06 19:31:58 -05:00
|
|
|
|
|
|
|
|
if err != nil {
|
2026-08-15 10:48:29 -05:00
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, createUserError)
|
|
|
|
|
return
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
createUserParams := database.CreateUserParams{
|
|
|
|
|
Email: trimmedEmail,
|
|
|
|
|
HashedPassword: hashed_password,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createdUser, err := s.database.CreateUser(r.Context(), createUserParams)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, createUserError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusCreated, createUserResponse{
|
2026-08-06 19:31:58 -05:00
|
|
|
Id: createdUser.ID.String(),
|
|
|
|
|
CreatedAt: createdUser.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: createdUser.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Email: createdUser.Email,
|
|
|
|
|
})
|
2026-08-05 10:13:23 -05:00
|
|
|
}
|
2026-08-05 06:59:14 -05:00
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
func (s *server) HandleGetAllChirps(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
existingChirps, err := s.database.GetAllChirps(r.Context())
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, apiError{
|
|
|
|
|
Err: "Unable to retrieve chirps",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
chirps := []chirpResponse{}
|
|
|
|
|
|
|
|
|
|
for _, c := range existingChirps {
|
|
|
|
|
chirps = append(chirps, chirpResponse{
|
|
|
|
|
Id: c.ID.String(),
|
|
|
|
|
CreatedAt: c.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: c.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Body: c.Body,
|
|
|
|
|
UserId: c.UserID.String(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusOK, chirps)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleGetChirp(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
chirpId := r.PathValue("id")
|
|
|
|
|
validChirpId, err := uuid.Parse(chirpId)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, apiError{
|
|
|
|
|
Err: "Chirp id is not valid. id must be valid UUID.",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existingChirp, err := s.database.GetChirpById(r.Context(), validChirpId)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusNotFound, apiError{
|
|
|
|
|
Err: "No chirp with given id found.",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusOK, chirpResponse{
|
|
|
|
|
Id: existingChirp.ID.String(),
|
|
|
|
|
CreatedAt: existingChirp.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: existingChirp.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Body: existingChirp.Body,
|
|
|
|
|
UserId: existingChirp.UserID.String(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type loginRequest struct {
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
Password string `json:"password"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *loginRequest) Validate() error {
|
|
|
|
|
if strings.TrimSpace(r.Email) == "" || strings.TrimSpace(r.Password) == "" {
|
|
|
|
|
return apiError{
|
|
|
|
|
Err: "Email and password must be non-empty string",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type loginResponse struct {
|
|
|
|
|
Id string `json:"id"`
|
|
|
|
|
CreatedAt string `json:"created_at"`
|
|
|
|
|
UpdatedAt string `json:"updated_at"`
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
Token string `json:"token"`
|
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleLogin(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
loginRequest, err := decodeJsonRequest[loginRequest](r)
|
|
|
|
|
|
|
|
|
|
err = loginRequest.Validate()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existingUser, err := s.database.GetUserByEmail(r.Context(), loginRequest.Email)
|
|
|
|
|
|
|
|
|
|
invalidLoginError := apiError{
|
|
|
|
|
Err: "Invalid login request",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, invalidLoginError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isCorrectPassword, err := auth.CheckPasswordHash(loginRequest.Password, existingUser.HashedPassword)
|
|
|
|
|
|
|
|
|
|
if err != nil || isCorrectPassword == false {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, invalidLoginError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
SECONDS_PER_HOUR := 3600
|
|
|
|
|
expiresInDuration := time.Duration(SECONDS_PER_HOUR) * time.Second
|
|
|
|
|
|
|
|
|
|
accessToken, err := auth.MakeJWT(existingUser.ID, s.jwtSecret, expiresInDuration)
|
|
|
|
|
|
|
|
|
|
loginFailedError := apiError{
|
|
|
|
|
Err: "Login failed",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, loginFailedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createRefreshTokenParams := database.CreateRefreshTokenParams{
|
|
|
|
|
Token: auth.MakeRefreshToken(),
|
|
|
|
|
ExpiresAt: time.Now().Add(60 * 24 * time.Hour),
|
|
|
|
|
RevokedAt: sql.NullTime{
|
|
|
|
|
Valid: false,
|
|
|
|
|
},
|
|
|
|
|
UserID: existingUser.ID,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createdRefreshToken, err := s.database.CreateRefreshToken(r.Context(), createRefreshTokenParams)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, loginFailedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusOK, loginResponse{
|
|
|
|
|
Id: existingUser.ID.String(),
|
|
|
|
|
CreatedAt: existingUser.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: existingUser.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Email: existingUser.Email,
|
|
|
|
|
Token: accessToken,
|
|
|
|
|
RefreshToken: createdRefreshToken.Token,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type refreshTokenResponse struct {
|
|
|
|
|
Token string `json:"token"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
refreshToken, err := auth.GetBearerToken(r.Header)
|
|
|
|
|
|
|
|
|
|
unauthorizedError := apiError{
|
|
|
|
|
Err: "Unable to refresh token",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existingRefreshToken, err := s.database.GetRefreshTokenByToken(r.Context(), refreshToken)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if existingRefreshToken.ExpiresAt.Before(time.Now()) || existingRefreshToken.RevokedAt.Valid {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
SECONDS_PER_HOUR := 3600
|
|
|
|
|
expiresInDuration := time.Duration(SECONDS_PER_HOUR) * time.Second
|
|
|
|
|
|
|
|
|
|
accessToken, err := auth.MakeJWT(existingRefreshToken.UserID, s.jwtSecret, expiresInDuration)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, apiError{
|
|
|
|
|
Err: "Failed to refresh token",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TODO: We should rotate the refresh token
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusOK, refreshTokenResponse{
|
|
|
|
|
Token: accessToken,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleRevoke(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
refreshToken, err := auth.GetBearerToken(r.Header)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, apiError{
|
|
|
|
|
Err: "No refresh token present in request",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existingRefreshToken, err := s.database.GetRefreshTokenByToken(r.Context(), refreshToken)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusNotFound, apiError{
|
|
|
|
|
Err: "Unable to revoke token",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = s.database.RevokeRefreshToken(r.Context(), existingRefreshToken.Token)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, apiError{
|
|
|
|
|
Err: "Unable to revoke token",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusNoContent, nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type updateUserRequest struct {
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
Password string `json:"password"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type updateUserResponse struct {
|
|
|
|
|
Id string `json:"id"`
|
|
|
|
|
CreatedAt string `json:"created_at"`
|
|
|
|
|
UpdatedAt string `json:"updated_at"`
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *updateUserRequest) Validate() error {
|
|
|
|
|
if strings.TrimSpace(r.Email) == "" || strings.TrimSpace(r.Password) == "" {
|
|
|
|
|
return apiError{
|
|
|
|
|
Err: "Email and password must be non-empty string",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
accessToken, err := auth.GetBearerToken(r.Header)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, apiError{
|
|
|
|
|
Err: "You are not authorized to perform this action",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
requestUserId, err := auth.ValidateJWT(accessToken, s.jwtSecret)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, apiError{
|
|
|
|
|
Err: "You are not authorized to perform this action",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updateUserRequest, err := decodeJsonRequest[updateUserRequest](r)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = updateUserRequest.Validate()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updatedHashedPassword, err := auth.HashPassword(updateUserRequest.Password)
|
|
|
|
|
|
|
|
|
|
updateError := apiError{
|
|
|
|
|
Err: "Unable to perform update",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, updateError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updateUserParams := database.UpdateUserParams{
|
|
|
|
|
ID: requestUserId,
|
|
|
|
|
Email: updateUserRequest.Email,
|
|
|
|
|
HashedPassword: updatedHashedPassword,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updatedUser, err := s.database.UpdateUser(r.Context(), updateUserParams)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, updateError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusOK, updateUserResponse{
|
|
|
|
|
Id: updatedUser.ID.String(),
|
|
|
|
|
CreatedAt: updatedUser.CreatedAt.Format(time.RFC3339),
|
|
|
|
|
UpdatedAt: updatedUser.UpdatedAt.Format(time.RFC3339),
|
|
|
|
|
Email: updatedUser.Email,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *server) HandleDeleteChirp(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
accessToken, err := auth.GetBearerToken(r.Header)
|
|
|
|
|
|
|
|
|
|
unauthorizedError := apiError{
|
|
|
|
|
Err: "You are not authorized to perform this action",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
requestUserId, err := auth.ValidateJWT(accessToken, s.jwtSecret)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusUnauthorized, unauthorizedError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
chirpId := r.PathValue("id")
|
|
|
|
|
validChirpId, err := uuid.Parse(chirpId)
|
|
|
|
|
|
|
|
|
|
invalidChirpIdError := apiError{
|
|
|
|
|
Err: "Chirp id must be a valid uuid for an existing chirp",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusBadRequest, invalidChirpIdError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
existingChirp, err := s.database.GetChirpById(r.Context(), validChirpId)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusNotFound, invalidChirpIdError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if existingChirp.UserID != requestUserId {
|
|
|
|
|
writeJsonResponse(w, http.StatusForbidden, apiError{
|
|
|
|
|
Err: "You can not delete a chirp that does not belong to you",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = s.database.DeleteChirpById(r.Context(), existingChirp.ID)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJsonResponse(w, http.StatusInternalServerError, apiError{
|
|
|
|
|
Err: "Yo bro we couldn't delete that shit",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJsonResponse(w, http.StatusNoContent, nil)
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-05 06:59:14 -05:00
|
|
|
func main() {
|
2026-08-06 19:31:58 -05:00
|
|
|
err := godotenv.Load()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatalf("Failed to load environment variables")
|
|
|
|
|
os.Exit(1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dbURL := os.Getenv("DB_URL")
|
|
|
|
|
platform := os.Getenv("PLATFORM")
|
2026-08-15 10:48:29 -05:00
|
|
|
jwtSecret := os.Getenv("JWT_SECRET")
|
|
|
|
|
|
|
|
|
|
if strings.TrimSpace(jwtSecret) == "" {
|
|
|
|
|
log.Fatalf("Failed to retrieve JWT_SECRET")
|
|
|
|
|
os.Exit(1)
|
|
|
|
|
}
|
2026-08-06 19:31:58 -05:00
|
|
|
|
|
|
|
|
db, err := sql.Open("postgres", dbURL)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Fatalf("Failed to connect to database: %v", err)
|
|
|
|
|
os.Exit(1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
server := &server{
|
2026-08-15 10:48:29 -05:00
|
|
|
database: database.New(db),
|
|
|
|
|
platform: platform,
|
|
|
|
|
jwtSecret: []byte(jwtSecret),
|
2026-08-06 19:31:58 -05:00
|
|
|
}
|
|
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
|
|
|
|
|
appRoot := "/app/"
|
|
|
|
|
|
|
|
|
|
mux.Handle(appRoot, server.HandleFiles(appRoot))
|
|
|
|
|
mux.HandleFunc("GET /admin/metrics", server.HandleMetrics)
|
|
|
|
|
mux.HandleFunc("POST /admin/reset", server.HandleReset)
|
|
|
|
|
|
|
|
|
|
mux.HandleFunc("GET /api/healthz", server.HandleHealthChecks)
|
|
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
mux.HandleFunc("POST /api/login", server.HandleLogin)
|
|
|
|
|
mux.HandleFunc("POST /api/refresh", server.HandleRefresh)
|
|
|
|
|
mux.HandleFunc("POST /api/revoke", server.HandleRevoke)
|
2026-08-06 19:31:58 -05:00
|
|
|
mux.HandleFunc("POST /api/users", server.HandleCreateUser)
|
2026-08-15 10:48:29 -05:00
|
|
|
mux.HandleFunc("PUT /api/users", server.HandleUpdateUser)
|
2026-08-06 19:31:58 -05:00
|
|
|
|
2026-08-15 10:48:29 -05:00
|
|
|
mux.HandleFunc("GET /api/chirps", server.HandleGetAllChirps)
|
|
|
|
|
mux.HandleFunc("GET /api/chirps/{id}", server.HandleGetChirp)
|
2026-08-06 19:31:58 -05:00
|
|
|
mux.HandleFunc("POST /api/chirps", server.HandleCreateChirp)
|
2026-08-15 10:48:29 -05:00
|
|
|
mux.HandleFunc("DELETE /api/chirps/{id}", server.HandleDeleteChirp)
|
2026-08-06 19:31:58 -05:00
|
|
|
|
2026-08-05 10:13:23 -05:00
|
|
|
port := ":8080"
|
|
|
|
|
|
|
|
|
|
httpServer := http.Server{
|
|
|
|
|
Handler: mux,
|
|
|
|
|
Addr: port,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
log.Printf("Server started and listening on %s\n", port)
|
|
|
|
|
|
|
|
|
|
err := httpServer.ListenAndServe()
|
|
|
|
|
|
|
|
|
|
if !errors.Is(err, http.ErrServerClosed) {
|
|
|
|
|
log.Fatalf("HTTP Server error: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
log.Println("Stopped serving new connections")
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
sigChan := make(chan os.Signal, 1)
|
|
|
|
|
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
|
<-sigChan
|
|
|
|
|
|
|
|
|
|
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
|
|
|
|
|
|
defer shutdownRelease()
|
|
|
|
|
|
|
|
|
|
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
|
|
|
|
log.Fatalf("HTTP shutdown error: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
log.Println("Graceful shutdown complete")
|
2026-08-05 06:59:14 -05:00
|
|
|
}
|