Update structure to domain driven architecture.
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// TODO CLEANUP: Test route for now
|
||||
func (s *Server) handleHome() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 1. Grab the userID from the context (placed there by s.hasAuth)
|
||||
userID, ok := userIDFromContext(r.Context())
|
||||
if !ok {
|
||||
// Technically never happen if the middleware is working...
|
||||
log.Printf("UNAUTHORIZED!")
|
||||
http.Error(w, "User not found in context", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Respond with something that proves it works
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"message": "Welcome to the nfeeder API!",
|
||||
"user_id": userID,
|
||||
"status": "authenticated",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"nfeeder/db"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func (s *Server) handleRegister() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
if email == "" || password == "" {
|
||||
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Email and password required"})
|
||||
return
|
||||
}
|
||||
|
||||
// hash password
|
||||
hashpw, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "Internal Error"})
|
||||
return
|
||||
}
|
||||
|
||||
// create the user
|
||||
user, err := s.store.CreateUser(r.Context(), db.CreateUserParams{
|
||||
Email: email,
|
||||
Password: string(hashpw),
|
||||
})
|
||||
if err != nil {
|
||||
// Log the actual error for yourself, send a generic one to the user
|
||||
log.Printf("Failed to create user: %v", err)
|
||||
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Failed to create user"})
|
||||
return
|
||||
}
|
||||
|
||||
s.issueToken(w, r, user.ID, false)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleLogin() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
user, err := s.store.GetUserByEmail(r.Context(), email)
|
||||
if err != nil {
|
||||
log.Printf("failed to get user: %v", err)
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
// compare passwords
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||||
if err != nil {
|
||||
log.Printf("incorrect password entered: %v", err)
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
s.issueToken(w, r, user.ID, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req RefreshTokenReq
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
log.Printf("handleRefresh failed to parse request body: %v", err)
|
||||
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Invalid JSON"})
|
||||
return
|
||||
}
|
||||
|
||||
hash := sha256.Sum256([]byte(req.RefreshToken))
|
||||
hex_token := hex.EncodeToString(hash[:])
|
||||
|
||||
tokenRecord, err := s.store.GetValidRefreshToken(r.Context(), hex_token)
|
||||
if err != nil {
|
||||
log.Printf("Logout succes, warning: token not found or expired: %v", err)
|
||||
WriteJSON(w, http.StatusOK, SuccessResponse{Message: "logout success"})
|
||||
return
|
||||
}
|
||||
|
||||
err = s.store.DeleteRefreshToken(r.Context(), db.DeleteRefreshTokenParams{
|
||||
TokenHash: hex_token,
|
||||
UserID: tokenRecord.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Failed to delete old refresh token: %v", err)
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, SuccessResponse{
|
||||
Message: "logout success",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleRefresh() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req RefreshTokenReq
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
log.Printf("handleRefresh failed to parse request body: %v", err)
|
||||
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "Invalid JSON"})
|
||||
return
|
||||
}
|
||||
|
||||
hash := sha256.Sum256([]byte(req.RefreshToken))
|
||||
hex_token := hex.EncodeToString(hash[:])
|
||||
|
||||
tokenRecord, err := s.store.GetValidRefreshToken(r.Context(), hex_token)
|
||||
if err != nil {
|
||||
log.Printf("Refresh failed - token not found or expired: %v", err)
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{Error: "Invalid or expired session"})
|
||||
return
|
||||
}
|
||||
|
||||
err = s.store.DeleteRefreshToken(r.Context(), db.DeleteRefreshTokenParams{
|
||||
TokenHash: hex_token,
|
||||
UserID: tokenRecord.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Failed to delete old refresh token: %v", err)
|
||||
}
|
||||
|
||||
s.issueToken(w, r, tokenRecord.UserID, false)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) issueToken(w http.ResponseWriter, r *http.Request, userID int64, checkLimit bool) {
|
||||
nowTime := time.Now()
|
||||
jwtExpireTime := nowTime.Add(24 * time.Hour)
|
||||
|
||||
claims := jwt.RegisteredClaims{
|
||||
Issuer: ISSUER,
|
||||
Subject: strconv.FormatInt(userID, 10),
|
||||
ExpiresAt: jwt.NewNumericDate(jwtExpireTime),
|
||||
IssuedAt: jwt.NewNumericDate(nowTime),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString(s.jwtSecret)
|
||||
if err != nil {
|
||||
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{
|
||||
Error: "Internal Server Error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
refreshToken := s.issueRefreshToken(r.Context(), userID, nowTime, checkLimit)
|
||||
if refreshToken == "" {
|
||||
WriteJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "Internal Server Error"})
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, AuthResponse{
|
||||
AccessToken: tokenString,
|
||||
RefreshToken: refreshToken,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) issueRefreshToken(ctx context.Context, userID int64, issuedTime time.Time, checkLimit bool) string {
|
||||
refreshExpireTime := issuedTime.Add((24 * time.Hour) * 3)
|
||||
|
||||
// Generate refresh token
|
||||
rawToken := rand.Text()
|
||||
hash := sha256.Sum256([]byte(rawToken))
|
||||
hex_token := hex.EncodeToString(hash[:])
|
||||
|
||||
// Check the user has not got the session limit.
|
||||
if checkLimit {
|
||||
sessionCount, err := s.store.CountUserRefreshTokens(ctx, userID)
|
||||
if err != nil {
|
||||
log.Printf("failed to count refresh token: %v", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
// Each user can only have 3 sessions, if they have 3 refresh tokens
|
||||
// remove the oldest one and then create a new refresh token
|
||||
if sessionCount >= int64(MAX_USER_SESSIONS) {
|
||||
err = s.store.DeleteOldestRefreshToken(ctx, userID)
|
||||
if err != nil {
|
||||
log.Printf("failed to delete oldest refresh token: %v", err)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_, err := s.store.CreateRefreshToken(ctx, db.CreateRefreshTokenParams{
|
||||
UserID: userID,
|
||||
TokenHash: hex_token,
|
||||
ExpiresAt: pgtype.Timestamptz{Time: refreshExpireTime, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
// Log the actual error for yourself, send a generic one to the user
|
||||
log.Printf("failed to create refresh token: %v", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
return rawToken
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func (s *Server) logRequest(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
// 1. Wrap the response writer
|
||||
// This intercepts the Status code when it's written later in the chain
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
|
||||
// 2. Call the next handler in the chain
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// 3. Capture the actual results
|
||||
status := ww.Status()
|
||||
duration := time.Since(start)
|
||||
|
||||
// 4. Build the log attributes
|
||||
// Using slog.Group keeps the "request" data organized
|
||||
requestGroup := slog.Group("request",
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.String("ip", r.RemoteAddr),
|
||||
)
|
||||
|
||||
// 5. Log with appropriate level based on status
|
||||
if status >= 400 {
|
||||
s.logger.Error("HTTP Request Error",
|
||||
requestGroup,
|
||||
slog.Int("status", status),
|
||||
slog.Duration("took", duration),
|
||||
)
|
||||
} else {
|
||||
s.logger.Info("HTTP Request",
|
||||
requestGroup,
|
||||
slog.Int("status", status),
|
||||
slog.Duration("took", duration),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) hasAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var tokenString string
|
||||
|
||||
// Authorization Header Bearer token
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
|
||||
tokenString = authHeader[7:]
|
||||
}
|
||||
|
||||
// Fallback to Cookie (future Web Frontend)
|
||||
if tokenString == "" {
|
||||
if cookie, err := r.Cookie("nfeeder_token"); err == nil {
|
||||
tokenString = cookie.Value
|
||||
}
|
||||
}
|
||||
|
||||
if tokenString == "" {
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// parse and validate
|
||||
claims := &jwt.RegisteredClaims{}
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
||||
// check/confirm alg
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
|
||||
return s.jwtSecret, nil
|
||||
})
|
||||
|
||||
/// golang-jwt the library internally runs a Valid():
|
||||
/// Time Check: It compares time.Now() against the ExpiresAt value.
|
||||
/// Not Before Check: It checks if the nbf (Not Before) time has passed.
|
||||
/// Issued At Check: It ensures the iat isn't in the future.
|
||||
if err != nil || !token.Valid {
|
||||
// Check if the error is specifically because the token expired
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "Token expired: Please use your refresh token to get a new session",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify issuer
|
||||
if claims.Issuer != ISSUER {
|
||||
log.Printf("Invalid Token, issuer incorrect or tampered with")
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "Invalid Token",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Success! Store userID in context for handlers to use
|
||||
ctx := context.WithValue(r.Context(), userIDKey, claims.Subject)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package web
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type SuccessResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type AuthResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
type RefreshTokenReq struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
func (s *Server) setupRoutes() *chi.Mux {
|
||||
router := chi.NewRouter()
|
||||
|
||||
// Global Middleware
|
||||
router.Use(middleware.RequestID)
|
||||
router.Use(middleware.RealIP)
|
||||
router.Use(s.logRequest)
|
||||
router.Use(middleware.Recoverer)
|
||||
|
||||
// Public routes
|
||||
router.Group(func(r chi.Router) {
|
||||
// Auth Routes
|
||||
router.Post("/register", s.handleRegister())
|
||||
router.Post("/login", s.handleLogin())
|
||||
router.Post("/logout", s.handleLogout())
|
||||
router.Post("/refresh", s.handleRefresh())
|
||||
})
|
||||
|
||||
// Private routes
|
||||
router.Group(func(r chi.Router) {
|
||||
// Requires log in
|
||||
r.Use(s.hasAuth)
|
||||
|
||||
// TODO add authenicated routes here
|
||||
r.Get("/home", s.handleHome())
|
||||
// router.Mount("/api", s.apiRoutes())
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"nfeeder/db"
|
||||
)
|
||||
|
||||
const (
|
||||
MAX_USER_SESSIONS = 3
|
||||
ISSUER = "nfeeder-app"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
logger *slog.Logger
|
||||
store *db.Store
|
||||
jwtSecret []byte
|
||||
}
|
||||
|
||||
func NewServer(store *db.Store, logger *slog.Logger, secret string) *Server {
|
||||
s := &Server{
|
||||
store: store,
|
||||
logger: logger,
|
||||
// could extend this to something more generic will do if more fields needed
|
||||
jwtSecret: []byte(secret),
|
||||
}
|
||||
|
||||
s.httpServer = &http.Server{
|
||||
Handler: s.setupRoutes(),
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start(addr string) error {
|
||||
s.httpServer.Addr = addr
|
||||
s.logger.Info("server starting", "addr", addr)
|
||||
|
||||
return s.httpServer.ListenAndServe()
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
s.logger.Info("shutting down http server")
|
||||
return s.httpServer.Shutdown(ctx)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Server will respond with an expected struct of information.
|
||||
// Otherwise will return the correct error status code.
|
||||
// Client responsibility to check status then unmarshal to
|
||||
// error response or data
|
||||
func WriteJSON[T any](w http.ResponseWriter, status int, data T) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if err := json.NewEncoder(w).Encode(data); err != nil {
|
||||
log.Printf("JSON encode error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func userIDFromContext(ctx context.Context) (int64, bool) {
|
||||
val := ctx.Value(userIDKey)
|
||||
if val == nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
strID, ok := val.(string)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
id, err := strconv.ParseInt(strID, 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return id, true
|
||||
}
|
||||
Reference in New Issue
Block a user