Initial commit
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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"}}`))
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||
)
|
||||
|
||||
// Client wraps the mongo client and exposes typed collection accessors.
|
||||
type Client struct {
|
||||
client *mongo.Client
|
||||
db *mongo.Database
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, uri string) (*Client, error) {
|
||||
opts := options.Client().ApplyURI(uri)
|
||||
c, err := mongo.Connect(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := c.Ping(pingCtx, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{client: c, db: c.Database("logjensticks")}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Disconnect(ctx context.Context) error {
|
||||
return c.client.Disconnect(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) Users() *mongo.Collection {
|
||||
return c.db.Collection("users")
|
||||
}
|
||||
|
||||
func (c *Client) Sessions() *mongo.Collection {
|
||||
return c.db.Collection("sessions")
|
||||
}
|
||||
|
||||
func (c *Client) Lanes() *mongo.Collection {
|
||||
return c.db.Collection("lanes")
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
||||
)
|
||||
|
||||
// EnsureIndexes creates all required indexes. Safe to call on every startup
|
||||
// (mongo ignores duplicate index creation).
|
||||
func (c *Client) EnsureIndexes(ctx context.Context) error {
|
||||
if err := c.ensureUserIndexes(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.ensureSessionIndexes(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.ensureLaneIndexes(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) ensureLaneIndexes(ctx context.Context) error {
|
||||
_, err := c.Lanes().Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "created_by", Value: 1}},
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) ensureUserIndexes(ctx context.Context) error {
|
||||
_, err := c.Users().Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "username", Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) ensureSessionIndexes(ctx context.Context) error {
|
||||
// Unique lookup index on the session token.
|
||||
if _, err := c.Sessions().Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "token", Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// TTL index: MongoDB automatically deletes session documents after
|
||||
// expires_at has passed (checked roughly every 60 s by the reaper).
|
||||
expireAfter := int32(0)
|
||||
if _, err := c.Sessions().Indexes().CreateOne(ctx, mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "expires_at", Value: 1}},
|
||||
Options: options.Index().SetExpireAfterSeconds(expireAfter),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SessionTTL is how long a session stays valid.
|
||||
const SessionTTL = 24 * time.Hour
|
||||
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// SeedBroker inserts a default broker account if no users exist.
|
||||
// Credentials are taken from environment variables SEED_USERNAME and
|
||||
// SEED_PASSWORD; if unset they fall back to dev defaults and a warning
|
||||
// is printed. This function must not run in production without those vars set.
|
||||
func (c *Client) SeedBroker(ctx context.Context, username, password string) error {
|
||||
count, err := c.Users().CountDocuments(ctx, bson.D{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil // already seeded
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = c.Users().InsertOne(ctx, bson.D{
|
||||
{Key: "username", Value: username},
|
||||
{Key: "password_hash", Value: string(hash)},
|
||||
{Key: "role", Value: "broker"},
|
||||
})
|
||||
if err != nil && !mongo.IsDuplicateKeyError(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("db: seeded broker user %q", username)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user