Initial commit

This commit is contained in:
2026-05-12 15:40:22 -06:00
parent 5b279865a1
commit 1eac72b3cd
31 changed files with 1192 additions and 45 deletions
+95
View File
@@ -0,0 +1,95 @@
package auth
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"golang.org/x/crypto/bcrypt"
"logjensticks/internal/db"
)
var ErrInvalidCredentials = errors.New("invalid username or password")
var ErrSessionNotFound = errors.New("session not found or expired")
type User struct {
Username string `bson:"username"`
PasswordHash string `bson:"password_hash"`
Role string `bson:"role"`
}
type Session struct {
Token string `bson:"token"`
Username string `bson:"username"`
Role string `bson:"role"`
ExpiresAt time.Time `bson:"expires_at"`
}
// Login verifies credentials, creates a session, and returns the session token.
func Login(ctx context.Context, dbc *db.Client, username, password string) (string, *Session, error) {
var user User
err := dbc.Users().FindOne(ctx, bson.D{{Key: "username", Value: username}}).Decode(&user)
if errors.Is(err, mongo.ErrNoDocuments) {
return "", nil, ErrInvalidCredentials
}
if err != nil {
return "", nil, err
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
return "", nil, ErrInvalidCredentials
}
token, err := generateToken()
if err != nil {
return "", nil, err
}
session := Session{
Token: token,
Username: user.Username,
Role: user.Role,
ExpiresAt: time.Now().UTC().Add(db.SessionTTL),
}
if _, err := dbc.Sessions().InsertOne(ctx, session); err != nil {
return "", nil, err
}
return token, &session, nil
}
// ValidateSession looks up a session by token and confirms it has not expired.
func ValidateSession(ctx context.Context, dbc *db.Client, token string) (*Session, error) {
var session Session
err := dbc.Sessions().FindOne(ctx, bson.D{{Key: "token", Value: token}}).Decode(&session)
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, ErrSessionNotFound
}
if err != nil {
return nil, err
}
if time.Now().After(session.ExpiresAt) {
return nil, ErrSessionNotFound
}
return &session, nil
}
// DeleteSession removes a session document (used on logout).
func DeleteSession(ctx context.Context, dbc *db.Client, token string) error {
_, err := dbc.Sessions().DeleteOne(ctx, bson.D{{Key: "token", Value: token}})
return err
}
func generateToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
+50
View File
@@ -0,0 +1,50 @@
package auth
import (
"context"
"net/http"
"logjensticks/internal/db"
)
const CookieName = "session_token"
type contextKey string
const sessionContextKey contextKey = "session"
// Middleware validates the session cookie on every request. Attach this to
// any route that requires authentication.
func Middleware(dbc *db.Client) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(CookieName)
if err != nil {
writeUnauthorized(w)
return
}
session, err := ValidateSession(r.Context(), dbc, cookie.Value)
if err != nil {
writeUnauthorized(w)
return
}
ctx := context.WithValue(r.Context(), sessionContextKey, session)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// SessionFromContext retrieves the validated session attached by Middleware.
// Returns nil if called outside an authenticated route.
func SessionFromContext(ctx context.Context) *Session {
s, _ := ctx.Value(sessionContextKey).(*Session)
return s
}
func writeUnauthorized(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"success":false,"data":null,"error":{"code":"UNAUTHORIZED","message":"authentication required"}}`))
}