webhooks and chirps by user id

This commit is contained in:
2025-03-13 22:47:03 +02:00
parent bad1d140ee
commit 66be0a2b40
13 changed files with 195 additions and 24 deletions

View File

@@ -96,3 +96,12 @@ func MakeRefreshToken() (string, error) {
token := hex.EncodeToString(key)
return token, nil
}
func GetAPIKey(headers http.Header) (string, error) {
auth := headers.Get("Authorization")
auth = strings.TrimPrefix(auth, "ApiKey ")
if auth == "" {
return "", errors.New("missing Authorization header")
}
return auth, nil
}

View File

@@ -14,10 +14,11 @@ type Chirp struct {
}
type User struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
type UserWithToken struct {
@@ -27,4 +28,5 @@ type UserWithToken struct {
Email string `json:"email"`
Token string `json:"token"`
RefreshToken string `json:"refresh_token"`
IsChirpyRed bool `json:"is_chirpy_red"`
}

View File

@@ -12,7 +12,7 @@ import (
const createUser = `-- name: CreateUser :one
INSERT INTO users (id, created_at, updated_at, email, hashed_password)
VALUES (gen_random_uuid(), NOW(), NOW(), $1, $2)
RETURNING id, created_at, updated_at, email, hashed_password
RETURNING id, created_at, updated_at, email, hashed_password, is_chirpy_red
`
type CreateUserParams struct {
@@ -29,6 +29,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
&i.IsChirpyRed,
)
return i, err
}

View File

@@ -0,0 +1,45 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: GetChirpsByUserID.sql
package database
import (
"context"
"github.com/google/uuid"
)
const getChirpsByUserID = `-- name: GetChirpsByUserID :many
SELECT id, created_at, updated_at, body, user_id FROM chirps WHERE user_id = $1 ORDER BY created_at
`
func (q *Queries) GetChirpsByUserID(ctx context.Context, userID uuid.UUID) ([]Chirp, error) {
rows, err := q.db.QueryContext(ctx, getChirpsByUserID, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Chirp
for rows.Next() {
var i Chirp
if err := rows.Scan(
&i.ID,
&i.CreatedAt,
&i.UpdatedAt,
&i.Body,
&i.UserID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@@ -10,7 +10,7 @@ import (
)
const getUserByEmail = `-- name: GetUserByEmail :one
SELECT id, created_at, updated_at, email, hashed_password FROM users WHERE email = $1
SELECT id, created_at, updated_at, email, hashed_password, is_chirpy_red FROM users WHERE email = $1
`
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
@@ -22,6 +22,7 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
&i.IsChirpyRed,
)
return i, err
}

View File

@@ -12,7 +12,7 @@ import (
)
const getUserByID = `-- name: GetUserByID :one
SELECT id, created_at, updated_at, email, hashed_password FROM users WHERE id = $1
SELECT id, created_at, updated_at, email, hashed_password, is_chirpy_red FROM users WHERE id = $1
`
func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (User, error) {
@@ -24,6 +24,7 @@ func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (User, error) {
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
&i.IsChirpyRed,
)
return i, err
}

View File

@@ -13,7 +13,7 @@ import (
const updateUserEmailAndPassword = `-- name: UpdateUserEmailAndPassword :one
UPDATE users SET email = $1, hashed_password = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3
RETURNING id, created_at, updated_at, email, hashed_password
RETURNING id, created_at, updated_at, email, hashed_password, is_chirpy_red
`
type UpdateUserEmailAndPasswordParams struct {
@@ -31,6 +31,7 @@ func (q *Queries) UpdateUserEmailAndPassword(ctx context.Context, arg UpdateUser
&i.UpdatedAt,
&i.Email,
&i.HashedPassword,
&i.IsChirpyRed,
)
return i, err
}

View File

@@ -0,0 +1,22 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: UpgradeUserToChirpyRed.sql
package database
import (
"context"
"github.com/google/uuid"
)
const upgradeUserToChirpyRed = `-- name: UpgradeUserToChirpyRed :exec
UPDATE users SET is_chirpy_red = true WHERE id = $1
RETURNING id, created_at, updated_at, email, hashed_password, is_chirpy_red
`
func (q *Queries) UpgradeUserToChirpyRed(ctx context.Context, id uuid.UUID) error {
_, err := q.db.ExecContext(ctx, upgradeUserToChirpyRed, id)
return err
}

View File

@@ -34,4 +34,5 @@ type User struct {
UpdatedAt time.Time
Email string
HashedPassword string
IsChirpyRed bool
}

110
main.go
View File

@@ -25,6 +25,7 @@ type apiConfig struct {
db database.Queries
platform string
secret string
polkaKey string
}
func (cfg *apiConfig) middlewareMetricsInc(next http.Handler) http.Handler {
@@ -82,10 +83,29 @@ func fileServerHandler() http.Handler {
func getAllChirpsHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
chirps, err := cfg.db.GetAllChirps(context.Background())
if err != nil {
httpResponse.SomethingWentWrong(w)
return
q := r.URL.Query().Get("author_id")
var chirps []database.Chirp
var err error
var id uuid.UUID
if len(q) == 0 {
chirps, err = cfg.db.GetAllChirps(context.Background())
if err != nil {
httpResponse.SomethingWentWrong(w)
return
}
} else {
id, err = uuid.Parse(q)
if err != nil {
httpResponse.SomethingWentWrong(w)
return
}
chirps, err = cfg.db.GetChirpsByUserID(context.Background(), id)
if err != nil {
httpResponse.SomethingWentWrong(w)
return
}
}
data := make([]dataMaps.Chirp, 0)
@@ -182,6 +202,59 @@ func deleteChirpByIDHandler(cfg *apiConfig) http.HandlerFunc {
httpResponse.PlainTextHandler(w, http.StatusNoContent, "")
}
}
func polkaWebhookHandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key, err := auth.GetAPIKey(r.Header)
if err != nil {
httpResponse.JSONHandler(w, http.StatusUnauthorized, `{"error": "Unauthorized"}`)
return
}
if key != cfg.polkaKey {
httpResponse.JSONHandler(w, http.StatusUnauthorized, `{"error": "Unauthorized"}`)
return
}
type polkaWebhook struct {
Event string `json:"event"`
Data struct {
UserId string `json:"user_id"`
} `json:"data"`
}
data := polkaWebhook{}
err = json.NewDecoder(r.Body).Decode(&data)
if err != nil {
httpResponse.SomethingWentWrong(w)
return
}
if data.Event != "user.upgraded" {
httpResponse.JSONHandler(w, http.StatusNoContent, "")
return
}
userID, err := uuid.Parse(data.Data.UserId)
if err != nil {
httpResponse.JSONHandler(w, http.StatusBadRequest, `{"error": "InvalidUserID"}`)
return
}
_, err = cfg.db.GetUserByID(context.Background(), userID)
if err != nil {
httpResponse.JSONHandler(w, http.StatusNotFound, `{"error": "UserNotFound"}`)
return
}
err = cfg.db.UpgradeUserToChirpyRed(context.Background(), userID)
if err != nil {
httpResponse.SomethingWentWrong(w)
return
}
httpResponse.PlainTextHandler(w, http.StatusNoContent, "")
}
}
func updateUserDatahandler(cfg *apiConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@@ -228,10 +301,11 @@ func updateUserDatahandler(cfg *apiConfig) http.HandlerFunc {
}
userJSON := dataMaps.User{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
IsChirpyRed: user.IsChirpyRed,
}
jsonData, err := json.Marshal(userJSON)
@@ -389,10 +463,11 @@ func loginHandler(cfg *apiConfig) http.HandlerFunc {
}
userJSON := dataMaps.UserWithToken{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
IsChirpyRed: user.IsChirpyRed,
}
expiresIn := time.Duration(3600) * time.Second
@@ -459,10 +534,11 @@ func postUsersHandler(cfg *apiConfig) http.HandlerFunc {
}
userJSON := dataMaps.User{
ID: usr.ID,
CreatedAt: usr.CreatedAt,
UpdatedAt: usr.UpdatedAt,
Email: usr.Email,
ID: usr.ID,
CreatedAt: usr.CreatedAt,
UpdatedAt: usr.UpdatedAt,
Email: usr.Email,
IsChirpyRed: usr.IsChirpyRed,
}
jsonData, err := json.Marshal(userJSON)
@@ -500,6 +576,7 @@ func main() {
apiCfg.platform = os.Getenv("PLATFORM")
apiCfg.secret = os.Getenv("SECRET")
apiCfg.polkaKey = os.Getenv("POLKA_KEY")
db, err := sql.Open("postgres", dbURL)
if err != nil {
@@ -522,6 +599,7 @@ func main() {
mux.HandleFunc("GET /api/chirps", getAllChirpsHandler(apiCfg))
mux.HandleFunc("GET /api/chirps/{chirpID}", getChirpByIDHandler(apiCfg))
mux.HandleFunc("DELETE /api/chirps/{chirpID}", deleteChirpByIDHandler(apiCfg))
mux.HandleFunc("POST /api/polka/webhooks", polkaWebhookHandler(apiCfg))
mux.HandleFunc("PUT /api/users", updateUserDatahandler(apiCfg))
mux.HandleFunc("GET /admin/metrics", adminMetricsHandler(apiCfg))

View File

@@ -0,0 +1,2 @@
-- name: GetChirpsByUserID :many
SELECT * FROM chirps WHERE user_id = $1 ORDER BY created_at;

View File

@@ -0,0 +1,3 @@
-- name: UpgradeUserToChirpyRed :exec
UPDATE users SET is_chirpy_red = true WHERE id = $1
RETURNING *;

View File

@@ -0,0 +1,5 @@
-- +goose Up
ALTER TABLE users ADD COLUMN is_chirpy_red BOOLEAN NOT NULL DEFAULT false;
-- +goose Down
ALTER TABLE users DROP COLUMN is_chirpy_red;