feat: Added last chapter and refactored whole project

This commit is contained in:
2024-10-26 21:19:11 +02:00
parent 8b7fdf59b5
commit 72581d912e
25 changed files with 501 additions and 495 deletions

213
internal/handler/chirp.go Normal file
View File

@ -0,0 +1,213 @@
package handler
import (
"database/sql"
"encoding/json"
"errors"
"log"
"net/http"
"sort"
"strings"
"time"
"github.com/finchrelia/chirpy-server/internal/auth"
"github.com/finchrelia/chirpy-server/internal/database"
"github.com/google/uuid"
)
type Chirp struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UserID uuid.UUID `json:"user_id"`
Body string `json:"body"`
}
func (cfg *APIConfig) ChirpsCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Content string `json:"body"`
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Error extracting token: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
userId, err := auth.ValidateJWT(token, cfg.JWT)
if err != nil {
log.Printf("Invalid JWT: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(&params)
if err != nil {
log.Printf("Error decoding parameters: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
cleanedChirp, err := cleanChirp(params.Content)
if err != nil {
type errorResponse struct {
Error error `json:"error"`
}
JsonResponse(w, http.StatusBadRequest, errorResponse{Error: err})
}
chirp, err := cfg.DB.CreateChirp(r.Context(), database.CreateChirpParams{
Body: cleanedChirp,
UserID: userId,
})
if err != nil {
log.Printf("Error creating chirp: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
JsonResponse(w, http.StatusCreated, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
})
}
func cleanChirp(s string) (string, error) {
const maxChirpLength = 140
if len(s) > maxChirpLength {
return "", errors.New("Chirp is too long")
}
splittedString := strings.Split(s, " ")
for idx, element := range splittedString {
switch strings.ToLower(element) {
case
"kerfuffle",
"sharbert",
"fornax":
splittedString[idx] = "****"
}
}
return strings.Join(splittedString, " "), nil
}
func (cfg *APIConfig) GetChirps(w http.ResponseWriter, r *http.Request) {
dbChirps := []database.Chirp{}
authorIdString := r.URL.Query().Get("author_id")
if authorIdString != "" {
authorId, err := uuid.Parse(authorIdString)
if err != nil {
log.Printf("Incorrect author ID: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
dbChirps, err = cfg.DB.GetChirpsByUserid(r.Context(), authorId)
if err != nil {
log.Printf("No chirp for user given: %v", err)
}
} else {
var err error
dbChirps, err = cfg.DB.GetChirps(r.Context())
if err != nil {
log.Printf("Error getting chirps: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
chirps := []Chirp{}
for _, chirp := range dbChirps {
chirps = append(chirps, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
})
}
sortOrder := r.URL.Query().Get("sort")
sort.Slice(chirps, func(i, j int) bool {
if sortOrder == "desc" {
return chirps[i].CreatedAt.After(chirps[j].CreatedAt)
}
// Defaults to asc
return chirps[i].CreatedAt.Before(chirps[j].CreatedAt)
})
JsonResponse(w, http.StatusOK, chirps)
}
func (cfg *APIConfig) GetChirp(w http.ResponseWriter, r *http.Request) {
idFromQuery := r.PathValue("chirpID")
id, err := uuid.Parse(idFromQuery)
if err != nil {
log.Printf("Not a valid ID: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
chirp, err := cfg.DB.GetChirp(r.Context(), id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
w.WriteHeader(http.StatusNotFound)
return
}
log.Printf("Error getting chirp: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
JsonResponse(w, http.StatusOK, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
})
}
func (cfg *APIConfig) DeleteChirp(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Error extracting token: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
userId, err := auth.ValidateJWT(token, cfg.JWT)
if err != nil {
log.Printf("Invalid JWT: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
idFromQuery := r.PathValue("chirpID")
id, err := uuid.Parse(idFromQuery)
if err != nil {
log.Printf("Not a valid ID: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
chirp, err := cfg.DB.GetChirp(r.Context(), id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
w.WriteHeader(http.StatusNotFound)
return
}
log.Printf("Error getting chirp: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if chirp.UserID != userId {
log.Printf("User %s not allowed to delete chirp owned by %s", userId, chirp.UserID)
w.WriteHeader(http.StatusForbidden)
return
}
err = cfg.DB.DeleteChirp(r.Context(), database.DeleteChirpParams{
ID: id,
UserID: userId,
})
if err != nil {
log.Printf("Error deleting chirp: %v", err)
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@ -0,0 +1,15 @@
package handler
import (
"sync/atomic"
"github.com/finchrelia/chirpy-server/internal/database"
)
type APIConfig struct {
FileserverHits atomic.Int32
DB *database.Queries
Platform string
JWT string
PolkaKey string
}

84
internal/handler/login.go Normal file
View File

@ -0,0 +1,84 @@
package handler
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"time"
"github.com/finchrelia/chirpy-server/internal/auth"
"github.com/finchrelia/chirpy-server/internal/database"
"github.com/google/uuid"
)
func (cfg *APIConfig) Login(w http.ResponseWriter, r *http.Request) {
type params struct {
Email string `json:"email"`
Password string `json:"password"`
}
decoder := json.NewDecoder(r.Body)
p := params{}
err := decoder.Decode(&p)
if err != nil {
log.Printf("Incorrect email or password")
w.WriteHeader(http.StatusUnauthorized)
return
}
loggedUser, err := cfg.DB.GetUserByEmail(r.Context(), p.Email)
if err != nil {
log.Printf("Error retrieving user: %v", err)
}
err = auth.CheckPasswordHash(p.Password, loggedUser.HashedPassword)
if err != nil {
log.Printf("Incorrect email or password")
w.WriteHeader(http.StatusUnauthorized)
return
}
newJwt, err := auth.MakeJWT(loggedUser.ID, cfg.JWT)
if err != nil {
log.Printf("Error creating JWT: %v", newJwt)
w.WriteHeader(http.StatusInternalServerError)
return
}
newRefreshToken, err := auth.MakeRefreshToken()
if err != nil {
log.Printf("Error creating refresh token: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
refreshTokenParams := database.CreateRefreshTokenParams{
Token: newRefreshToken,
UserID: loggedUser.ID,
ExpiresAt: sql.NullTime{Time: time.Now().AddDate(0, 0, 60), Valid: true},
}
_, err = cfg.DB.CreateRefreshToken(r.Context(), refreshTokenParams)
if err != nil {
log.Printf("Error adding refresh token to db: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
type loginResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
AccessToken string `json:"token"`
RefreshToken string `json:"refresh_token"`
ChirpyRed bool `json:"is_chirpy_red"`
}
JsonResponse(w, http.StatusOK, loginResponse{
ID: loggedUser.ID,
CreatedAt: loggedUser.CreatedAt,
UpdatedAt: loggedUser.UpdatedAt,
Email: loggedUser.Email,
AccessToken: newJwt,
RefreshToken: newRefreshToken,
ChirpyRed: loggedUser.IsChirpyRed,
})
}

View File

@ -0,0 +1,27 @@
package handler
import (
"fmt"
"net/http"
)
func (cfg *APIConfig) MiddlewareMetricsInc(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg.FileserverHits.Add(1)
next.ServeHTTP(w, r)
})
}
func (cfg *APIConfig) Metrics(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
hits := cfg.FileserverHits.Load()
template := `
<html>
<body>
<h1>Welcome, Chirpy Admin</h1>
<p>Chirpy has been visited %d times!</p>
</body>
</html>`
w.Write([]byte(fmt.Sprintf(template, hits)))
}

View File

@ -0,0 +1,9 @@
package handler
import "net/http"
func Readiness(w http.ResponseWriter, req *http.Request) {
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}

22
internal/handler/reset.go Normal file
View File

@ -0,0 +1,22 @@
package handler
import (
"log"
"net/http"
)
func (cfg *APIConfig) Reset(w http.ResponseWriter, r *http.Request) {
cfg.FileserverHits.Store(0)
if cfg.Platform != "dev" {
log.Printf("Invalid %s platform !", cfg.Platform)
w.WriteHeader(http.StatusForbidden)
return
}
_, err := cfg.DB.DeleteUser(r.Context())
if err != nil {
log.Printf("Error deleting users: %v", err)
w.WriteHeader(http.StatusBadRequest)
}
w.WriteHeader(http.StatusOK)
}

View File

@ -0,0 +1,19 @@
package handler
import (
"encoding/json"
"log"
"net/http"
)
func JsonResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(payload)
if err != nil {
log.Printf("Error marshalling JSON: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(statusCode)
w.Write(data)
}

52
internal/handler/token.go Normal file
View File

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

156
internal/handler/users.go Normal file
View File

@ -0,0 +1,156 @@
package handler
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/finchrelia/chirpy-server/internal/auth"
"github.com/finchrelia/chirpy-server/internal/database"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
HashedPassword string `json:"-"`
ChirpyRed bool `json:"is_chirpy_red"`
}
func (cfg *APIConfig) CreateUsers(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(&params)
if err != nil {
log.Printf("Error decoding parameters: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
log.Printf("Error hashing password: %v", err)
}
newDBUser, err := cfg.DB.CreateUser(r.Context(), database.CreateUserParams{
Email: params.Email,
HashedPassword: hashedPassword,
})
if err != nil {
log.Printf("Error creating user %s: %v", params.Email, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
newId := newDBUser.ID
JsonResponse(w, http.StatusCreated, User{
ID: newId,
CreatedAt: newDBUser.CreatedAt,
UpdatedAt: newDBUser.UpdatedAt,
Email: newDBUser.Email,
ChirpyRed: newDBUser.IsChirpyRed,
})
}
func (cfg *APIConfig) UpdateUsers(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Error extracting token: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
userId, err := auth.ValidateJWT(token, cfg.JWT)
if err != nil {
log.Printf("Invalid JWT: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(&params)
if err != nil {
log.Printf("Error decoding parameters: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
log.Printf("Error hashing password: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
credentialsQueryParams := database.UpdateUserCredentialsParams{
ID: userId,
Email: params.Email,
HashedPassword: hashedPassword,
}
updatedCredentials, err := cfg.DB.UpdateUserCredentials(r.Context(), credentialsQueryParams)
if err != nil {
log.Printf("Error updating user credentials: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
JsonResponse(w, http.StatusOK, User{
ID: userId,
CreatedAt: updatedCredentials.CreatedAt,
UpdatedAt: updatedCredentials.UpdatedAt,
Email: updatedCredentials.Email,
ChirpyRed: updatedCredentials.IsChirpyRed,
})
}
func (cfg *APIConfig) SubscribeUser(w http.ResponseWriter, r *http.Request) {
_, err := auth.GetAPIKey(r.Header)
if err != nil {
log.Printf("Error extracting apiKey: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
type parameters struct {
Event string `json:"event"`
Data map[string]string `json:"data"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(&params)
if err != nil {
log.Printf("Error decoding parameters: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
defer r.Body.Close()
if params.Event != "user.upgraded" {
w.WriteHeader(http.StatusNoContent)
return
}
paramsUserIdString := params.Data["user_id"]
paramsUserId, err := uuid.Parse(paramsUserIdString)
if err != nil {
log.Printf("Specified user_id is not a valid UUID: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
err = cfg.DB.UpgradeUser(r.Context(), paramsUserId)
if err != nil {
log.Printf("No user matches user_id given: %v", err)
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
}