webhooks and chirps by user id
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ type User struct {
|
||||
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"`
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
45
internal/database/GetChirpsByUserID.sql.go
Normal file
45
internal/database/GetChirpsByUserID.sql.go
Normal 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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
22
internal/database/UpgradeUserToChirpyRed.sql.go
Normal file
22
internal/database/UpgradeUserToChirpyRed.sql.go
Normal 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
|
||||
}
|
||||
@@ -34,4 +34,5 @@ type User struct {
|
||||
UpdatedAt time.Time
|
||||
Email string
|
||||
HashedPassword string
|
||||
IsChirpyRed bool
|
||||
}
|
||||
|
||||
80
main.go
80
main.go
@@ -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,11 +83,30 @@ 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())
|
||||
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)
|
||||
for _, chirp := range chirps {
|
||||
@@ -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) {
|
||||
@@ -232,6 +305,7 @@ func updateUserDatahandler(cfg *apiConfig) http.HandlerFunc {
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
Email: user.Email,
|
||||
IsChirpyRed: user.IsChirpyRed,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(userJSON)
|
||||
@@ -393,6 +467,7 @@ func loginHandler(cfg *apiConfig) http.HandlerFunc {
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
Email: user.Email,
|
||||
IsChirpyRed: user.IsChirpyRed,
|
||||
}
|
||||
|
||||
expiresIn := time.Duration(3600) * time.Second
|
||||
@@ -463,6 +538,7 @@ func postUsersHandler(cfg *apiConfig) http.HandlerFunc {
|
||||
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))
|
||||
|
||||
2
sql/queries/GetChirpsByUserID.sql
Normal file
2
sql/queries/GetChirpsByUserID.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- name: GetChirpsByUserID :many
|
||||
SELECT * FROM chirps WHERE user_id = $1 ORDER BY created_at;
|
||||
3
sql/queries/UpgradeUserToChirpyRed.sql
Normal file
3
sql/queries/UpgradeUserToChirpyRed.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
-- name: UpgradeUserToChirpyRed :exec
|
||||
UPDATE users SET is_chirpy_red = true WHERE id = $1
|
||||
RETURNING *;
|
||||
@@ -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;
|
||||
Reference in New Issue
Block a user