Inadvisable or not, my Django site assigns each user a page at the root, e.g., /rgov
.
I use a character set whitelist, so creating index.html
or something nefarious should be prevented. My URL configuration also routes user pages last, so it should not be possible to hijack /admin
or anything else by registering the corresponding name.
However, I'd like to prevent users from registering admin
, since their page will be broken.
(Similar question, which does not have an ideal solution, as the following part describes.)
Here is my attempt:
def is_reserved(username):
r = urls.resolvers.get_resolver('mysite.systemurls')
hit = False
for path in ('/{}', '/{}/'):
try:
r.resolve(path.format(username))
hit = True
break
except urls.exceptions.Resolver404:
continue
return hit
Here, the mysite.systemurls
module defines every URL pattern except for the user pages.
This does prevent picking the username admin
because there is a route defined for /admin/
. But it does not prevent api
, because while there is /api/foo/bar
, there is no route for /api/
.
Is there a way to test if there is a route that is a suffix of /api/
(for example)? Since URL patterns are regular expressions, maybe it's not so easy, but in a theoretical sense it should be possible.