feat: Added last chapter and refactored whole project
This commit is contained in:
@ -108,3 +108,37 @@ func (q *Queries) GetChirps(ctx context.Context) ([]Chirp, error) {
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const getChirpsByUserid = `-- name: GetChirpsByUserid :many
|
||||
SELECT id, created_at, updated_at, body, user_id FROM chirps
|
||||
WHERE chirps.user_id = $1
|
||||
`
|
||||
|
||||
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
|
||||
}
|
||||
|
@ -44,3 +44,30 @@ func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshToken
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserFromRefreshToken = `-- name: GetUserFromRefreshToken :one
|
||||
SELECT user_id FROM refresh_tokens
|
||||
WHERE refresh_tokens.token = $1
|
||||
AND refresh_tokens.expires_at > NOW()
|
||||
AND refresh_tokens.revoked_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserFromRefreshToken(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
row := q.db.QueryRowContext(ctx, getUserFromRefreshToken, token)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const revokeRefreshToken = `-- name: RevokeRefreshToken :exec
|
||||
UPDATE refresh_tokens
|
||||
SET
|
||||
revoked_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE token = $1
|
||||
`
|
||||
|
||||
func (q *Queries) RevokeRefreshToken(ctx context.Context, token string) error {
|
||||
_, err := q.db.ExecContext(ctx, revokeRefreshToken, token)
|
||||
return err
|
||||
}
|
||||
|
@ -1,23 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.27.0
|
||||
// source: update_token.sql
|
||||
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const revokeRefreshToken = `-- name: RevokeRefreshToken :exec
|
||||
UPDATE refresh_tokens
|
||||
SET
|
||||
revoked_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE token = $1
|
||||
`
|
||||
|
||||
func (q *Queries) RevokeRefreshToken(ctx context.Context, token string) error {
|
||||
_, err := q.db.ExecContext(ctx, revokeRefreshToken, token)
|
||||
return err
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.27.0
|
||||
// source: update_users.sql
|
||||
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const updateUserCredentials = `-- name: UpdateUserCredentials :one
|
||||
UPDATE users
|
||||
SET email = $2,
|
||||
hashed_password = $3,
|
||||
updated_at = NOW()
|
||||
WHERE users.id = $1
|
||||
RETURNING id, created_at, updated_at, email, is_chirpy_red
|
||||
`
|
||||
|
||||
type UpdateUserCredentialsParams struct {
|
||||
ID uuid.UUID
|
||||
Email string
|
||||
HashedPassword string
|
||||
}
|
||||
|
||||
type UpdateUserCredentialsRow struct {
|
||||
ID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Email string
|
||||
IsChirpyRed bool
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateUserCredentials(ctx context.Context, arg UpdateUserCredentialsParams) (UpdateUserCredentialsRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, updateUserCredentials, arg.ID, arg.Email, arg.HashedPassword)
|
||||
var i UpdateUserCredentialsRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Email,
|
||||
&i.IsChirpyRed,
|
||||
)
|
||||
return i, err
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.27.0
|
||||
// source: user_from_token.sql
|
||||
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const getUserFromRefreshToken = `-- name: GetUserFromRefreshToken :one
|
||||
SELECT user_id FROM refresh_tokens
|
||||
WHERE refresh_tokens.token = $1
|
||||
AND refresh_tokens.expires_at > NOW()
|
||||
AND refresh_tokens.revoked_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserFromRefreshToken(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
row := q.db.QueryRowContext(ctx, getUserFromRefreshToken, token)
|
||||
var user_id uuid.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
@ -7,6 +7,7 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@ -80,6 +81,42 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateUserCredentials = `-- name: UpdateUserCredentials :one
|
||||
UPDATE users
|
||||
SET email = $2,
|
||||
hashed_password = $3,
|
||||
updated_at = NOW()
|
||||
WHERE users.id = $1
|
||||
RETURNING id, created_at, updated_at, email, is_chirpy_red
|
||||
`
|
||||
|
||||
type UpdateUserCredentialsParams struct {
|
||||
ID uuid.UUID
|
||||
Email string
|
||||
HashedPassword string
|
||||
}
|
||||
|
||||
type UpdateUserCredentialsRow struct {
|
||||
ID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Email string
|
||||
IsChirpyRed bool
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateUserCredentials(ctx context.Context, arg UpdateUserCredentialsParams) (UpdateUserCredentialsRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, updateUserCredentials, arg.ID, arg.Email, arg.HashedPassword)
|
||||
var i UpdateUserCredentialsRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Email,
|
||||
&i.IsChirpyRed,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const upgradeUser = `-- name: UpgradeUser :exec
|
||||
UPDATE users
|
||||
SET is_chirpy_red = true
|
||||
|
213
internal/handler/chirp.go
Normal file
213
internal/handler/chirp.go
Normal 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(¶ms)
|
||||
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)
|
||||
}
|
15
internal/handler/config.go
Normal file
15
internal/handler/config.go
Normal 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
84
internal/handler/login.go
Normal 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,
|
||||
})
|
||||
}
|
27
internal/handler/metrics.go
Normal file
27
internal/handler/metrics.go
Normal 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)))
|
||||
}
|
9
internal/handler/readiness.go
Normal file
9
internal/handler/readiness.go
Normal 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
22
internal/handler/reset.go
Normal 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)
|
||||
}
|
19
internal/handler/response.go
Normal file
19
internal/handler/response.go
Normal 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
52
internal/handler/token.go
Normal 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
156
internal/handler/users.go
Normal 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(¶ms)
|
||||
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(¶ms)
|
||||
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(¶ms)
|
||||
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)
|
||||
}
|
Reference in New Issue
Block a user