Added auth routes with jwt generation and middleware.
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"nfeeder/internal/db"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const ISSUER = "nfeeder-app"
|
||||
|
||||
var jwtKey = []byte("very_super_duper_secret")
|
||||
|
||||
func (s *Server) handleRegister() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
// hash password
|
||||
hashpw, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
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)
|
||||
http.Error(w, "Could not create user", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-login after reg
|
||||
s.issueTokenAndRedirect(w, r, fmt.Sprintf("%d", user.ID))
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// compare passwords
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
s.issueTokenAndRedirect(w, r, fmt.Sprintf("%d", user.ID))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// To logout, we simply instruct the browser to delete the cookie
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "nfeeder_token",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
Expires: time.Unix(0, 0), // Expire immediately
|
||||
HttpOnly: true,
|
||||
})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) issueTokenAndRedirect(w http.ResponseWriter, r *http.Request, userID string) {
|
||||
claims := jwt.RegisteredClaims{
|
||||
Issuer: ISSUER,
|
||||
Subject: userID,
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString(jwtKey)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "nfeeder_token",
|
||||
Value: tokenString,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: false, // Set to true in prod for HTTPS
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: time.Now().Add(24 * time.Hour),
|
||||
})
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func (s *Server) hasAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("nfeeder_token")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// parse and validate
|
||||
claims := &jwt.RegisteredClaims{}
|
||||
token, err := jwt.ParseWithClaims(cookie.Value, claims, func(t *jwt.Token) (interface{}, error) {
|
||||
// check alg
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
|
||||
return jwtKey, 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 {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Verify issuer
|
||||
if claims.Issuer != ISSUER {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Success! Store userID in context for handlers to use
|
||||
ctx := context.WithValue(r.Context(), userIDKey, claims.Subject)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
+12
-2
@@ -18,11 +18,21 @@ func (s *Server) setupRoutes() *chi.Mux {
|
||||
|
||||
// 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())
|
||||
|
||||
// public pages
|
||||
r.Get("/", s.handleHome())
|
||||
})
|
||||
|
||||
//s.router.Get("/", s.handleIndex())
|
||||
//s.router.Post("/users", s.handleCreateUser())
|
||||
// User routes
|
||||
router.Group(func(r chi.Router) {
|
||||
// Requires log in
|
||||
r.Use(s.hasAuth)
|
||||
router.Mount("/users", s.userRoutes())
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user