How to get logged username in template - django-templates

I am using Django 1.8 with Python 3.4
I had no idea why my template doesn't show my username on template profile.html :/
profile.py
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'accounts/css/style.css' %}" />
{% block content %}
<h2>My profile</h2>
<p>{{ request.user.username }}</p>
{% endblock %}
views.py
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/accounts/profile')
else:
# Return a 'disabled account' error message
...
pass
else:
# Return an 'invalid login' error message.
pass
form = AuthenticationForm()
args = {}
args.update(csrf(request))
args['form']= AuthenticationForm()
return render_to_response('accounts/login.html', args)
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
print(request.user)
if user.is_active:
login(request, user)
return HttpResponseRedirect('/accounts/profile')
else:
# Return a 'disabled account' error message
...
else:
# Return an 'invalid login' error message.
...
def profile(request):
username = request.user.username
return render_to_response('accounts/profile.html', username)
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form']= UserCreationForm()
return render_to_response('accounts/register_user.html', args)
def register_success(request):
return render_to_response('accounts/register_success.html')
What's the best way to get user information from a django template?

Add django.template.context_processors.request to context_processors options of TEMPLATE variable in your settings.py file :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request', # add this line
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Related

Got AttributeError when attempting to get a value for field `email` on serializer `LoginSerializer`

Creating a Django API and want to login the user, the login is working but the exceptions not so much.
It was working until i wanted to return status
AttributeError at /login/
Got AttributeError when attempting to get a value for field email on serializer LoginSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Response instance.
Original exception text was: 'Response' object has no attribute 'email'.
I saw a few answers but the context didnt match.
What am i missing or doing wrong?
class LoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=68, min_length=6, write_only = True)
username = serializers.CharField(
read_only=True
)
tokens = serializers.CharField(max_length=68, min_length=6, read_only=True)
class Meta:
model=User
fields = ['email', 'username', 'password', 'tokens']
def validate(self, attrs):
email = attrs.get('email', '')
password = attrs.get('password', '')
user = auth.authenticate(email=email, password=password)
if user is None:
return Response({'msg':'No such user'}, status=status.HTTP_401_UNAUTHORIZED)
# raise AuthenticationFailed({'status':False,'message': ' username is worng'}, status=status.HTTP_401_UNAUTHORIZED)
if not user.is_active:
raise AuthenticationFailed({'msg':'Account is disabled'})
if not user.is_verified:
raise AuthenticationFailed({'msg': 'Email is not verified'})
if not user:
return Response({'msg':'Invalid credentials, try again'}, status=status.HTTP_401_Unauthorized)
return{
'email':user.email,
'username':user.username,
'tokens':user.tokens()
}
return super.validate(attrs)
'views.py'
class LoginAPIView(APIView):
serializer_class = LoginSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception = True)
return Response(serializer.data, status=status.HTTP_200_OK)
custom user model
class UserManager(BaseUserManager):
def create_user(self, username, email, password):
if username is None:
raise TypeError("User should be provide username")
if email is None:
raise TypeError("User should be provide email")
if password is None:
raise TypeError("User should be provide password")
user = self.model(username=username, email=self.normalize_email(email))
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password):
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, db_index=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
is_verified = models.BooleanField(default=False)
# is_authenticated = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
def __str__(self):
return self.email
def tokens(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
user = auth.authenticate(email=email, password=password)
print (user)
if not user:
raise AuthenticationFailed({'msg': 'No such user'}, code=status.HTTP_401_UNAUTHORIZED)
if user is None:
raise AuthenticationFailed({'message': ' Your Email or Password is wrong'}, code=status.HTTP_401_UNAUTHORIZED)
# raise AuthenticationFailed({'message': ' username is wrong'})
if not user.is_active:
raise AuthenticationFailed({'msg':'Account is disabled'},code=status.HTTP_403_FORBIDDEN)
if not user.is_verified:
raise AuthenticationFailed({'msg': 'Email is not verified'}, code=status.HTTP_401_UNAUTHORIZED)
This did the job for me. I guess the error came because the 'auth' did not take 'Response'

How to assert a json property which can be either null(Porp:null) or has a sub schema(Porp:{ denyAny: '#boolean', assertions: '#[]' }) In KARATE DSL?

I have a Json payload to validate. And It has a property which can be either null or a sub json object. But this property exists in the json.
I tried following methods:
01
And def dnyAssertionSchema = { denyAny: '#boolean', assertions: '##[]' }
And match each policyGResponse ==
"""
{
denyAssertions: '##(dnyAssertionSchema)'
}
"""
AND
And match each policyGResponse ==
"""
{
denyAssertions: '##null dnyAssertionSchema'
}
"""
AND
This does not work as the property is not an array so I tried above second method even I couldn't find an example as such.
And match each policyGResponse ==
"""
{
denyAssertions: '##[] dnyAssertionSchema'
}
"""
The Actual response can be either
{
denyAssertions=null
}
OR
{
denyAssertions={ denyAny: true, assertions: ["a","b"] }
}
I use Karate 0.9.1
Error message I get is 'reason: actual value has 1 more key(s) than expected: {denyAssertions=null}' in first try
In second try I get 'assertion failed: path: $[3].denyAssertions, actual: {denyAny=false, assertions=[]}, expected: '##null dnyAssertionSchema', reason: not equal'
Your JSON is still not valid but anyway. Here you go:
* def schema = { denyAny: '#boolean', assertions: '#[]' }
* def response1 = { denyAssertions: { denyAny: true, assertions: ["a","b"] } }
* match response1 == { denyAssertions: '##(schema)' }
* def response2 = { denyAssertions: null }
* match response1 == { denyAssertions: '##(schema)' }

Django rest framework Logout and Login View don't work

I'm doing a user registration via email with email confirmation. Then user gets a email letter to activate and finish its registration, login methods works. But I cant logout that user, and log him again. Could you suggest any other methods got logout and login with similar register View.
Here is my RegisterView, that works good.
class RegisterView(APIView):
permission_classes = [AllowAny]
def post(self, request, *args, **kwargs):
email = request.data.get('email', False)
password = request.data.get('password', False)
role = request.data.get('role')
if email and password and role:
user = User.objects.filter(email=email)
if user.exists():
return JsonResponse('Такой email уже существует', safe=False)
else:
temp_data = {
'email': email,
'password': password,
'role': role
}
serializer = CreateUserSerializer(data=temp_data)
serializer.is_valid(raise_exception=True)
user.is_active = False
user = serializer.save()
# user = authenticate(request, email=email, password=password)
user.set_password(user.password)
user.save()
current_site = get_current_site(request)
print(current_site)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
print(message)
from_email = settings.EMAIL_HOST_USER
to_email = serializer.validated_data.get('email')
email = EmailMessage(
subject, message, from_email, to=[to_email],
)
print(email)
email.send()
# return Response(serializer.data, status=status.HTTP_201_CREATED)
return HttpResponse('Please confirm your email address to complete the registration')
else:
return JsonResponse('Email не указан', safe=False)
Here is function for registration activating
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.set_password(user.password)
user.save()
login(request, user)
return HttpResponse('Thank you')
else:
return HttpResponse('Activation link is invalid!')
But my logout and login views dont work
class LogoutView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated,]
def post(self, request):
# django_logout(request)
request.user.auth_token.delete()
return Response(status=204)
class LoginView(KnoxLoginView):
permission_classes = (AllowAny,) #условие, если email не подтвержден, не поулчится залогиниться
def post(self, request, format=None):
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
# token, created = Token.objects.get_or_create(user=user)
# return Response({"token": token.key, 'id': token.user.id}, status=200)
login(request, user)
return super().post(request, format=None)
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(style={'input_type': 'password'}, trim_whitespace=False)
def validate(self, data):
email = data.get('email')
print(email)
password = data.get('password')
if email and password:
if User.objects.filter(email=email).exists():
print(email, password)
user = authenticate(request=self.context.get('request'), email=email, password=password)
print(user)
else:
msg = {
'status': False,
'detail': 'Email is not found'
}
raise serializers.ValidationError(msg)
if not user:
msg = {
'status': False,
'detail': 'Эмейлы не совпадают'
}
raise serializers.ValidationError(msg, code='authorization')
else:
msg = {
'status': False,
'detail': 'Email is not found in request'
}
raise serializers.ValidationError(msg, code='authorization')
data['user'] = user
return data

Error "u'social' is not a registered namespace" in basic integration of Auth0 with Django 1.8

I have a basic functional integration of Auth0 with Django 1.9 for user authentication, obtained of https://auth0.com/docs/quickstart/backend/django that use Python2.7 and works fine.
But I whant change the version of the Django to 1.8. To do this I did some changes mostly in settigs, but I'm missing something.
When whant to access to http://127.0.0.1:8000/login/auth0 get the error: NoReverseMatch at /login/auth0. u'social' is not a registered namespace
That URL match with social_django.urls
The code is:
Settings.py
from dotenv import load_dotenv, find_dotenv
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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',
'social_django',
'auth0login'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'webappexample.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 = 'webappexample.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
# ********************************
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
# SOCIAL AUTH AUTH0 BACKEND CONFIG
SOCIAL_AUTH_TRAILING_SLASH = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SECURE_SSL_REDIRECT = False
SOCIAL_AUTH_AUTH0_KEY = os.environ.get('AUTH0_CLIENT_ID')
SOCIAL_AUTH_AUTH0_SECRET = os.environ.get('AUTH0_CLIENT_SECRET')
SOCIAL_AUTH_AUTH0_SCOPE = [
'openid',
'profile'
]
SOCIAL_AUTH_AUTH0_DOMAIN = os.environ.get('AUTH0_DOMAIN')
AUDIENCE = None
if os.environ.get('AUTH0_AUDIENCE'):
AUDIENCE = os.environ.get('AUTH0_AUDIENCE')
else:
if SOCIAL_AUTH_AUTH0_DOMAIN:
AUDIENCE = 'https://' + SOCIAL_AUTH_AUTH0_DOMAIN + '/userinfo'
if AUDIENCE:
SOCIAL_AUTH_AUTH0_AUTH_EXTRA_ARGUMENTS = {'audience': AUDIENCE}
AUTHENTICATION_BACKENDS = {
'auth0login.auth0backend.Auth0',
'django.contrib.auth.backends.ModelBackend'
}
LOGIN_URL = '/login/auth0'
LOGIN_REDIRECT_URL = '/dashboard'
SOCIAL_AUTH_URL_NAMESPACE = 'social'
urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^dashboard$', views.dashboard),
url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
url(r'^', include('django.contrib.auth.urls')),
url(r'^', include('social_django.urls')),
]
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as log_out
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
import json
from django.utils.http import urlencode
def index(request):
username = None
if request.user.is_authenticated():
username = request.user.username
viewItems = {
'username':username
}
return render(request, 'index.html', viewItems)
#login_required
def dashboard(request):
user = request.user
auth0user = user.social_auth.get(provider='auth0')
userdata = {
'user_id': auth0user.uid,
'name': user.first_name,
'picture': auth0user.extra_data['picture']
}
return render(request, 'dashboard.html', {
'auth0User': auth0user,
'userdata': json.dumps(userdata, indent=4)
})
index.html
{% extends 'layout.html' %}
{% block content %}
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
{% if username == None %}
<p> No se encuentra logeado ningún usuario.</p>
<a class="btn btn-primary" href="/login/auth0">Login</a><br>
{% else %}
<p> Se encuentra logeado el usuario: {{ username }}.</p>
<a class="btn btn-primary" href="/logout">Logout</a><br>
{% endif %}
</div>
</div>
{% endblock content %}
auth0backend.py
from urllib2 import urlopen
from jose import jwt
from social_core.backends.oauth import BaseOAuth2
class Auth0(BaseOAuth2):
"""Auth0 OAuth authentication backend"""
name = 'auth0'
SCOPE_SEPARATOR = ' '
ACCESS_TOKEN_METHOD = 'POST'
EXTRA_DATA = [
('picture', 'picture')
]
def authorization_url(self):
print 'https://' + self.setting('DOMAIN') + '/authorize'
return 'https://' + self.setting('DOMAIN') + '/authorize'
def access_token_url(self):
print 'https://' + self.setting('DOMAIN') + '/oauth/token'
return 'https://' + self.setting('DOMAIN') + '/oauth/token'
def get_user_id(self, details, response):
"""Return current user id."""
print details['user_id']
return details['user_id']
def get_user_details(self, response):
# Obtain JWT and the keys to validate the signature
id_token = response.get('id_token')
jwks = urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json')
issuer = 'https://' + self.setting('DOMAIN') + '/'
audience = self.setting('KEY') # CLIENT_ID
payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer)
print {'username': payload['nickname'],
'first_name': payload['name'],
'picture': payload['picture'],
'user_id': payload['sub']}
return {'username': payload['nickname'],
'first_name': payload['name'],
'picture': payload['picture'],
'user_id': payload['sub']}
Looking at your urls.py I don't see the route you are looking to leverage. Have you combed through your app as well as well as your Auth0 application dashboard to confirm that any changes made are reflected there as well? That would be the first step I would recommend to resolve this issue. I hope this helps you in your quest!

Mock Grails Spring Security Logged in User

Looking for a way to mock spring security in some unit/integration tests.
Grails: V2.1.0
Spring Security Core: V1.2.7.3
Controller has the following:
// some action
def index(){
def user = getLoggedInUser()
render ....
}
...
private getLoggedInUser(){
return User.get(springSecurityService.principal.id)
}
I tried the following and various other ways but can't see to get it to work:
void testSomething(){
def dc = new SomeController()
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
principal: [username:"Bob"]]
dc.index()
... assertion....
It seems that the user is not getting created and can't get the principal.id. Any suggestions or better alternatives?
I think the user is just being created, but not saved, and that's why it doesn't have an ID.
The solution could be this:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(username: "Bob").save() // This way the user will have an ID
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
principal: loggedInUser]
dc.index() ... assertion....
There's an alternative:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(...).save()
dc.metaClass.getLoggedInUser = { loggedInUser }
...
I would suggest a refactor to getLoggedInUser:
private getLoggedInUser(){
return springSecurityService.currentUser
}
With this change, you could write:
void testSomething(){
def dc = new SomeController()
def loggedInUser = new User(...).save()
dc.springSecurityService = [
encodePassword: 'password',
reauthenticate: { String u -> true},
loggedIn: true,
getCurrenUser: { loggedInUser }]
...