Compare commits

..

4 Commits

14 changed files with 380 additions and 72 deletions

View File

@@ -7,9 +7,6 @@
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers/features/github-cli:1": {},
"ghcr.io/devcontainers/features/docker-in-docker:2": {
"moby": false
},
"ghcr.io/tailscale/codespace/tailscale": {
"version": "latest"
},
@@ -18,19 +15,14 @@
"golangciLintVersion": "2.6.1"
}
},
"postCreateCommand": "./scripts/setup-git.sh",
"postCreateCommand": "./scripts/setup-git.sh && ./scripts/install-vscode-extensions.sh",
"customizations": {
"vscode": {
"extensions": [
"biomejs.biome",
"bradlc.vscode-tailwindcss",
"ms-vscode.vscode-typescript-next",
"esbenp.prettier-vscode",
"ms-vscode.vscode-json",
"formulahendry.auto-rename-tag",
"christian-kohler.path-intellisense",
"ms-vscode.vscode-eslint",
"convex.convex-vscode"
"golang.go"
],
"settings": {
"editor.defaultFormatter": "biomejs.biome",

View File

@@ -1,6 +1,11 @@
package auth
import "fmt"
import (
"errors"
"fmt"
)
var ErrUnauthenticatedRequest = errors.New("unauthenticated request")
type InvalidAccessTokenError struct {
err error

View File

@@ -3,6 +3,7 @@ package auth
import (
"errors"
"github.com/get-drexa/drexa/internal/user"
"github.com/gofiber/fiber/v2"
)
@@ -20,9 +21,9 @@ type registerRequest struct {
}
type loginResponse struct {
User User `json:"user"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
User user.User `json:"user"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
}
func RegisterAPIRoutes(api fiber.Router, s *Service) {
@@ -56,7 +57,7 @@ func login(c *fiber.Ctx) error {
}
return c.JSON(loginResponse{
User: result.User,
User: *result.User,
AccessToken: result.AccessToken,
RefreshToken: result.RefreshToken,
})
@@ -76,14 +77,15 @@ func register(c *fiber.Ctx) error {
displayName: req.DisplayName,
})
if err != nil {
if errors.Is(err, ErrUserExists) {
var ae *user.AlreadyExistsError
if errors.As(err, &ae) {
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": "User already exists"})
}
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Internal server error"})
}
return c.JSON(loginResponse{
User: result.User,
User: *result.User,
AccessToken: result.AccessToken,
RefreshToken: result.RefreshToken,
})

View File

@@ -0,0 +1,56 @@
package auth
import (
"errors"
"strings"
"github.com/get-drexa/drexa/internal/user"
"github.com/gofiber/fiber/v2"
)
const authenticatedUserKey = "authenticatedUser"
// NewBearerAuthMiddleware is a middleware that authenticates a request using a bearer token.
// To obtain the authenticated user in subsequent handlers, see AuthenticatedUser.
func NewBearerAuthMiddleware(s *Service) fiber.Handler {
return func(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
if authHeader == "" {
return c.SendStatus(fiber.StatusUnauthorized)
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
return c.SendStatus(fiber.StatusUnauthorized)
}
token := parts[1]
u, err := s.AuthenticateWithAccessToken(c.Context(), token)
if err != nil {
var e *InvalidAccessTokenError
if errors.As(err, &e) {
return c.SendStatus(fiber.StatusUnauthorized)
}
var nf *user.NotFoundError
if errors.As(err, &nf) {
return c.SendStatus(fiber.StatusUnauthorized)
}
return c.SendStatus(fiber.StatusInternalServerError)
}
c.Locals(authenticatedUserKey, u)
return c.Next()
}
}
// AuthenticatedUser returns the authenticated user from the given fiber context.
// Returns ErrUnauthenticatedRequest if not authenticated.
func AuthenticatedUser(c *fiber.Ctx) (*user.User, error) {
if u, ok := c.Locals(authenticatedUserKey).(*user.User); ok {
return u, nil
}
return nil, ErrUnauthenticatedRequest
}

View File

@@ -5,20 +5,23 @@ import (
"encoding/hex"
"errors"
"github.com/get-drexa/drexa/internal/password"
"github.com/get-drexa/drexa/internal/user"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
type LoginResult struct {
User User
User *user.User
AccessToken string
RefreshToken string
}
var ErrInvalidCredentials = errors.New("invalid credentials")
var ErrUserExists = errors.New("user already exists")
type Service struct {
db *bun.DB
userService *user.Service
tokenConfig TokenConfig
}
@@ -28,32 +31,35 @@ type registerOptions struct {
password string
}
func NewService(db *bun.DB, tokenConfig TokenConfig) *Service {
func NewService(db *bun.DB, userService *user.Service, tokenConfig TokenConfig) *Service {
return &Service{
db: db,
userService: userService,
tokenConfig: tokenConfig,
}
}
func (s *Service) LoginWithEmailAndPassword(ctx context.Context, email, password string) (*LoginResult, error) {
var user User
err := s.db.NewSelect().Model(&user).Where("email = ?", email).Scan(ctx)
func (s *Service) LoginWithEmailAndPassword(ctx context.Context, email, plain string) (*LoginResult, error) {
u, err := s.userService.UserByEmail(ctx, email)
if err != nil {
var nf *user.NotFoundError
if errors.As(err, &nf) {
return nil, ErrInvalidCredentials
}
return nil, err
}
ok, err := VerifyPassword(password, user.Password)
ok, err := password.Verify(plain, u.Password)
if err != nil || !ok {
return nil, ErrInvalidCredentials
}
at, err := GenerateAccessToken(&user, &s.tokenConfig)
at, err := GenerateAccessToken(u, &s.tokenConfig)
if err != nil {
return nil, err
}
rt, err := GenerateRefreshToken(&user, &s.tokenConfig)
rt, err := GenerateRefreshToken(u, &s.tokenConfig)
if err != nil {
return nil, err
}
@@ -64,49 +70,59 @@ func (s *Service) LoginWithEmailAndPassword(ctx context.Context, email, password
}
return &LoginResult{
User: user,
User: u,
AccessToken: at,
RefreshToken: hex.EncodeToString(rt.Token),
}, nil
}
func (s *Service) Register(ctx context.Context, opts registerOptions) (*LoginResult, error) {
user := User{
hashed, err := password.Hash(opts.password)
if err != nil {
return nil, err
}
u, err := s.userService.RegisterUser(ctx, user.UserRegistrationOptions{
Email: opts.email,
DisplayName: opts.displayName,
}
exists, err := s.db.NewSelect().Model(&user).Where("email = ?", opts.email).Exists(ctx)
if err != nil {
return nil, err
}
if exists {
return nil, ErrUserExists
}
user.Password, err = HashPassword(opts.password)
Password: hashed,
})
if err != nil {
return nil, err
}
_, err = s.db.NewInsert().Model(&user).Exec(ctx)
at, err := GenerateAccessToken(u, &s.tokenConfig)
if err != nil {
return nil, err
}
at, err := GenerateAccessToken(&user, &s.tokenConfig)
rt, err := GenerateRefreshToken(u, &s.tokenConfig)
if err != nil {
return nil, err
}
rt, err := GenerateRefreshToken(&user, &s.tokenConfig)
_, err = s.db.NewInsert().Model(rt).Exec(ctx)
if err != nil {
return nil, err
}
return &LoginResult{
User: user,
User: u,
AccessToken: at,
RefreshToken: hex.EncodeToString(rt.Token),
}, nil
}
func (s *Service) AuthenticateWithAccessToken(ctx context.Context, token string) (*user.User, error) {
claims, err := ParseAccessToken(token, &s.tokenConfig)
if err != nil {
return nil, err
}
id, err := uuid.Parse(claims.Subject)
if err != nil {
return nil, newInvalidAccessTokenError(err)
}
return s.userService.UserByID(ctx, id)
}

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"time"
"github.com/get-drexa/drexa/internal/user"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/uptrace/bun"
@@ -35,7 +36,7 @@ type RefreshToken struct {
CreatedAt time.Time `bun:"created_at,notnull"`
}
func GenerateAccessToken(user *User, c *TokenConfig) (string, error) {
func GenerateAccessToken(user *user.User, c *TokenConfig) (string, error) {
now := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
@@ -54,7 +55,7 @@ func GenerateAccessToken(user *User, c *TokenConfig) (string, error) {
return signed, nil
}
func GenerateRefreshToken(user *User, c *TokenConfig) (*RefreshToken, error) {
func GenerateRefreshToken(user *user.User, c *TokenConfig) (*RefreshToken, error) {
now := time.Now()
buf := make([]byte, refreshTokenByteLength)
@@ -80,6 +81,8 @@ func GenerateRefreshToken(user *User, c *TokenConfig) (*RefreshToken, error) {
}, nil
}
// ParseAccessToken parses a JWT access token and returns the claims.
// Returns an InvalidAccessTokenError if the token is invalid.
func ParseAccessToken(token string, c *TokenConfig) (*jwt.RegisteredClaims, error) {
parsed, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (any, error) {
return c.SecretKey, nil

View File

@@ -1,17 +0,0 @@
package auth
import (
"github.com/google/uuid"
"github.com/uptrace/bun"
)
type User struct {
bun.BaseModel `bun:"users"`
ID uuid.UUID `bun:",pk,type:uuid" json:"id"`
DisplayName string `bun:"display_name,notnull" json:"displayName"`
Email string `bun:"email,unique,notnull" json:"email"`
Password string `bun:"password,notnull" json:"-"`
StorageUsageBytes int64 `bun:"storage_usage_bytes,notnull" json:"storageUsageBytes"`
StorageQuotaBytes int64 `bun:"storage_quota_bytes,notnull" json:"storageQuotaBytes"`
}

View File

@@ -0,0 +1,61 @@
package database
import (
"errors"
"github.com/uptrace/bun/driver/pgdriver"
)
// PostgreSQL SQLSTATE error codes.
// See: https://www.postgresql.org/docs/current/errcodes-appendix.html
const (
PgUniqueViolation = "23505"
PgForeignKeyViolation = "23503"
PgNotNullViolation = "23502"
)
// PostgreSQL protocol error field identifiers used with pgdriver.Error.Field().
// See: https://www.postgresql.org/docs/current/protocol-error-fields.html
//
// Common fields:
// - 'C' - SQLSTATE code (e.g., "23505")
// - 'M' - Primary error message
// - 'D' - Detail message
// - 'H' - Hint
// - 's' - Schema name
// - 't' - Table name
// - 'c' - Column name
// - 'n' - Constraint name
const (
pgFieldCode = 'C'
pgFieldConstraint = 'n'
)
// IsUniqueViolation checks if the error is a PostgreSQL unique constraint violation.
func IsUniqueViolation(err error) bool {
return hasPgCode(err, PgUniqueViolation)
}
// IsForeignKeyViolation checks if the error is a PostgreSQL foreign key violation.
func IsForeignKeyViolation(err error) bool {
return hasPgCode(err, PgForeignKeyViolation)
}
// IsNotNullViolation checks if the error is a PostgreSQL not-null constraint violation.
func IsNotNullViolation(err error) bool {
return hasPgCode(err, PgNotNullViolation)
}
// ConstraintName returns the constraint name from a PostgreSQL error, or empty string if not applicable.
func ConstraintName(err error) string {
var pgErr pgdriver.Error
if errors.As(err, &pgErr) {
return pgErr.Field(pgFieldConstraint)
}
return ""
}
func hasPgCode(err error, code string) bool {
var pgErr pgdriver.Error
return errors.As(err, &pgErr) && pgErr.Field(pgFieldCode) == code
}

View File

@@ -9,6 +9,7 @@ import (
"github.com/get-drexa/drexa/internal/auth"
"github.com/get-drexa/drexa/internal/database"
"github.com/get-drexa/drexa/internal/user"
"github.com/gofiber/fiber/v2"
)
@@ -24,7 +25,8 @@ func NewServer(c ServerConfig) *fiber.App {
app := fiber.New()
db := database.NewFromPostgres(c.PostgresURL)
authService := auth.NewService(db, auth.TokenConfig{
userService := user.NewService(db)
authService := auth.NewService(db, userService, auth.TokenConfig{
Issuer: c.JWTIssuer,
Audience: c.JWTAudience,
SecretKey: c.JWTSecretKey,

View File

@@ -1,4 +1,4 @@
package auth
package password
import (
"crypto/rand"
@@ -11,6 +11,10 @@ import (
"golang.org/x/crypto/argon2"
)
// Hashed represents a securely hashed password.
// This type ensures plaintext passwords cannot be accidentally stored.
type Hashed string
// argon2id parameters
const (
memory = 64 * 1024
@@ -34,14 +38,15 @@ type argon2Hash struct {
hash []byte
}
func HashPassword(password string) (string, error) {
// Hash securely hashes a plaintext password using argon2id.
func Hash(plain string) (Hashed, error) {
salt := make([]byte, saltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("failed to generate salt: %w", err)
}
hash := argon2.IDKey(
[]byte(password),
[]byte(plain),
salt,
iterations,
memory,
@@ -52,7 +57,7 @@ func HashPassword(password string) (string, error) {
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
encodedHash := fmt.Sprintf(
encoded := fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
memory,
@@ -62,17 +67,18 @@ func HashPassword(password string) (string, error) {
b64Hash,
)
return encodedHash, nil
return Hashed(encoded), nil
}
func VerifyPassword(password, encodedHash string) (bool, error) {
h, err := decodeHash(encodedHash)
// Verify checks if a plaintext password matches a hashed password.
func Verify(plain string, hashed Hashed) (bool, error) {
h, err := decodeHash(string(hashed))
if err != nil {
return false, err
}
otherHash := argon2.IDKey(
[]byte(password),
[]byte(plain),
h.salt,
h.iterations,
h.memory,

View File

@@ -0,0 +1,36 @@
package user
import (
"fmt"
"github.com/google/uuid"
)
type NotFoundError struct {
// ID is the ID that was used to try to find the user.
// Not set if not tried.
id uuid.UUID
// Email is the email that was used to try to find the user.
// Not set if not tried.
email string
}
func newNotFoundError(id uuid.UUID, email string) *NotFoundError {
return &NotFoundError{id, email}
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("user not found: %v", e.id)
}
type AlreadyExistsError struct {
// Email is the email that was used to try to create the user.
Email string
}
func newAlreadyExistsError(email string) *AlreadyExistsError {
return &AlreadyExistsError{email}
}
func (e *AlreadyExistsError) Error() string {
return fmt.Sprintf("user with email %s already exists", e.Email)
}

View File

@@ -0,0 +1,74 @@
package user
import (
"context"
"database/sql"
"errors"
"github.com/get-drexa/drexa/internal/database"
"github.com/get-drexa/drexa/internal/password"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
type Service struct {
db *bun.DB
}
type UserRegistrationOptions struct {
Email string
DisplayName string
Password password.Hashed
}
func NewService(db *bun.DB) *Service {
return &Service{
db: db,
}
}
func (s *Service) RegisterUser(ctx context.Context, opts UserRegistrationOptions) (*User, error) {
u := User{
Email: opts.Email,
DisplayName: opts.DisplayName,
Password: opts.Password,
}
_, err := s.db.NewInsert().Model(&u).Returning("*").Exec(ctx)
if err != nil {
if database.IsUniqueViolation(err) {
return nil, newAlreadyExistsError(u.Email)
}
return nil, err
}
return &u, nil
}
func (s *Service) UserByID(ctx context.Context, id uuid.UUID) (*User, error) {
var user User
err := s.db.NewSelect().Model(&user).Where("id = ?", id).Scan(ctx)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, newNotFoundError(id, "")
}
return nil, err
}
return &user, nil
}
func (s *Service) UserByEmail(ctx context.Context, email string) (*User, error) {
var user User
err := s.db.NewSelect().Model(&user).Where("email = ?", email).Scan(ctx)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, newNotFoundError(uuid.Nil, email)
}
return nil, err
}
return &user, nil
}
func (s *Service) UserExistsByEmail(ctx context.Context, email string) (bool, error) {
return s.db.NewSelect().Model(&User{}).Where("email = ?", email).Exists(ctx)
}

View File

@@ -0,0 +1,18 @@
package user
import (
"github.com/get-drexa/drexa/internal/password"
"github.com/google/uuid"
"github.com/uptrace/bun"
)
type User struct {
bun.BaseModel `bun:"users"`
ID uuid.UUID `bun:",pk,type:uuid" json:"id"`
DisplayName string `bun:"display_name,notnull" json:"displayName"`
Email string `bun:"email,unique,notnull" json:"email"`
Password password.Hashed `bun:"password,notnull" json:"-"`
StorageUsageBytes int64 `bun:"storage_usage_bytes,notnull" json:"storageUsageBytes"`
StorageQuotaBytes int64 `bun:"storage_quota_bytes,notnull" json:"storageQuotaBytes"`
}

View File

@@ -0,0 +1,54 @@
#!/bin/bash
# Install VS Code extensions from devcontainer.json
# This script reads extensions from the single source of truth
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEVCONTAINER_JSON="$SCRIPT_DIR/../.devcontainer/devcontainer.json"
echo "Installing VS Code extensions from devcontainer.json..."
if [ ! -f "$DEVCONTAINER_JSON" ]; then
echo "Error: devcontainer.json not found at $DEVCONTAINER_JSON"
exit 1
fi
# Use Bun to parse JSON and extract extensions
EXTENSIONS=$(bun -e "
const config = await Bun.file('$DEVCONTAINER_JSON').json();
const extensions = config?.customizations?.vscode?.extensions ?? [];
console.log(extensions.join('\n'));
")
if [ -z "$EXTENSIONS" ]; then
echo "No extensions found in devcontainer.json"
exit 0
fi
# Determine which CLI to use (code-server, cursor, or code)
if command -v code-server &> /dev/null; then
CLI="code-server"
elif command -v cursor &> /dev/null; then
CLI="cursor"
elif command -v code &> /dev/null; then
CLI="code"
else
echo "Warning: No VS Code CLI found (code-server, cursor, or code)"
echo "Extensions to install:"
echo "$EXTENSIONS"
exit 0
fi
echo "Using $CLI to install extensions..."
# Install each extension
echo "$EXTENSIONS" | while read -r ext; do
if [ -n "$ext" ]; then
echo "Installing: $ext"
$CLI --install-extension "$ext" 2>/dev/null || true
fi
done
echo "Extension installation complete!"