From 75d4bfd5417c9b0af076a4f98c2c8216b4207204 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/attribute_kinds.py | 12 +++++ src/authentic2/custom_user/apps.py | 20 +++++--- src/authentic2/models.py | 9 +++- src/authentic2/settings.py | 2 + .../templates/authentic2/accounts.html | 18 ++++--- .../templates/authentic2/accounts_edit.html | 7 ++- src/authentic2/urls.py | 4 ++ src/authentic2/utils.py | 51 +++++++++++++++++++ 8 files changed, 108 insertions(+), 15 deletions(-) diff --git a/src/authentic2/attribute_kinds.py b/src/authentic2/attribute_kinds.py index 27ae00b4..a3d917b2 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 store_image capfirst = allow_lazy(capfirst, unicode) @@ -151,6 +152,17 @@ DEFAULT_ATTRIBUTE_KINDS = [ 'field_class': PhoneNumberField, 'rest_framework_field_class': PhoneNumberDRFField, }, + { + 'label': _('image'), + 'name': 'image', + 'field_class': forms.ImageField, + 'serialize': store_image, + 'serialize_eval_args' : [ + "owner.uuid", + ], + 'deserialize': lambda x: x, + 'rest_framework_field_class': serializers.ImageField, + }, ] diff --git a/src/authentic2/custom_user/apps.py b/src/authentic2/custom_user/apps.py index d220422c..1f35fa11 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 _ @@ -50,16 +50,24 @@ class CustomUserConfig(AppConfig): 'asked_on_registration': True, 'user_editable': True, 'user_visible': True}) + 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}) - 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/models.py b/src/authentic2/models.py index b14f3085..f1fa68f3 100644 --- a/src/authentic2/models.py +++ b/src/authentic2/models.py @@ -225,7 +225,14 @@ class Attribute(models.Model): av.verified = verified av.save() else: - content = serialize(value) + if self.get_kind().get('serialize_eval_args'): + serialize_args = list() + for flat_arg in self.get_kind().get('serialize_eval_args', []): + serialize_args.append(eval(flat_arg)) + content = serialize(value, *serialize_args) + else: + content = serialize(value) + av, created = AttributeValue.objects.get_or_create( content_type=ContentType.objects.get_for_model(owner), object_id=owner.pk, 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..aec73e7d 100644 --- a/src/authentic2/templates/authentic2/accounts.html +++ b/src/authentic2/templates/authentic2/accounts.html @@ -18,14 +18,18 @@ {% for attribute in attributes %}
{{ attribute.attribute.label|capfirst }} :
- {% if attribute.values|length == 1 %} - {{ attribute.values.0 }} + {% if attribute.attribute.kind == 'image' %} + {% 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..8ecba1fb 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,49 @@ def get_user_flag(user, name, default=None): if ou_value is not None: return ou_value return default + + +def store_image(file_wrapper, owner_uuid): + logger = logging.getLogger(__name__) + + digest = md5(file_wrapper.read()) + image_uuid = digest.hexdigest() + image_format = file_wrapper.image.format + + image_folder = default_storage.path('avatars/{oid}'.format( + oid=owner_uuid)) + + image_path = os.path.join( + image_folder, + "{uuid}.{ext}".format(uuid=image_uuid, ext=image_format)) + + uri = os.path.join(settings.MEDIA_URL, 'avatars/{oid}/{uuid}.{ext}'.format( + oid=owner_uuid, uuid=image_uuid, ext=image_format)) + + try: + if not os.path.exists(image_folder): + os.makedirs(image_folder) + + with open(image_path, 'wb') as f: + try: + fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + with tempfile.NamedTemporaryFile(mode='wb', dir=image_folder, delete=False) as temp: + try: + file_wrapper.seek(0) + temp.write(file_wrapper.read()) + temp.flush() + os.rename(temp.name, image_path) + pass + except: + logger.error("Could'nt store image to {}", file_path) + os.unlink(temp.name) + finally: + fcntl.lockf(f, fcntl.LOCK_UN) + except: + logger.error("Couldn't hold exclusive lock for file {}".format(image_path)) + finally: + fcntl.lockf(f, fcntl.LOCK_UN) + except IOError: + return + + return uri -- 2.19.0.rc1