From 45e44895e3b7c3c117ef94f506f2906040c5b4ac Mon Sep 17 00:00:00 2001 From: Paul Marillonnet Date: Tue, 4 Sep 2018 16:26:15 +0200 Subject: [PATCH] WIP support avatar picture in user profile (#26022) --- src/authentic2/api_views.py | 5 +- src/authentic2/attribute_kinds.py | 26 ++++++ src/authentic2/custom_user/apps.py | 20 ++-- src/authentic2/custom_user/models.py | 4 +- src/authentic2/forms/widgets.py | 21 ++++- src/authentic2/models.py | 21 ++++- src/authentic2/settings.py | 2 + .../templates/authentic2/accounts.html | 22 +++-- .../templates/authentic2/accounts_edit.html | 7 +- src/authentic2/urls.py | 4 + src/authentic2/utils.py | 91 +++++++++++++++++++ 11 files changed, 200 insertions(+), 23 deletions(-) diff --git a/src/authentic2/api_views.py b/src/authentic2/api_views.py index b6fa431a..7ece0d8c 100644 --- a/src/authentic2/api_views.py +++ b/src/authentic2/api_views.py @@ -298,9 +298,10 @@ password_change = PasswordChange.as_view() @cache_control(private=True, max_age=60) @decorators.json def user(request): - if request.user.is_anonymous(): + u = request.user + if u.is_anonymous(): return {} - return request.user.to_json() + return u.to_json(request) def attributes_hash(attributes): diff --git a/src/authentic2/attribute_kinds.py b/src/authentic2/attribute_kinds.py index 27ae00b4..02d768c2 100644 --- a/src/authentic2/attribute_kinds.py +++ b/src/authentic2/attribute_kinds.py @@ -17,6 +17,7 @@ from .decorators import to_iter from .plugins import collect_from_plugins from . import app_settings from .forms import widgets +from .utils import image_serialize capfirst = allow_lazy(capfirst, unicode) @@ -91,6 +92,11 @@ class FrPostcodeDRFField(serializers.CharField): default_validators = [validate_fr_postcode] +class A2ImageDRFField(serializers.ImageField): + def to_representation(self, value, *args, **kwargs): + return self.context['request'].build_absolute_uri(value) + + DEFAULT_ALLOW_BLANK = True DEFAULT_MAX_LENGTH = 256 @@ -151,6 +157,26 @@ DEFAULT_ATTRIBUTE_KINDS = [ 'field_class': PhoneNumberField, 'rest_framework_field_class': PhoneNumberDRFField, }, + { + 'label': _('image'), + 'name': 'image', + 'field_class': forms.ImageField, + 'kwargs': { + 'widget': widgets.AttributeImageInput, + }, + 'serialize': image_serialize, + 'serialize_eval_kwargs' : { + 'owner_uuid': 'owner.uuid', + 'owner_pk': 'owner.pk', + 'attr_label': 'self.label', + }, + 'deserialize': lambda x: x, + 'rest_framework_field_class': A2ImageDRFField, + 'rest_framework_field_kwargs': { + 'read_only': True, + }, + 'value_is_relative_uri': True, + }, ] diff --git a/src/authentic2/custom_user/apps.py b/src/authentic2/custom_user/apps.py index d220422c..442cf919 100644 --- a/src/authentic2/custom_user/apps.py +++ b/src/authentic2/custom_user/apps.py @@ -10,10 +10,10 @@ class CustomUserConfig(AppConfig): from django.db.models.signals import post_migrate post_migrate.connect( - self.create_first_name_last_name_attributes, + self.create_custom_attributes, sender=self) - def create_first_name_last_name_attributes(self, app_config, verbosity=2, interactive=True, + def create_custom_attributes(self, app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): from django.utils import translation from django.utils.translation import ugettext_lazy as _ @@ -34,6 +34,14 @@ class CustomUserConfig(AppConfig): content_type = ContentType.objects.get_for_model(User) attrs = {} + attrs['avatar_picture'], created = Attribute.objects.get_or_create( + name='avatar_picture', + defaults={'kind': 'image', + 'label': _('Avatar picture'), + 'required': False, + 'asked_on_registration': False, + 'user_editable': True, + 'user_visible': True}) attrs['first_name'], created = Attribute.objects.get_or_create( name='first_name', defaults={'kind': 'string', @@ -51,15 +59,15 @@ class CustomUserConfig(AppConfig): 'user_editable': True, 'user_visible': True}) - serialize = get_kind('string').get('serialize') for user in User.objects.all(): - for attr_name in attrs: + for at in attrs: + serialize = get_kind(at.kind).get('serialize') av, created = AttributeValue.objects.get_or_create( content_type=content_type, object_id=user.id, - attribute=attrs[attr_name], + attribute=attrs[at], defaults={ 'multiple': False, 'verified': False, - 'content': serialize(getattr(user, attr_name, None)) + 'content': serialize(getattr(user, at, None)) }) diff --git a/src/authentic2/custom_user/models.py b/src/authentic2/custom_user/models.py index ea3f4fba..2be14220 100644 --- a/src/authentic2/custom_user/models.py +++ b/src/authentic2/custom_user/models.py @@ -219,10 +219,10 @@ class User(AbstractBaseUser, PermissionMixin): def has_verified_attributes(self): return AttributeValue.objects.with_owner(self).filter(verified=True).exists() - def to_json(self): + def to_json(self, request): d = {} for av in AttributeValue.objects.with_owner(self): - d[str(av.attribute.name)] = av.to_python() + d[str(av.attribute.name)] = av.to_python(request) d.update({ 'uuid': self.uuid, 'username': self.username, diff --git a/src/authentic2/forms/widgets.py b/src/authentic2/forms/widgets.py index c3d1dda2..db0226c9 100644 --- a/src/authentic2/forms/widgets.py +++ b/src/authentic2/forms/widgets.py @@ -11,7 +11,8 @@ import json import re import uuid -from django.forms.widgets import DateTimeInput, DateInput, TimeInput +from django.forms.widgets import DateTimeInput, DateInput, TimeInput, \ + ClearableFileInput from django.forms.widgets import PasswordInput as BasePasswordInput from django.utils.formats import get_language, get_format from django.utils.safestring import mark_safe @@ -246,3 +247,21 @@ class CheckPasswordInput(PasswordInput): json.dumps(_id), ) return output + + +class AttributeImageInput(ClearableFileInput): + # template_name = "authentic2/accounts_image.html" # Django 1.11 only todo + template_with_initial = ( + '%(initial_text)s:

' + '%(clear_template)s
%(input_text)s: %(input)s' + ) + + def is_initial(self, value): + return bool(value) + + def get_template_substitution_values(self, value): + subs_values = dict() + subs_values.update({ + 'initial': value, + }) + return subs_values diff --git a/src/authentic2/models.py b/src/authentic2/models.py index b14f3085..42410dc1 100644 --- a/src/authentic2/models.py +++ b/src/authentic2/models.py @@ -225,7 +225,16 @@ class Attribute(models.Model): av.verified = verified av.save() else: - content = serialize(value) + serialize_eval_kwargs = self.get_kind().get('serialize_eval_kwargs', {}) + if serialize_eval_kwargs: + kwargs = dict() + for key, flat_value in serialize_eval_kwargs.items(): + evalue = eval(flat_value) + kwargs.update({key: evalue}) + content = serialize(value, **kwargs) + else: + content = serialize(value) + av, created = AttributeValue.objects.get_or_create( content_type=ContentType.objects.get_for_model(owner), object_id=owner.pk, @@ -275,9 +284,13 @@ class AttributeValue(models.Model): objects = managers.AttributeValueManager() - def to_python(self): - deserialize = self.attribute.get_kind()['deserialize'] - return deserialize(self.content) + def to_python(self, request=None): + kind = self.attribute.get_kind() + deserialize = kind['deserialize'] + content = self.content + if request and kind.get('value_is_relative_uri'): + content = request.build_absolute_uri(content) + return deserialize(content) def natural_key(self): if not hasattr(self.owner, 'natural_key'): diff --git a/src/authentic2/settings.py b/src/authentic2/settings.py index c045ce2a..8c9289a6 100644 --- a/src/authentic2/settings.py +++ b/src/authentic2/settings.py @@ -22,6 +22,8 @@ SECRET_KEY = 'please-change-me-with-a-very-long-random-string' DEBUG = False DEBUG_DB = False MEDIA = 'media' +MEDIA_ROOT = 'media' +MEDIA_URL = '/media/' # See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] diff --git a/src/authentic2/templates/authentic2/accounts.html b/src/authentic2/templates/authentic2/accounts.html index 4e9f979f..8f076609 100644 --- a/src/authentic2/templates/authentic2/accounts.html +++ b/src/authentic2/templates/authentic2/accounts.html @@ -18,14 +18,22 @@ {% for attribute in attributes %}
{{ attribute.attribute.label|capfirst }} :
- {% if attribute.values|length == 1 %} - {{ attribute.values.0 }} + {% if attribute.attribute.kind == 'image' %} + {% if attribute.attribute.name == 'avatar_picture' %} + + {% else %} + + {% endif %} {% else %} - + {% if attribute.values|length == 1 %} + {{ attribute.values.0 }} + {% else %} + + {% endif %} {% endif %}
{% endfor %} diff --git a/src/authentic2/templates/authentic2/accounts_edit.html b/src/authentic2/templates/authentic2/accounts_edit.html index c7587b14..a642b1b7 100644 --- a/src/authentic2/templates/authentic2/accounts_edit.html +++ b/src/authentic2/templates/authentic2/accounts_edit.html @@ -12,7 +12,12 @@ {% endblock %} {% block content %} -
+ {% if form.is_multipart %} + + {% else %} + + {% endif %} + {% csrf_token %} {{ form.as_p }} {% if form.instance and form.instance.id %} diff --git a/src/authentic2/urls.py b/src/authentic2/urls.py index 35b13139..048a6396 100644 --- a/src/authentic2/urls.py +++ b/src/authentic2/urls.py @@ -44,6 +44,10 @@ if settings.DEBUG: urlpatterns += [ url(r'^static/(?P.*)$', serve) ] + urlpatterns += [ + url(r'^media/(?P.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT}) + ] if settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar diff --git a/src/authentic2/utils.py b/src/authentic2/utils.py index d32a5a67..97110c72 100644 --- a/src/authentic2/utils.py +++ b/src/authentic2/utils.py @@ -8,11 +8,15 @@ import urlparse import uuid import datetime import copy +import fcntl +import os +import tempfile from functools import wraps from itertools import islice, chain, count from importlib import import_module +from hashlib import md5 from django.conf import settings from django.http import HttpResponseRedirect, HttpResponse @@ -30,6 +34,7 @@ from django.shortcuts import resolve_url from django.template.loader import render_to_string, TemplateDoesNotExist from django.core.mail import send_mail from django.core import signing +from django.core.files.storage import default_storage from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.formats import localize from django.contrib import messages @@ -1073,3 +1078,89 @@ def get_user_flag(user, name, default=None): if ou_value is not None: return ou_value return default + + +def _store_image(in_memory_image, owner_uuid): + logger = logging.getLogger(__name__) + + digest = md5(in_memory_image.read()) + + img_id = digest.hexdigest() + img_ext = in_memory_image.image.format + + img_media_dir = 'avatars/{oid}/'.format(oid=owner_uuid) + img_media_path = '{imdir}/{iid}.{ext}'.format( + imdir=img_media_dir, iid=img_id, ext=img_ext) + + img_abs_path = default_storage.path(img_media_path) + img_abs_dir = default_storage.path(img_media_dir) + + try: + if not os.path.exists(img_abs_dir): + os.makedirs(img_abs_dir) + + with open(img_abs_path, 'wb') as f: + try: + fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + with tempfile.NamedTemporaryFile(mode='wb', dir=img_abs_dir, delete=False) as temp: + try: + in_memory_image.seek(0) + temp.write(in_memory_image.read()) + temp.flush() + os.rename(temp.name, img_abs_path) + except: + logger.error("Could'nt store image to {}".format(img_abs_path)) + os.unlink(temp.name) + except: + logger.error("Couldn't hold exclusive lock for file {}".format(img_abs_path)) + finally: + fcntl.lockf(f, fcntl.LOCK_UN) + except IOError: + return + + return img_media_path + +def _delete_images_from_user(owner_pk, attr_label): + from .models import Attribute, AttributeValue + + logger = logging.getLogger(__name__) + User = get_user_model() + + try: + owner = User.objects.get(pk=owner_pk) + except User.DoesNotExist: + logger.error("Primary key {} doesn't match with any user.".format(owner_pk)) + return + + try: + attr = Attribute.objects.get(label=attr_label) + all_values = AttributeValue.objects.with_owner(owner) + values = all_values.filter(attribute=attr) + except: + logger.error("Couldn't retrieve values for Attribute {}.".format(attr_label)) + + for value in values: + # Direct URI <-> file location correspondence + local_file = value.content.split(default_storage.base_url)[-1] + if not local_file: + continue + media_file = default_storage.path(local_file) + + try: + os.remove(media_file) + value.delete() + except: + logger.error("Could'nt delete image {}".format(media_file)) + + +def image_serialize(image, owner_uuid, owner_pk, attr_label): + uri = '' + if isinstance(image, basestring): + uri = image + else: + # Discard previous user avatars + _delete_images_from_user(owner_pk, attr_label) + if image: + img_media_path = _store_image(image, owner_uuid) + uri = os.path.join(settings.MEDIA_URL, img_media_path) + return uri -- 2.19.0