How to set up ALLOWED_HOSTS in digital ocean - django

I successfully hosted my Django code in digital ocean with DNS.After hosted I'm getting weird output in my browser.
when I enter example.com.i'm getting the login page after logged in I'm reached my home page.all works fine.But when I enter www.example.com I'm redirected to my login page.then again I test example.com it shows homepage, not the login page. I don't know what I'm doing wrong here.
my ALLOWED_HOSTS look like this initially
ALLOWED_HOSTS = ['www.example.com','example.com']
Then I changed it to:
ALLOWED_HOSTS = ['.example.com']
last try
ALLOWED_HOSTS = [*]
I changed multiple things but the result is same.Any help really appreciate :)

Set in settings below settings then Django will redirect user to automatic on www.example.com
PREPEND_WWW = True
ALLOWED_HOSTS = ['www.example.com']
If user enter http://example.com then Django will redirect http://www.example.com

In settings.py,
SESSION_COOKIE_DOMAIN = '.example.com'
ALLOWED_HOSTS = ['.example.com']
But i recommend to do like non-www -> www or www->non-www permanent redirect.It can be done webserver itself before touching django.

Related

There is no cookie at all in my Next.Js frontend

I made Django Backend. and Next.js Frontend. There is cookie which has _ga, csrftoken when I tested on local server 127.0.0.1.
BUT, there is no cookie at all on my production (which has different domain backend and frontend).
I guessed that everything happened because I used different domain when production. Here is some django settings.py I have
ALLOWED_HOSTS = [
"127.0.0.1",
"localhost",
"BACKENDURL",
"FRONTENDURL",
"*.FRONTENDURL",
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = [
"http://127.0.0.1:3000",
"http://localhost:3000",
"https://*.frontendURL",
"https://FRONTENDURL",
]
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
For the future visitors...
I figured out what I was wrong.
In Development Settings,
I use same domain
[127.0.0.1:3000] as frontend (Next.JS)
[127.0.0.1:8000] as backend (Django)
But, In Production Settings,
I use different domain
[frontend.com] as frontend
[backend.com] as backend
Which leads "cross-site" error on request/response.
I also found that there is no cookie in my production
due to I use different domain in production
Different domain cannot use same cookie => No Cookie on the frontend.
Thus, I have to set the domain same on backend and frontend in 'hosting service site'
www -> frontendurl
backend -> backendurl
=> Then I can get the csrftoken and sessionid when login.
Also, I made my settings.py in django project including...
SESSION_COOKIE_DOMAIN = ".mydomain"
CSRF_COOKIE_DOMAIN = ".mydomain"
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
I recognize that CORS_ALLOW_ALL_ORIGINS leads some danger...
I set it just to confirm that everything is fine.
Later on, In production, change it into
CORS_ALLOWED_ORIGINS = [...]
Hope my answer helped someone.
Happy Hacking my friends. Good Luck!

Login not working in django when using rewrites from firebase hosting to cloud run

Current Setup: I've got a Django application behind gunicorn running on Cloud Run. Since the region it is deployed in does not support Custom Domains, I have a firebase hosting setup with the following code:
{
"hosting": {
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [{
"source": "/**",
"run": {
"serviceId": "website",
"region": "ap-south1"
}
}]
}
}
The relevant settings in settings.py:
CSRF_TRUSTED_ORIGINS = ['.<domain>.com']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
The problem: However, the login form on /admin does not work if I access the site using my domain name https://doman.com/admin even though it works fine if I use the Cloud Run endpoint https://endpoint-uw.a.run.app.
Faulty behaviour: When accessing it from my domain, the login page shows up, I enter my credentials and log in, it adds the relevant cookies to my browser but then it redirects me back to the login page.
Could it be that since the URL is being rewritten by firebase django is expecting a cookie from uw.a.run.app? I tried adding the setting SESSION_COOKIE_DOMAIN = '.<domain>.com' but that did not fix it either, it just made the Cloud Run endpoint stop working as well.
Any advice on how to fix this or how to diagnose what is going wrong would be much appreciated, thanks!
The relevant settings in settings.py:
SESSION_COOKIE_NAME = "__session"
as firebase send cookie in the name "__session"

django-userena: how to activate account for local development?

I just installed django-userena for my accounts management.
Because I'm still at the stage of basic development and I don't have a public domain name. I'm using gmail for my EMAIL_HOST for testing. The default setting from django-userena is using example.com for demo. How can I switch it to my local domain, i.e. 127.0.0.1:8000, so I can make some dummy "users" activated and test it for my other apps?
Thank you!!!
EDITED:
Because I don't have a domain name, when the user click the activation email in his email(e.g. Gmail), it's directed to http://example.com/accounts/activate/hash_as_placeholder/, so the result is that the user can't activate his account. How can I let them activate their accounts on a local domain?
Try this. Add this lines to settings.py
LOGIN_REDIRECT_URL = '/accounts/%(username)s/'
LOGIN_URL = '/accounts/signin/'
LOGOUT_URL = '/accounts/signout/'
and about email configuration, i have issues with gmail if i send a lot of mails.
So for testing purposes i have this in my settings:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #printed in console
All emails will be printed in console.
EDITED:
Create new file initial_data.json in your project root with
[{
"pk": 1,
"model": "sites.site",
"fields": {
"name": "127.0.0.1:8000",
"domain":"127.0.0.1:8000"
}
}]
and run syncdb of course.
This will change your example.com to 127.0.0.1:8000

How to make game use https when played via facebook and http when played from other domain

Our users play our Django game directly via our domain, cnamed to herokuapp.com. We request our assets via http.
We want to add our game to facebook, which requires using https. Heroku can handle this.
Using https requests: our game works on facebook but fails to load assets when accessed via our cnamed domain.
Can we make our game use https when played via facebook and http when played from our domain? What code must we add to settings.py?
We've tried this code in settings.py but it didn't work
Option 1:
import socket
if socket.gethostname().startswith('app'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
Option 2:
import socket
if socket.gethostname().startswith('edge'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
You could use protocol relative urls to save yourself from the pain of worrying about the protocol to use.
So the settings would look like:
STATIC_URL = "//d******1.cloudfront.net/"
and you can safely get rid of all the computation logic in your code snippet.

How to enable https in Django-auth generated pages?

Using the Django-auth application (Django version 1.3), I want to have my login page go to https://mysite.com/login/. Currently, I'm using:
# urls.py
from django.contrib.auth.views import login
urlpatterns = patterns('', url(r'^login/$', login, name='login-view'),)
# navbar.html
<li id="nav-login"><a href="{% url login-view %}" ><b>Login</b></a></li>
which works nicely, but goes to http://mysite.com/login/.
Is there some way to tell Django-auth what prefix (https) to use, when it reverses the view name? I've read the entire manual page, and haven't found anything that covers it. Or maybe some way to tell the url tag to go to https?
Or is the only option to specify the entire URL manually? I hope not :) And given how powerful Django has been so far, I can't believe it wouldn't have that ability - I must be overlooking it. :)
Set OS environmental variable HTTPS to on
You need to enable the OS environmental variable HTTPS to 'on' so django will prepend https to fully generated links (e.g., like with HttpRedirectRequests). If you are using mod_wsgi, you can add the line:
os.environ['HTTPS'] = "on"
to your wsgi script. You can see the need for this by reading django/http/__init__.py:
def build_absolute_uri(self, location=None):
"""
Builds an absolute URI from the location and the variables available in
this request. If no location is specified, the absolute URI is built on
``request.get_full_path()``.
"""
if not location:
location = self.get_full_path()
if not absolute_http_url_re.match(location):
current_uri = '%s://%s%s' % (self.is_secure() and 'https' or 'http',
self.get_host(), self.path)
location = urljoin(current_uri, location)
return iri_to_uri(location)
def is_secure(self):
return os.environ.get("HTTPS") == "on"
Secure your cookies
In settings.py put the lines
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
and cookies will only be sent via HTTPS connections. Additionally, you probably also want SESSION_EXPIRE_AT_BROWSER_CLOSE=True. Note if you are using older versions of django (less than 1.4), there isn't a setting for secure CSRF cookies. As a quick fix, you can just have CSRF cookie be secure when the session cookie is secure (SESSION_COOKIE_SECURE=True), by editing django/middleware/csrf.py:
class CsrfViewMiddleware(object):
...
def process_response(self, request, response):
...
response.set_cookie(settings.CSRF_COOKIE_NAME,
request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52,
domain=settings.CSRF_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None)
Direct HTTP requests to HTTPS in the webserver
Next you want a rewrite rule that redirects http requests to https, e.g., in nginx
server {
listen 80;
rewrite ^(.*) https://$host$1 permanent;
}
Django's reverse function and url template tags only return relative links; so if you are on an https page your links will keep you on the https site.
As seen in other StackOverflow questions, you could implement middleware that would automatically redirect the login page to a secure version.
If you are really serious about security, you should probably migrate the entire website to SSL. From the EFF's How to Deploy HTTPS Correctly:
You must serve the entire application domain over HTTPS. Redirect HTTP requests with HTTP 301 or 302 responses to the equivalent HTTPS resource.
Some site operators provide only the login page over HTTPS, on the theory that only the user’s password is sensitive. These sites’ users are vulnerable to passive and active attack.