An open source, non-profit web search engine
Allow login with email and password (no username)
Daoud Clarkeeb21d46f4b60
diff --git a/mwmbl/api.py b/mwmbl/api.pyindex 9054a71..b56fafe 100644--- a/mwmbl/api.py+++ b/mwmbl/api.py@@ -14,16 +14,48 @@ JWT token endpoints (from NinjaJWTDefaultController) are also registered here,typically at /api/v1/platform/token/pair, /api/v1/platform/token/refresh, etc."""-from ninja_extra import NinjaExtraAPI-from ninja_jwt.controller import NinjaJWTDefaultController+from ninja import Field+from ninja_extra import NinjaExtraAPI, api_controller, http_post+from ninja_extra.permissions import AllowAny+from ninja_jwt.controller import TokenVerificationController, TokenObtainPairController+from ninja_jwt.schema import TokenObtainPairInputSchema+from ninja_jwt.schema_control import SchemaControl+from ninja_jwt.settings import api_settingsfrom mwmbl.exceptions import InvalidRequestfrom scalar_ninja import ScalarViewerfrom scalar_ninja.scalar_ninja import AgentConfig-# Patch the JWT controller to restore its original path and use a capitalised tag-NinjaJWTDefaultController.get_api_controller().prefix = "/platform/token"-NinjaJWTDefaultController.get_api_controller().tags = ["Authentication"]+_schema = SchemaControl(api_settings)+++class MwmblTokenObtainSchema(TokenObtainPairInputSchema):+ username: str = Field(description="Your username or email address.")+ password: str = Field(description="Your password.")+++@api_controller("/platform/token", permissions=[AllowAny], tags=["Authentication"], auth=None)+class MwmblTokenController(TokenVerificationController, TokenObtainPairController):+ """JWT token endpoints for authentication."""++ auto_import = False++ @http_post(+ "/pair",+ response=MwmblTokenObtainSchema.get_response_schema(),+ url_name="token_obtain_pair",+ operation_id="token_obtain_pair",+ summary="Obtain JWT token pair",+ description=(+ "Exchange credentials for a JWT access/refresh token pair. "+ "The `username` field accepts either a **username** or an **email address**. "+ "Include the returned `access` token in the `Authorization: Bearer <token>` "+ "header on subsequent requests."+ ),+ )+ def obtain_token(self, user_token: MwmblTokenObtainSchema):+ user_token.check_user_authentication_rule()+ return user_token.to_response_schema()api = NinjaExtraAPI(title="Mwmbl API",@@ -35,6 +67,7 @@ api = NinjaExtraAPI("## Authentication\n\n""Most write endpoints require a JWT bearer token. ""Obtain a token pair by posting your credentials to `/api/v1/platform/token/pair`. "+ "You can log in with either your **username** or your **email address**. ""Include the access token in the `Authorization: Bearer <token>` header.\n\n""Some crawler endpoints use a separate API key passed in the request body."),@@ -51,7 +84,7 @@ api = NinjaExtraAPI()# Register JWT token endpoints (/platform/token/pair, /platform/token/refresh, /platform/token/verify)-api.register_controllers(NinjaJWTDefaultController)+api.register_controllers(MwmblTokenController)# Register the shared InvalidRequest exception handlerdiff --git a/mwmbl/auth.py b/mwmbl/auth.pyindex 8055a84..0dd3f6c 100644--- a/mwmbl/auth.py+++ b/mwmbl/auth.py@@ -11,3 +11,37 @@ def require_email_confirmation(user):return Falsereturn has_verified_email(user)+++class UsernameOrEmailBackend:+ """+ Auth backend that accepts either username or email in the username field.+ Used by the JWT token endpoint, which always passes credentials as username+password.+ """++ def authenticate(self, request, username=None, password=None, **kwargs):+ from django.contrib.auth import get_user_model+ UserModel = get_user_model()++ if not username or not password:+ return None++ try:+ user = UserModel.objects.get(username=username)+ except UserModel.DoesNotExist:+ try:+ user = UserModel.objects.get(email=username)+ except UserModel.DoesNotExist:+ return None++ if user.check_password(password):+ return user+ return None++ def get_user(self, user_id):+ from django.contrib.auth import get_user_model+ UserModel = get_user_model()+ try:+ return UserModel.objects.get(pk=user_id)+ except UserModel.DoesNotExist:+ return Nonediff --git a/mwmbl/models.py b/mwmbl/models.pyindex 8ed692e..f4c25f3 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -1,3 +1,4 @@+import randomimport secretsfrom django.contrib.postgres.fields import ArrayField@@ -7,6 +8,238 @@ from django.utils import timezonefrom ninja import ModelSchemafrom ninja.orm import create_schema+_ADJECTIVES = [+ # A+ "able", "abiding", "agile", "airy", "alabaster", "alert", "alpine", "amber",+ "ample", "ancient", "ardent", "arctic", "arid", "ashen", "astral", "astute",+ "atomic", "auburn", "august", "avid", "azure",+ # B+ "balmy", "bare", "benevolent", "blazed", "blazing", "blithe", "blissful",+ "blooming", "blushing", "bold", "boreal", "boundless", "brave", "breezy",+ "bright", "brisk", "broad", "bronze", "buoyant", "burnished",+ # C+ "calm", "candid", "carefree", "caramel", "cedar", "celestial", "cerulean",+ "chatty", "cheerful", "chestnut", "chill", "civic", "clear", "clever",+ "clover", "cloudy", "coastal", "cobalt", "comet", "cool", "copper", "coral",+ "cordial", "cosmic", "courageous", "cozy", "creative", "crisp", "crystal",+ "curly", "cyan",+ # D+ "dainty", "dapper", "daring", "dark", "dashing", "dauntless", "dawn",+ "decisive", "deep", "devoted", "dewy", "diligent", "dim", "drifting",+ "durable", "dusty", "dynamic",+ # E+ "eager", "early", "earnest", "earthy", "easy", "ebony", "effervescent",+ "electric", "elegant", "eloquent", "emerald", "empty", "enduring", "endless",+ "energetic", "enlightened", "epic", "eternal", "everlasting", "even", "exact",+ "exquisite",+ # F+ "fabled", "fair", "faithful", "famous", "fancy", "far", "farsighted", "fast",+ "felicitous", "fern", "fervent", "festive", "fierce", "fiery", "fine", "firm",+ "first", "flexible", "flint", "floral", "flourishing", "flowing", "foggy",+ "fond", "forest", "forward", "fragrant", "frank", "free", "fresh", "frosty",+ "frozen", "full",+ # G+ "gallant", "gentle", "genuine", "gifted", "gilded", "glacial", "glad",+ "gleaming", "glorious", "glowing", "golden", "good", "graceful", "gracious",+ "grand", "granite", "grateful", "great", "green", "grey", "grounded",+ # H+ "halcyon", "hardy", "harmonious", "hazy", "hearty", "heroic", "high",+ "hollow", "honest", "hopeful", "humble",+ # I+ "icy", "idle", "idyllic", "illumined", "imaginative", "immense", "impeccable",+ "indigo", "infinite", "ingenious", "inland", "inner", "inspired", "intrepid",+ "inventive", "invincible", "iron", "ivory",+ # J+ "jade", "jolly", "jovial", "joyful", "joyous", "jubilant", "judicious", "just",+ # K+ "keen", "kind", "kindhearted", "kinetic",+ # L+ "lambent", "large", "lasting", "lavender", "leafy", "lean", "legendary",+ "lemon", "level", "light", "lively", "lone", "long", "loyal", "lucid",+ "lucky", "luminous", "lunar", "lush", "lyric",+ # M+ "magic", "magnanimous", "majestic", "maple", "marble", "mature", "measured",+ "meditative", "mellifluous", "mellow", "merciful", "methodical", "mighty",+ "mild", "mindful", "misty", "modest", "moonlit", "mossy", "mountainous", "muted",+ # N+ "narrow", "natural", "neat", "nimble", "noble", "nocturnal", "nordic",+ "north", "nurturing",+ # O+ "oak", "observant", "obsidian", "oceanic", "olive", "open", "opulent",+ "optimistic", "orange", "orderly", "outer",+ # P+ "pale", "passionate", "patient", "peaceful", "pearly", "perennial",+ "persevering", "petal", "pine", "pioneering", "plain", "playful", "poised",+ "polar", "polished", "pragmatic", "principled", "promising", "proud", "pure",+ "purple", "purposeful",+ # Q+ "quiet", "quickened", "quintessential",+ # R+ "radiant", "rapid", "rare", "ready", "receptive", "reflective", "refreshing",+ "regal", "reliable", "resilient", "resolute", "resourceful", "respectful",+ "responsive", "rich", "righteous", "roaming", "robust", "rooted", "rosy",+ "rough", "round", "royal", "ruby", "rugged", "running", "rustic", "rustling",+ # S+ "sacred", "sage", "sandy", "sapphire", "scholarly", "seasoned", "serene",+ "seraphic", "sharp", "shining", "silent", "silken", "silver", "simple",+ "sincere", "skillful", "sleek", "slender", "slow", "smart", "smooth", "snowy",+ "sociable", "solar", "solemn", "solid", "sonic", "soulful", "sovereign",+ "spirited", "steadfast", "sterling", "still", "stoic", "stormy", "stout",+ "strategic", "strong", "sturdy", "sublime", "subtle", "sunny", "supernal",+ "supple", "supportive", "swift",+ # T+ "talented", "tall", "tawny", "tender", "tenacious", "thoughtful", "thriving",+ "tidal", "tidy", "timeless", "timely", "tireless", "tranquil", "transparent",+ "triumphant", "true", "trusty", "trusting", "twilight",+ # U+ "ultra", "unassuming", "undaunted", "unwavering", "upbeat", "uplifting",+ "unyielding", "upright",+ # V+ "valiant", "vast", "velvet", "venerable", "venturous", "verdant", "vernal",+ "versatile", "vibrant", "vigilant", "visionary", "vital", "vivacious", "vivid",+ # W+ "warm", "watchful", "wavy", "whimsical", "wholesome", "willing", "windswept",+ "wise", "witty", "wondrous", "worthy", "woven",+ # X Y Z+ "xenial", "xeric", "yielding", "young", "youthful", "zealous", "zenith",+ "zephyr", "zestful", "zippy",+ # extras to reach 500+ "affable", "aloft", "animated", "artful", "balanced", "bountiful", "bracing",+ "candent", "capacious", "certain", "clean", "collected", "composed", "confident",+ "conscientious", "considerate", "constant", "deft", "deliberate", "dependable",+ "dignified", "discerning", "effulgent", "elevated", "eminent", "endeared",+ "equable", "established", "expansive", "expressive", "felicific", "forthright",+ "fulsome", "generative", "graced", "hallowed", "idiomatic", "imaginable",+ "immovable", "incisive", "inquisitive", "insightful", "integral", "intuitive",+ "jaunty", "knowing", "limber", "limpid", "lofty", "manifest",+ "masterful", "meticulous", "musing", "nascent", "nuanced",+ "openhearted", "ordinate", "pacific", "pellucid", "perceptive", "pious",+ "plentiful", "precise", "pristine", "progressing",+ "reasoned", "refined", "reposed", "revered", "rhapsodic", "sapient",+ "sanguine", "settled", "sheer", "sideral", "spiraling",+ "stately", "stellar", "temperate", "thorough", "tonal",+ "torchlit", "tractable", "transcendent", "unbounded", "unfailing", "unfettered",+]++_NOUNS = [+ # A+ "adder", "alder", "algae", "aloe", "anchor", "antler", "anvil", "apex",+ "apple", "arch", "arrow", "ash", "aspen", "atlas", "atoll", "aurora",+ "autumn", "avalanche", "axe",+ # B+ "badger", "bark", "barn", "basalt", "basin", "bay", "beacon", "bear",+ "beaver", "beech", "bell", "berry", "birch", "bison", "blade", "bloom",+ "blossom", "bluebell", "bluff", "boar", "bog", "boulder", "bough", "bramble",+ "brant", "bream", "brine", "brook", "buck", "bud", "burrow", "buttercup",+ "butte",+ # C+ "canoe", "canopy", "canyon", "cape", "cardinal", "carp", "catfish", "cave",+ "cedar", "channel", "charcoal", "chestnut", "chisel", "chough", "cicada",+ "cinder", "cirque", "cirrus", "clam", "cliff", "clover", "cobble", "cobalt",+ "cockle", "col", "comet", "compass", "condor", "coral", "cormorant", "corrie",+ "cove", "coyote", "crane", "crater", "creek", "crest", "crocus", "crow",+ "crystal", "curlew", "current", "cypress",+ # D+ "dale", "darter", "dawn", "deer", "delta", "dew", "dipper", "dock",+ "dolphin", "dormouse", "dotterel", "dove", "dragonfly", "drumlin", "dunlin",+ "dune", "dyke",+ # E+ "eagle", "echo", "eel", "egret", "elder", "elk", "elm", "ember",+ "escarpment", "estuary",+ # F+ "falcon", "fawn", "fern", "field", "fiord", "firecrest", "finch", "fir",+ "fjord", "flame", "flint", "flood", "flora", "fluke", "flycatcher", "foam",+ "fog", "forest", "forge", "fossil", "fox", "frost", "fulmar",+ # G+ "gale", "gannet", "garganey", "garnet", "geyser", "glacier", "glade",+ "glen", "godwit", "goldcrest", "goldfinch", "goosander", "gorge", "goshawk",+ "granite", "gravel", "grove", "grouse", "guillemot", "gulch", "gull", "gust",+ # H+ "hamster", "hare", "harrier", "hartebeest", "hawk", "hazel", "heath",+ "hedgehog", "heron", "hill", "hillside", "holly", "hoopoe", "horizon",+ "hornet",+ # I+ "ibex", "ibis", "inlet", "iris", "island", "ivory",+ # J+ "jackal", "jackdaw", "jasper", "jay", "juniper",+ # K+ "kelp", "kestrel", "kingfisher", "kite", "kiwi", "knoll", "knot",+ # L+ "lagoon", "lake", "lapwing", "larch", "lark", "lava", "leaf", "ledge",+ "lemur", "leveret", "lichen", "limestone", "linden", "linnet", "lion",+ "loam", "loess", "locust", "lodge", "loon", "lotus", "lynx",+ # M+ "mackerel", "magpie", "mallard", "maple", "marl", "marsh", "martin",+ "meadow", "merganser", "merlin", "mesa", "midstream", "milfoil", "mink",+ "mist", "moorland", "moose", "moss", "moth", "mountain", "mudflat",+ "mudstone", "muskrat",+ # N+ "narwhal", "needle", "newt", "nightingale", "nightjar", "noctule", "north",+ "nutmeg", "nuthatch",+ # O+ "oak", "opal", "orca", "osprey", "otter", "outcrop", "owl", "oyster",+ "oystercatcher",+ # P+ "partridge", "pass", "pasture", "peak", "peat", "pebble", "peewit",+ "pelican", "pennant", "perch", "peregrine", "petal", "pheasant", "pigeon",+ "pine", "pintail", "pipit", "plover", "plume", "pochard", "polecat",+ "pond", "poplar", "porcupine", "prairie", "ptarmigan", "puffin",+ # Q+ "quartz", "quill",+ # R+ "rabbit", "raven", "reed", "reedbed", "reef", "ridge", "rift", "rill",+ "ringlet", "ripple", "robin", "rock", "rockpool", "roe", "roost",+ "rosefinch", "root", "rowan", "runnel", "rush", "rushes",+ # S+ "sage", "salmon", "sandbar", "sandpiper", "sandstone", "sapphire", "scree",+ "seabird", "seagrass", "sedge", "serin", "sett", "shale", "shearwater",+ "shoal", "shore", "shoveler", "shrew", "shrike", "sierra", "siskin",+ "skimmer", "skua", "skylark", "slate", "sluice", "smew", "snipe",+ "snowdrop", "snowfield", "snout", "sora", "sorrel", "sparrow", "spire",+ "spoonbill", "spruce", "squall", "squirrel", "stag", "starling", "stem",+ "steppe", "stoat", "stone", "stonefly", "stork", "storm", "stream",+ "stubble", "summit", "sundew", "sunfish", "swallow", "swamp", "swan",+ "swift", "sycamore",+ # T+ "talon", "tanager", "tarpon", "teal", "tern", "thistle", "thorn",+ "thornbill", "thicket", "thrush", "tide", "timber", "titlark", "toad",+ "torchwood", "torrent", "trail", "treecreeper", "trogon", "trout", "tuatara",+ "tumulus", "tundra", "turnstone", "turtle", "twite",+ # U+ "upland",+ # V+ "vale", "valley", "veery", "verdure", "vetch", "viburnum", "vireo",+ "viper", "vixen", "vole",+ # W+ "wader", "wagtail", "warbler", "waterfowl", "watershed", "wave", "waxwing",+ "weasel", "weir", "wheatear", "whinchat", "whitethroat", "wigeon", "wildcat",+ "willow", "wolf", "woodcock", "woodland", "woodpecker", "wormwood", "wren",+ "wryneck",+ # Y Z+ "yarrow", "yellowhammer", "yew", "zander", "zinnia", "zorilla",+ # extras to reach 500+ "acorn", "agate", "albatross", "alcove", "almond", "alp", "amaranth",+ "amethyst", "anemone", "antelope", "arroyo", "azalea", "barnacle", "bayou",+ "blizzard", "bracken", "brushwood", "buffalo",+ "bulrush", "bunting", "bushtit", "buzzard", "capercaillie", "caribou",+ "catkin", "chaffinch", "chalcedony", "chamomile", "cheetah", "cinnabar",+ "cistus", "clough", "coho", "columbine", "coppice", "crag", "crake",+ "crossbill", "crowberry", "dace", "daisy", "damselfly", "dandelion",+ "dewdrop", "dhole", "dingo", "dunock", "earthworm", "echidna", "ermine",+ "esker", "fen", "flounder", "flyway", "forb", "gallinule", "garfish",+ "gecko", "geode", "gerbil", "gibbon", "ginkgo", "gloaming", "glowworm",+ "gneiss", "gnu",+]+++def generate_username():+ for _ in range(10):+ candidate = f"{random.choice(_ADJECTIVES)}_{random.choice(_NOUNS)}_{random.randint(100, 999)}"+ if not MwmblUser.objects.filter(username=candidate).exists():+ return candidate+ # Extremely unlikely fallback+ return f"user_{secrets.token_hex(6)}"+class MwmblUser(AbstractUser):class Tier(models.TextChoices):diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex fbed683..21bcc62 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -10,7 +10,7 @@ from polar_sdk import Polarfrom polar_sdk.webhooks import validate_event, WebhookVerificationErrorfrom mwmbl.exceptions import InvalidRequest-from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling+from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, generate_usernamefrom mwmbl.platform.schemas import (Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory,@@ -32,16 +32,23 @@ def check_email_verified(request):'/register',summary="Register a new user",description=(- "Create a new Mwmbl user account. A confirmation email will be sent to the provided "- "address. The account cannot be used until the email is confirmed via the "- "`/platform/confirm-email` endpoint."+ "Create a new Mwmbl user account. Only `email` and `password` are required. "+ "`username` is optional — if omitted, a unique name is generated automatically in the "+ "form `adjective_noun_NNN` (e.g. `swift_falcon_379`). "+ "A confirmation email will be sent to the provided address; the account cannot be used "+ "until the email is confirmed via the `/platform/confirm-email` endpoint. "+ "The assigned username is returned in the response."),)def register(request, registration: Registration):- if MwmblUser.objects.filter(username=registration.username).exists():+ if MwmblUser.objects.filter(email=registration.email).exists():+ raise InvalidRequest("Email already registered")++ username = registration.username or generate_username()+ if registration.username and MwmblUser.objects.filter(username=registration.username).exists():raise InvalidRequest("Username already exists")- user = MwmblUser(username=registration.username, email=registration.email)+ user = MwmblUser(username=username, email=registration.email)user.set_password(registration.password)user.save()@@ -50,7 +57,7 @@ def register(request, registration: Registration):return {"status": "ok",- "username": registration.username,+ "username": username,"message": "User registered successfully. Check your email for confirmation."}@@ -60,7 +67,9 @@ def register(request, registration: Registration):summary="Confirm email address",description=("Confirm a user's email address using the key sent in the confirmation email. "- "The `key`, `email`, and `username` must all match the values from the confirmation email."+ "Only `email` and `key` are required. The `username` field is accepted for backwards "+ "compatibility but is ignored. "+ "The confirmed account's username is returned in the response."),)def confirm_email(request, confirm: ConfirmEmail):@@ -69,18 +78,14 @@ def confirm_email(request, confirm: ConfirmEmail):raise InvalidRequest("Invalid confirmation key")if confirmation.email_address.email != confirm.email:- raise InvalidRequest("Invalid username or email")-- user = MwmblUser.objects.get(username=confirm.username)- if user.email != confirm.email:- raise InvalidRequest("Invalid username or email")+ raise InvalidRequest("Invalid email or key")adapter = get_adapter()adapter.confirm_email(request, confirmation.email_address)return {"status": "ok",- "username": confirm.username,+ "username": confirmation.email_address.user.username,"message": "Email confirmed successfully."}diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex 062aff3..3d95a6c 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -77,15 +77,24 @@ class ApiKeyListItem(Schema):class Registration(Schema):- email: str- username: str- password: str+ email: str = Field(description="Email address for the new account. Must be unique.")+ password: str = Field(description="Password for the new account.")+ username: Optional[str] = Field(+ default=None,+ description=(+ "Optional username. If omitted, one is generated automatically in the form "+ "`adjective_noun_NNN` (e.g. `swift_falcon_379`). Must be unique if provided."+ ),+ )class ConfirmEmail(Schema):- username: str- email: str- key: str+ email: str = Field(description="Email address to confirm.")+ key: str = Field(description="Confirmation key from the verification email.")+ username: Optional[str] = Field(+ default=None,+ description="Deprecated — ignored. Accepted for backwards compatibility only.",+ )class DomainSubmissionSchema(ModelSchema):diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex d8c1e0a..d766a69 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -128,10 +128,13 @@ DJANGO_VITE_DEV_MODE = FalseDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'AUTHENTICATION_BACKENDS = [- # Needed to login by username in Django admin, regardless of `allauth`+ # Accepts username or email in the username field — used by the JWT token endpoint+ 'mwmbl.auth.UsernameOrEmailBackend',++ # Needed for Django's permission system (has_perm, has_module_perms) used by the admin'django.contrib.auth.backends.ModelBackend',- # `allauth` specific authentication methods, such as login by email+ # allauth backend for allauth's own views (social auth, email confirmation, etc.)'allauth.account.auth_backends.AuthenticationBackend',]@@ -141,6 +144,8 @@ AUTH_USER_MODEL = "mwmbl.MwmblUser"ACCOUNT_EMAIL_REQUIRED = TrueACCOUNT_EMAIL_VERIFICATION = "mandatory"+ACCOUNT_USERNAME_REQUIRED = False+ACCOUNT_AUTHENTICATION_METHOD = "username_email"DEFAULT_FROM_EMAIL = "[email protected]"