django all-auth authenticating via twitch - python

I am trying to authenticate a user from twitch Auth using Django and reactjs. I am able to authorize the user and store its details in the Django admin from backend but not sure how to do it from reactjs.
What I tried so far:
Following the documents from here: https://django-allauth.readthedocs.io/en/latest/installation.html
I configured everything as:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.twitch',
'django_extensions',
'users.apps.UsersConfig',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = app-name.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sphinx.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
I also registered the social application in the Django admin.
When I hit:
http://localhost:8000/accounts/twitch/login/
It takes me to the twitch authorization page, Which when I click on "Authorize" saves the user details in the Django admin redirects me back to the url:
http://localhost:8000/accounts/profile/
The problem is I need to make sure the LOGIN_REDIRECT_URL page '/accounts/profile/' has some authentication so only the logged in user can access it and to display the username of that user.
How do I authenticate the user? Like how do I send the access_token to the front-end reactjs and verify the user?

If you're using a custom auth schema, you can use the #login_required decorator before the view.

Related

Application labels aren't unique, duplicates: staticfiles

I'm having trouble figuring out what I'm duplicating here. I'm trying to migrate my files so I can deploy on Heroku. It says that "staticfiles" is duplicated, but I can't see where the conflict is. Does migration need to be done in order to deploy? or is there something wrong with my database?
import dj_database_url
import os
ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com']
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'wiki_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.postgres',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'coding_dojo_final_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'coding_dojo_final_project.wsgi.application'
...
WHITENOISE_USE_FINDERS = True
...
STATIC_URL = '/static/'
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
You need to set a static root which is where Django compiles the static files for serving in production when you run python manage.py collectstatic. The name must be different than the location of your static files in your project.
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
See the docs for more info.

Django app do not render html templates (no requirements.txt)

I am working with this app, I have tried running the app using the command provided in the doc then I had to install both Django and requests but now the template view do not render at all, it seems it's interpreted as text
What do I have to install? Or this app is not working properly? I am not sure why there's no requirements.txt
Below is the settings file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxx'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Company.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
There's also a file named urls.py that contains the path I am supposed to work with
urlpatterns = [
url(r'^payment_request/',Payment_Request),
url(r'^payment_response/',Payment_Response),
url(r'^payment_receipt/',Payment_Receipt),
url(r'^admin/', admin.site.urls),
]
Only admin is working, Payment_Receipt and Payment_Response shows error but that's normal because they should get some data to process before
I also I'd like to mention that in the docs they ask to generate some hash sequence, is that mandatory to simply shows the htm template? I have never done this before
Create SHA256 Hash with below mention Parameters.
Merchant needs to form the below hash sequence before posting the transaction.
Below is the SHA 256 Hash creation format : Hash Sequence :-
trackid|Terminalid|password|secret_key|amount|currency_code
There are two ways this could happen:
Content type is wrong - Open up the Chrome Developer Console, Go to Network tab, reload the page and look at the content-type header in the request. Is it text/html? If it's something else, Chrome won't render it
The HTML is escaped - Right click on the page and click View Source. Is it different from the HTML you see in the page?
You have to add the name of the app in settings.py in the list INSTALLED_APPS
INSTALLED_APPS = [
"appname",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Can django webapp and django-rest-framework live together?

I have a Django WebApp to administrate certain things of my business. It's currently using Django 1.5.5, but I just migrated the code to Django 1.11.
The thing is that we are developing another apps using other technologies, and due to all my information is in the Django app, I decided to add Django Rest Framework to my existing Django Webapp. All ok so far, beautiful, API with Token access... happy...
But, then I realized that on PROD env, I've ALLOWED_HOST setting. :(. I added that line in my devbox, and the happiness end.
I tried adding CORS support using django-cors-headers, but, so far, I've not successful.
So, to avoid wasting time, I want to ask to people that knows more than me about it, if the Django App and the DRF API can live together, without removing the ALLOWED_HOST setting or setting it as ALLOWED_HOSTS = ['*'].
Thanks in advance!
UPDATE
My settings.py file looks like this:
# Django settings for dojosite project.
# -*- coding: utf-8 -*-
import os
import datetime
DEBUG = True
ALLOWED_HOSTS = ['www.myapp.com']
...
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(os.path.join(ROOT_PATH, 'templates'),)],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
],
},
},
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'django.contrib.humanize',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'myapp',
)
...
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions',
]
}
# JWT settings
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_AUTH_COOKIE': None,
}
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
That configuration is causing that ALLOWED_HOSTS is applied to the WebApp urls and also to the API URLs.
UPDATE 2
Something I didn't say, is that I want that API public. I mean, let's suppose that I didn't know which hosts will invoke my API. So, what I want to do is:
WebApp: should be just called from known hosts (ALLOWED_HOSTS should be applied)
API: can be called from unknown hosts (ALLOWED_HOSTS control should not be applied here).
Is this possible? How can I achieve this?
Thanks!
Yes you can use Django Rest Framework with your Django webapp with no problem at all. Moving to cors part you should first install pip install django-cors-headers
then add corsheaders to installed apps
INSTALLED_APPS = (
...
'corsheaders',
...
)
Add middleware properly in settings.py
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
... ]
lastly you should do in settings.py as you are allowing every host
CORS_ORIGIN_ALLOW_ALL = True
else make the whitelist
CORS_ORIGIN_WHITELIST = (
'hostname.example.com',
'localhost:8000',
'127.0.0.1:9000'
)

CSRF error on djangorestfull while ajaxing for /api-auth/login

I'm in server side of web project that use djangorestfull. Our UI team runs UI with gulp on port 3000 and Django server runs on port 8000. For login we use /api-auth/login url for ajax. Answer of option method from /api-auth/login contains csrftoken and a form but post method (that contains username and password) faces with CSRF error. How can I check the source of this problem? Is it in server side or the token won't send with post method?
Here is my setting.py:
REQUIRED_APPS = [
'django_admin_bootstrapped',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'rest_framework',
]
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
and urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('User.urls', namespace='User')),
url(r'^schedule/', include('Schedule.urls', namespace='Schedule')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
The problem seems to come from the UI team. Chances are high they are not including the CSRF token in the POST request. Kindly confirm that. Here are some docs from Django on how to add the token. https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax

No module named rest_authusers error

I am in the process of adding allauth to my project, following this tutorial:
http://django-allauth.readthedocs.org/en/latest/installation.html
When trying to make migrations I get the following error:
"ImportError: No module named rest_authusers"
My settings.py is as follows:
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth'
'users',
# The Django sites framework is required
'django.contrib.sites',
'allauth.socialaccount.providers.facebook',
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# `allauth` needs this from django
'django.template.context_processors.request',
],
},
},
]
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
AUTH_USER_MODEL = 'users.UserProfile'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
Am furthermore not sure how to fix this as there is no reference of authusers in my project files.
Traceback: https://dpaste.de/2SDB
You simply forgot to put the comma after 'rest_auth' ;)

Categories