Example #1
0
def add(request, extra_context=None, next_override=None,
        upload_form=UploadAvatarForm, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    upload_avatar_form = upload_form(request.POST or None,
        request.FILES or None, user=request.user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                emailuser = request.user.username,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
        else:
            messages.error(request, upload_avatar_form.errors['avatar'])

        return HttpResponseRedirect(_get_next(request))
    else:
        # Only allow post request to change avatar.
        raise Http404
Example #2
0
def add(request, extra_context=None, next_override=None,
        upload_form=UploadAvatarForm, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    upload_avatar_form = upload_form(request.POST or None,
        request.FILES or None, user=request.user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                emailuser = request.user.username,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
        else:
            messages.error(request, upload_avatar_form.errors['avatar'])

        return HttpResponseRedirect(_get_next(request))
    else:
        # Only allow post request to change avatar.
        raise Http404
Example #3
0
    def post(self, request):

        image_file = request.FILES.get('avatar', None)
        if not image_file:
            error_msg = 'avatar invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        (root, ext) = os.path.splitext(image_file.name.lower())
        if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS:
            error_msg = _(
                u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s"
            ) % {
                'ext': ext,
                'valid_exts_list': ", ".join(AVATAR_ALLOWED_FILE_EXTS)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > AVATAR_MAX_SIZE:
            error_msg = _(
                u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s"
            ) % {
                'size': filesizeformat(image_file.size),
                'max_valid_size': filesizeformat(AVATAR_MAX_SIZE)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        username = request.user.username
        count = Avatar.objects.filter(emailuser=username).count()
        if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER:
            error_msg = _(
                u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d."
            ) % {
                'nb_avatars': count,
                'nb_max_avatars': AVATAR_MAX_AVATARS_PER_USER
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar = Avatar(
                emailuser=username,
                primary=True,
            )
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
Example #4
0
def update_dingtalk_user_info(email, name, contact_email, avatar_url):

    # make sure the contact_email is unique
    if contact_email and Profile.objects.get_profile_by_contact_email(contact_email):
        logger.warning('contact email %s already exists' % contact_email)
        contact_email = ''

    profile_kwargs = {}
    if name:
        profile_kwargs['nickname'] = name
    if contact_email:
        profile_kwargs['contact_email'] = contact_email

    if profile_kwargs:
        try:
            Profile.objects.add_or_update(email, **profile_kwargs)
        except Exception as e:
            logger.error(e)

    if avatar_url:
        try:
            image_name = 'dingtalk_avatar'
            image_file = requests.get(avatar_url).content
            avatar = Avatar.objects.filter(emailuser=email, primary=True).first()
            avatar = avatar or Avatar(emailuser=email, primary=True)
            avatar_file = ContentFile(image_file)
            avatar_file.name = image_name
            avatar.avatar = avatar_file
            avatar.save()
        except Exception as e:
            logger.error(e)
Example #5
0
def update_weixin_user_info(api_user):
    """ update user profile from weixin

    use for weixin login, bind
    """
    # update additional user info
    username = api_user.get('username')
    nickname = api_user.get('nickname').encode('ISO-8859-1').decode('utf8')
    headimgurl = api_user.get('headimgurl')

    profile_kwargs = {}
    if nickname:
        profile_kwargs['nickname'] = nickname

    if profile_kwargs:
        try:
            Profile.objects.add_or_update(username, **profile_kwargs)
        except Exception as e:
            logger.error(e)

    # avatar

    try:
        image_name = 'weixin_headimgurl'
        image_file = requests.get(headimgurl).content
        avatar = Avatar.objects.filter(emailuser=username,
                                       primary=True).first()
        avatar = avatar or Avatar(emailuser=username, primary=True)
        avatar_file = ContentFile(image_file)
        avatar_file.name = image_name
        avatar.avatar = avatar_file
        avatar.save()
    except Exception as e:
        logger.error(e)
Example #6
0
    def post(self, request):

        image_file = request.FILES.get('avatar', None)
        avatar_size = request.data.get('avatar_size', 64)

        if not image_file:
            error_msg = 'avatar invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar_size = int(avatar_size)
        except Exception as e:
            logger.error(e)
            error_msg = 'avatar_size invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        (root, ext) = os.path.splitext(image_file.name.lower())
        if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS:
            error_msg = _(u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s") % {'ext' : ext, 'valid_exts_list' : ", ".join(AVATAR_ALLOWED_FILE_EXTS)}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > AVATAR_MAX_SIZE:
            error_msg = _(u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s") % { 'size' : filesizeformat(image_file.size), 'max_valid_size' : filesizeformat(AVATAR_MAX_SIZE)}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        username = request.user.username
        count = Avatar.objects.filter(emailuser=username).count()
        if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER:
            error_msg = _(u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d.") % { 'nb_avatars' : count, 'nb_max_avatars' : AVATAR_MAX_AVATARS_PER_USER}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar = Avatar(
                emailuser = username,
                primary = True,
            )
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            avatar_url, is_default, date_uploaded = api_avatar_url(username, int(avatar_size))
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'avatar_url': request.build_absolute_uri(avatar_url)})
Example #7
0
def _update_user_avatar(user, pic):
    if not pic:
        return

    logger.info("retrieve pic from %s" % pic)

    filedata = urllib2.urlopen(pic)
    datatowrite = filedata.read()
    filename = '/tmp/%s.jpg' % user.username
    with open(filename, 'wb') as f:
        f.write(datatowrite)

    logger.info("save pic to %s" % filename)
    avatar = Avatar(emailuser=user.username, primary=True)
    avatar.avatar.save('image.jpg', File(open(filename)))
    avatar.save()
    avatar_updated.send(sender=Avatar, user=user, avatar=avatar)

    os.remove(filename)
Example #8
0
def _update_user_avatar(user, pic):
    if not pic:
        return

    logger.info("retrieve pic from %s" % pic)

    filedata = urllib2.urlopen(pic)
    datatowrite = filedata.read()
    filename = '/tmp/%s.jpg' % user.username
    with open(filename, 'wb') as f:
        f.write(datatowrite)

    logger.info("save pic to %s" % filename)
    avatar = Avatar(emailuser=user.username, primary=True)
    avatar.avatar.save(
        'image.jpg', File(open(filename))
    )
    avatar.save()
    avatar_updated.send(sender=Avatar, user=user, avatar=avatar)

    os.remove(filename)
Example #9
0
    def post(self, request):

        image_file = request.FILES.get('avatar', None)
        avatar_size = request.data.get('avatar_size', 64)

        if not image_file:
            error_msg = 'avatar invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar_size = int(avatar_size)
        except Exception as e:
            logger.error(e)
            error_msg = 'avatar_size invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        (root, ext) = os.path.splitext(image_file.name.lower())
        if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS:
            error_msg = _(
                "%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s"
            ) % {
                'ext': ext,
                'valid_exts_list': ", ".join(AVATAR_ALLOWED_FILE_EXTS)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > AVATAR_MAX_SIZE:
            error_msg = _(
                "Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s"
            ) % {
                'size': filesizeformat(image_file.size),
                'max_valid_size': filesizeformat(AVATAR_MAX_SIZE)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        username = request.user.username

        try:
            avatar = Avatar.objects.filter(emailuser=username,
                                           primary=True).first()
            avatar = avatar or Avatar(emailuser=username, primary=True)
            avatar.avatar = image_file
            avatar.save()
            avatar_url, is_default, date_uploaded = api_avatar_url(
                username, int(avatar_size))
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'avatar_url': avatar_url})
Example #10
0
def update_work_weixin_user_info(api_user):
    """ update user profile from work weixin

    use for work weixin departments, login, profile bind
    """
    # update additional user info
    username = api_user.get('username')
    nickname = api_user.get('name')
    contact_email = api_user.get('contact_email')
    headimgurl = api_user.get('avatar')

    # make sure the contact_email is unique
    if contact_email and Profile.objects.get_profile_by_contact_email(contact_email):
        logger.warning('contact email %s already exists' % contact_email)
        contact_email = ''

    profile_kwargs = {}
    if nickname:
        profile_kwargs['nickname'] = nickname
    if contact_email:
        profile_kwargs['contact_email'] = contact_email

    if profile_kwargs:
        try:
            Profile.objects.add_or_update(username, **profile_kwargs)
        except Exception as e:
            logger.error(e)

    # avatar

    try:
        image_name = 'work_weixin_avatar'
        image_file = requests.get(headimgurl).content
        avatar = Avatar.objects.filter(emailuser=username, primary=True).first()
        avatar = avatar or Avatar(emailuser=username, primary=True)
        avatar_file = ContentFile(image_file)
        avatar_file.name = image_name
        avatar.avatar = avatar_file
        avatar.save()
    except Exception as e:
        logger.error(e)
Example #11
0
def weixin_oauth_callback(request):

    if not ENABLE_WEIXIN:
        return render_error(request, _('Error, please contact administrator.'))

    state = request.GET.get('state', '')
    if not state or state != request.session.get('weixin_oauth_login_state', ''):
        logger.error('invalid state')
        return render_error(request, _('Error, please contact administrator.'))

    # get access_token and user openid
    parameters = {
        'appid': WEIXIN_OAUTH_APP_ID,
        'secret': WEIXIN_OAUTH_APP_SECRET,
        'code': request.GET.get('code'),
        'grant_type': WEIXIN_OAUTH_GRANT_TYPE,
    }

    access_token_url = WEIXIN_OAUTH_ACCESS_TOKEN_URL + '?' + urllib.parse.urlencode(parameters)
    access_token_json = requests.get(access_token_url).json()

    openid = access_token_json.get('openid', '')
    access_token = access_token_json.get('access_token', '')
    if not access_token or not openid:
        logger.error('invalid access_token or openid')
        logger.error(access_token_url)
        logger.error(access_token_json)
        return render_error(request, _('Error, please contact administrator.'))

    # login user in
    auth_user = SocialAuthUser.objects.get_by_provider_and_uid('weixin', openid)
    if auth_user:
        email = auth_user.username
    else:
        email = gen_user_virtual_id()
        SocialAuthUser.objects.add(email, 'weixin', openid)

    try:
        user = auth.authenticate(remote_user=email)
    except User.DoesNotExist:
        user = None
    except Exception as e:
        logger.error(e)
        return render_error(request, _('Error, please contact administrator.'))

    if not user or not user.is_active:
        return render_error(request, _('User %s not found or inactive.') % email)

    request.user = user
    auth.login(request, user)

    # get user profile info
    parameters = {
        'access_token': access_token,
        'openid': openid,
    }
    user_info_url = WEIXIN_OAUTH_USER_INFO_URL + '?' + urllib.parse.urlencode(parameters)
    user_info_resp = requests.get(user_info_url).json()

    name = user_info_resp['nickname'] if 'nickname' in user_info_resp else ''
    name = name.encode('raw_unicode_escape').decode('utf-8')
    if name:

        profile = Profile.objects.get_profile_by_user(email)
        if not profile:
            profile = Profile(user=email)

        profile.nickname = name.strip()
        profile.save()

    avatar_url = user_info_resp['headimgurl'] if 'headimgurl' in user_info_resp else ''
    try:
        image_name = 'dingtalk_avatar'
        image_file = requests.get(avatar_url).content
        avatar = Avatar.objects.filter(emailuser=email, primary=True).first()
        avatar = avatar or Avatar(emailuser=email, primary=True)
        avatar_file = ContentFile(image_file)
        avatar_file.name = image_name
        avatar.avatar = avatar_file
        avatar.save()
    except Exception as e:
        logger.error(e)

    # generate auth token for Seafile client
    api_token = get_api_token(request)

    # redirect user to home page
    response = HttpResponseRedirect(request.session['weixin_oauth_login_redirect'])
    response.set_cookie('seahub_auth', email + '@' + api_token.key)
    return response