Пример #1
0
def addon_image_uploader(request, **kwargs):
    uploader = AjaxUploader(filetype='image',
                            upload_dir=setting('IMAGE_UPLOAD_DIR', 'images'),
                            size_limit=setting('IMAGE_UPLOAD_SIZE', 10485760))
    result = uploader.handle_upload(request)
    if result['success']:
        new = Pic()
        new.content_type = ContentType.objects.get_for_id(
            int(kwargs['content_type']))
        new.object_id = int(kwargs['object_id'])
        new.description = result['old_filename']
        new.user = request.user
        new.created_date = now()
        new.pic = result['path']
        fullpath = os.path.join(settings.MEDIA_ROOT, new.pic.field.upload_to,
                                new.pic.path)
        new.size = os.path.getsize(fullpath)
        new.save()
        # noinspection PyBroadException
        try:
            pics_count = dict(pics_count=new.content_object.pics_count)
            result.update(pics_count)
        except:
            pass
        # noinspection PyBroadException
        try:
            addons = dict(
                html=render_to_string('upload/image_item.html', {'pic': new}))
        except:
            addons = {}
        result.update(addons)
    return ajax_answer(result)
Пример #2
0
def addon_file_uploader(request, **kwargs):
    uploader = AjaxUploader(filetype='file',
                            upload_dir=setting('FILE_UPLOAD_DIR', 'files'),
                            size_limit=setting('FILE_UPLOAD_SIZE', 104857600))
    result = uploader.handle_upload(request)
    if result['success']:
        new = Doc()
        new.content_type = ContentType.objects.get_for_id(
            int(kwargs['content_type']))
        new.object_id = int(kwargs['object_id'])
        new.description = result['old_filename']
        new.user = request.user
        new.created_date = now()
        new.doc = result['path']
        fullpath = os.path.join(settings.MEDIA_ROOT, new.doc.field.upload_to,
                                new.doc.path)
        new.size = os.path.getsize(fullpath)
        new.save()
        try:
            addons = dict(
                html=render_to_string('upload/file_item.html', {'doc': new}))
        except:
            addons = {}
        result.update(addons)
    return ajax_answer(result)
Пример #3
0
def addon_image_uploader(request, **kwargs):
    uploader = AjaxUploader(
        filetype="image",
        uploadDirectory=setting("IMAGE_UPLOAD_DIR", "images"),
        sizeLimit=setting("IMAGE_UPLOAD_SIZE", 10485760),
    )
    result = uploader.handleUpload(request)
    if result["success"]:
        new = Pic()
        new.content_type = get_object_or_404(ContentType, id=int(kwargs["content_type"]))
        new.object_id = int(kwargs["object_id"])
        new.description = result["old_filename"]
        new.user = request.user
        new.created_date = now()
        new.pic = result["path"]
        fullpath = os.path.join(settings.MEDIA_ROOT, new.pic.field.upload_to, new.pic.path)
        new.size = os.path.getsize(fullpath)
        new.save()
        try:
            pics_count = dict(pics_count=new.content_object.pics_count)
            result.update(pics_count)
        except:
            pass
        try:
            addons = dict(html=render_to_string("upload/image_item.html", {"pic": new}))
        except:
            addons = {}
        result.update(addons)
    return AjaxAnswer(result)
Пример #4
0
def file_uploader(request, **kwargs):
    uploader = AjaxUploader(
        filetype="image",
        uploadDirectory=setting("IMAGE_UPLOAD_DIR", "images"),
        sizeLimit=setting("IMAGE_UPLOAD_SIZE", 10485760),
    )
    result = uploader.handleUpload(request)
    if result["success"]:
        ctype = get_object_or_404(ContentType, id=int(kwargs["content_type"]))
        object_id = int(kwargs["object_id"])
        obj = ctype.get_object_for_this_type(pk=object_id)
        try:
            remove_thumbnails(obj.img.path)
            remove_file(obj.img.path)
            obj.img.delete()
        except:
            pass
        obj.img = result["path"]
        obj.save()
        try:
            addons = dict(
                tmb=make_thumbnail(
                    obj.img.url, width=int(kwargs["width"]), height=int(kwargs["height"]), aspect=int(kwargs["aspect"])
                )
            )
        except:
            addons = {}
        result.update(addons)
    return AjaxAnswer(result)
Пример #5
0
def file_uploader(request, **kwargs):
    uploader = AjaxUploader(filetype='image',
                            uploadDirectory=setting('IMAGE_UPLOAD_DIR',
                                                    'images'),
                            sizeLimit=setting('IMAGE_UPLOAD_SIZE', 10485760))
    result = uploader.handleUpload(request)
    if result['success']:
        ctype = get_object_or_404(ContentType, id=int(kwargs['content_type']))
        object_id = int(kwargs['object_id'])
        obj = ctype.get_object_for_this_type(pk=object_id)
        try:
            remove_thumbnails(obj.img.path)
            remove_file(obj.img.path)
            obj.img.delete()
        except:
            pass
        obj.img = result['path']
        obj.save()
        try:
            addons = dict(tmb=make_thumbnail(obj.img.url,
                                             width=int(kwargs['width']),
                                             height=int(kwargs['height']),
                                             aspect=int(kwargs['aspect'])))
        except:
            addons = {}
        result.update(addons)
    return AjaxAnswer(result)
Пример #6
0
def addon_image_uploader(request, **kwargs):
    uploader = AjaxUploader(filetype='image', upload_dir=setting('IMAGE_UPLOAD_DIR', 'images'),
                            size_limit=setting('IMAGE_UPLOAD_SIZE', 10485760))
    result = uploader.handle_upload(request)
    if result['success']:
        new = Pic()
        new.content_type = ContentType.objects.get_for_id(int(kwargs['content_type']))
        new.object_id = int(kwargs['object_id'])
        new.description = result['old_filename']
        new.user = request.user
        new.created_date = now()
        new.pic = result['path']
        fullpath = os.path.join(settings.MEDIA_ROOT,
                                new.pic.field.upload_to, new.pic.path)
        new.size = os.path.getsize(fullpath)
        new.save()
        # noinspection PyBroadException
        try:
            pics_count = dict(pics_count=new.content_object.pics_count)
            result.update(pics_count)
        except:
            pass
        # noinspection PyBroadException
        try:
            addons = dict(html=render_to_string('upload/image_item.html', {'pic': new}))
        except:
            addons = {}
        result.update(addons)
    return ajax_answer(result)
Пример #7
0
 def form_valid(self, form):
     email = form.cleaned_data.get('email')
     username = form.cleaned_data.get('username')
     password = form.cleaned_data.get('password2')
     # noinspection PyBroadException
     try:
         e = EmailValidation.objects.get(email=email)
     except:
         e = EmailValidation()
         e.username = username
         e.email = email
         e.password = password
         e.created = now()
         e.key = make_key(username)
         e.save()
     mail_dict = {
         'key': e.key,
         'expiration_days': setting('ACCOUNT_ACTIVATION_DAYS', 7),
         'site_name': setting('SITENAME', 'NNMWARE'),
         'email': email
     }
     subject = 'registration/activation_subject.txt'
     body = 'registration/activation.txt'
     send_template_mail(subject, body, mail_dict, [e.email])
     return super(SignupView, self).form_valid(form)
Пример #8
0
def backend_setting(backend, name, default=None):
    """
    Looks for setting value following these rules:
        1. Search for <backend_name> prefixed setting
        2. Search for setting given by name
        3. Return default
    """
    backend_name = backend.AUTH_BACKEND.name.upper().replace('-', '_')
    return setting('%s_%s' % (backend_name, name)) or setting(name) or default
Пример #9
0
 def oauth_request(self, token, url, extra_params=None):
     extra_params = extra_params or {}
     scope = GOOGLE_OAUTH_SCOPE + setting('GOOGLE_OAUTH_EXTRA_SCOPE', [])
     extra_params.update({
         'scope': ' '.join(scope),
     })
     if not self.registered():
         xoauth_displayname = setting('GOOGLE_DISPLAY_NAME', 'Social Auth')
         extra_params['xoauth_displayname'] = xoauth_displayname
     return super(GoogleOAuth, self).oauth_request(token, url, extra_params)
Пример #10
0
 def oauth_request(self, token, url, extra_params=None):
     extra_params = extra_params or {}
     scope = GOOGLE_OAUTH_SCOPE + setting('GOOGLE_OAUTH_EXTRA_SCOPE', [])
     extra_params.update({
         'scope': ' '.join(scope),
     })
     if not self.registered():
         xoauth_displayname = setting('GOOGLE_DISPLAY_NAME', 'Social Auth')
         extra_params['xoauth_displayname'] = xoauth_displayname
     return super(GoogleOAuth, self).oauth_request(token, url, extra_params)
Пример #11
0
def save_status_to_session(request, auth, pipeline_index, *args, **kwargs):
    """Saves current social-auth status to session."""
    next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY')

    if next_entry and next_entry in PIPELINE:
        idx = PIPELINE.index(next_entry)
    else:
        idx = pipeline_index + 1

    data = auth.to_session_dict(idx, *args, **kwargs)
    name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
    request.session[name] = data
Пример #12
0
def convert_from_client_currency(request, amount):
    try:
        if request.COOKIES['currency'] == setting('CURRENCY', 'RUB'):
            return amount
        currency = Currency.objects.get(code=request.COOKIES['currency'])
        rate = ExchangeRate.objects.filter(currency=currency).filter(date__lte=now()).order_by('-date')[0]
        if setting('OFFICIAL_RATE', True):
            exchange = rate.official_rate
        else:
            exchange = rate.rate
        return int((int(amount) * exchange) / rate.nominal)
    except:
        return int(amount)
Пример #13
0
def avatar_set(request):
    uploader = AjaxUploader(filetype='image', upload_dir=setting('AVATAR_UPLOAD_DIR', 'avatars'),
                            size_limit=setting('AVATAR_UPLOAD_SIZE', 1024000))
    result = uploader.handle_upload(request)
    if result['success']:
        request.user.img = result['path']
        request.user.save()
        try:
            addons = dict(html=render_to_string('user/avatar.html', {'object': request.user}))
        except:
            addons = {}
        result.update(addons)
    return ajax_answer_lazy(result)
Пример #14
0
def validate_whitelists(backend, email):
    """
    Validates allowed domains and emails against the following settings:
        GOOGLE_WHITE_LISTED_DOMAINS
        GOOGLE_WHITE_LISTED_EMAILS

    All domains and emails are allowed if setting is an empty list.
    """
    emails = setting('GOOGLE_WHITE_LISTED_EMAILS', [])
    domains = setting('GOOGLE_WHITE_LISTED_DOMAINS', [])
    if emails and email in emails:
        return  # you're good
    if domains and email.split('@', 1)[1] not in domains:
        raise AuthFailed(backend, 'Domain not allowed')
Пример #15
0
def validate_whitelists(backend, email):
    """
    Validates allowed domains and emails against the following settings:
        GOOGLE_WHITE_LISTED_DOMAINS
        GOOGLE_WHITE_LISTED_EMAILS

    All domains and emails are allowed if setting is an empty list.
    """
    emails = setting('GOOGLE_WHITE_LISTED_EMAILS', [])
    domains = setting('GOOGLE_WHITE_LISTED_DOMAINS', [])
    if emails and email in emails:
        return  # you're good
    if domains and email.split('@', 1)[1] not in domains:
        raise AuthFailed(backend, 'Domain not allowed')
Пример #16
0
    def auth_complete(self, *args, **kwargs):
        """Performs check of authentication in VKontakte, returns User if
        succeeded"""
        app_cookie = 'vk_app_' + self.APP_ID

        if not 'id' in self.request.GET or \
           not app_cookie in self.request.COOKIES:
            raise ValueError('VKontakte authentication is not completed')

        cookie_dict = dict(
            item.split('=')
            for item in self.request.COOKIES[app_cookie].split('&'))
        check_str = ''.join(item + '=' + cookie_dict[item]
                            for item in ['expire', 'mid', 'secret', 'sid'])

        hash = md5(check_str + setting('VKONTAKTE_APP_SECRET')).hexdigest()

        if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time():
            raise ValueError('VKontakte authentication failed: invalid hash')
        else:
            kwargs.update({
                'auth': self,
                'response': self.user_data(cookie_dict['mid']),
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)
Пример #17
0
 def get_user_id(self, details, response):
     """Use google email or id as unique id"""
     user_id = super(GoogleOAuth2Backend,
                     self).get_user_id(details, response)
     if setting('GOOGLE_OAUTH2_USE_UNIQUE_USER_ID', False):
         return response['id']
     return user_id
Пример #18
0
class EvernoteBackend(OAuthBackend):
    """
    Evernote OAuth authentication backend.

    Possible Values:
       {'edam_expires': ['1367525289541'],
        'edam_noteStoreUrl': [
            'https://sandbox.evernote.com/shard/s1/notestore'
        ],
        'edam_shard': ['s1'],
        'edam_userId': ['123841'],
        'edam_webApiUrlPrefix': ['https://sandbox.evernote.com/shard/s1/'],
        'oauth_token': [
            'S=s1:U=1e3c1:E=13e66dbee45:C=1370f2ac245:P=185:A=my_user:'******'H=411443c5e8b20f8718ed382a19d4ae38'
        ]}
    """
    name = 'evernote'

    EXTRA_DATA = [('access_token', 'access_token'),
                  ('oauth_token', 'oauth_token'),
                  ('edam_noteStoreUrl', 'store_url'),
                  ('edam_expires', setting('SOCIAL_AUTH_EXPIRATION',
                                           'expires'))]

    def get_user_details(self, response):
        """Return user details from Evernote account"""
        return {
            USERNAME: response['edam_userId'],
            'email': '',
        }

    def get_user_id(self, details, response):
        return response['edam_userId']
Пример #19
0
def get_backends(force_load=False):
    """
    Entry point to the BACKENDS cache. If BACKENDSCACHE hasn't been
    populated, each of the modules referenced in
    AUTHENTICATION_BACKENDS is imported and checked for a BACKENDS
    definition and if enabled, added to the cache.

    Previously all backends were attempted to be loaded at
    import time of this module, which meant that backends that subclass
    bases found in this module would not have the chance to be loaded
    by the time they were added to this module's BACKENDS dict. See:
    https://github.com/omab/django-social-auth/issues/204

    This new approach ensures that backends are allowed to subclass from
    bases in this module and still be picked up.

    A force_load boolean arg is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    if not BACKENDSCACHE or force_load:
        for auth_backend in setting('AUTHENTICATION_BACKENDS'):
            mod, cls_name = auth_backend.rsplit('.', 1)
            module = import_module(mod)
            backend = getattr(module, cls_name)

            if issubclass(backend, SocialAuthBackend):
                name = backend.name
                backends = getattr(module, 'BACKENDS', {})
                if name in backends and backends[name].enabled():
                    BACKENDSCACHE[name] = backends[name]
    return BACKENDSCACHE
Пример #20
0
class MarketBaseView(ListView):
    template_name = 'market/product_list.html'
    paginate_by = setting('PAGINATE_BY', 20)
    model = Product

    def get_paginate_by(self, queryset):
        return self.request.session.get('paginator', self.paginate_by)
Пример #21
0
def parse_currency(on_date=None):
    f = lambda x: Decimal(x.replace(',', '.'))
    sdate = on_date or strftime("%d.%m.%Y", localtime())
    d, m, y = map(lambda x: int(x), sdate.split('.'))
    rate_date = datetime.date(y, m, d)
    lst_currency = parse_xml_currency(currency_xml_input(sdate))
    from nnmware.apps.money.models import ExchangeRate, Currency
    currencies = Currency.objects.all().values_list('code', flat=True)
    for currency in lst_currency:
        charcode = currency['CharCode']
        if charcode in currencies and charcode != setting('DEFAULT_CURRENCY', 'RUB'):
            curr = Currency.objects.get(code=charcode)
            # noinspection PyBroadException
            try:
                rate = ExchangeRate.objects.get(date=rate_date, currency=curr)
            except:
                rate = ExchangeRate()
                rate.date = rate_date
                rate.currency = curr
            rate.nominal = currency['Nominal']
            rate.official_rate = f(currency['Value'])
            if not rate.rate:
                rate.rate = f(currency['Value'])
            rate.save()
    return None
Пример #22
0
def get_backends(force_load=False):
    """
    Entry point to the BACKENDS cache. If BACKENDSCACHE hasn't been
    populated, each of the modules referenced in
    AUTHENTICATION_BACKENDS is imported and checked for a BACKENDS
    definition and if enabled, added to the cache.

    Previously all backends were attempted to be loaded at
    import time of this module, which meant that backends that subclass
    bases found in this module would not have the chance to be loaded
    by the time they were added to this module's BACKENDS dict. See:
    https://github.com/omab/django-social-auth/issues/204

    This new approach ensures that backends are allowed to subclass from
    bases in this module and still be picked up.

    A force_load boolean arg is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    if not BACKENDSCACHE or force_load:
        for auth_backend in setting('AUTHENTICATION_BACKENDS'):
            mod, cls_name = auth_backend.rsplit('.', 1)
            module = import_module(mod)
            backend = getattr(module, cls_name)

            if issubclass(backend, SocialAuthBackend):
                name = backend.name
                backends = getattr(module, 'BACKENDS', {})
                if name in backends and backends[name].enabled():
                    BACKENDSCACHE[name] = backends[name]
    return BACKENDSCACHE
Пример #23
0
 def auth_extra_arguments(self):
     """Return extra arguments needed on auth process, setting is per
     backend and defined by:
         <backend name in uppercase>_AUTH_EXTRA_ARGUMENTS.
     """
     backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
     return setting(backend_name + '_AUTH_EXTRA_ARGUMENTS', {})
Пример #24
0
class YahooOAuthBackend(OAuthBackend):
    """Yahoo OAuth authentication backend"""
    name = 'yahoo-oauth'

    EXTRA_DATA = [
        ('guid', 'id'),
        ('access_token', 'access_token'),
        ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires'))
    ]

    def get_user_id(self, details, response):
        return response['guid']

    def get_user_details(self, response):
        """Return user details from Yahoo Profile"""
        fname = response.get('givenName')
        lname = response.get('familyName')
        if 'emails' in response:
            email = response.get('emails')[0]['handle']
        else:
            email = ''
        return {USERNAME:     response.get('nickname'),
                'email':      email,
                'fullname':   '%s %s' % (fname, lname),
                'first_name': fname,
                'last_name':  lname}
Пример #25
0
class LiveBackend(OAuthBackend):
    name = 'live'

    EXTRA_DATA = [
        ('id', 'id'),
        ('access_token', 'access_token'),
        ('reset_token', 'reset_token'),
        ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')),
        ('email', 'email'),
        ('first_name', 'first_name'),
        ('last_name', 'last_name'),
    ]

    def get_user_id(self, details, response):
        return response['id']

    def get_user_details(self, response):
        """Return user details from Live Connect account"""
        try:
            email = response['emails']['account']
        except KeyError:
            email = ''

        return {
            USERNAME: response.get('name'),
            'email': email,
            'first_name': response.get('first_name'),
            'last_name': response.get('last_name')
        }
Пример #26
0
    def extra_data(self, user, uid, response, details):
        """Return defined extra data names to store in extra_data field.
        Settings will be inspected to get more values names that should be
        stored on extra_data field. Setting name is created from current
        backend name (all uppercase) plus _SREG_EXTRA_DATA and
        _AX_EXTRA_DATA because values can be returned by SimpleRegistration
        or AttributeExchange schemas.

        Both list must be a value name and an alias mapping similar to
        SREG_ATTR, OLD_AX_ATTRS or AX_SCHEMA_ATTRS
        """
        name = self.name.replace('-', '_').upper()
        sreg_names = setting(name + '_SREG_EXTRA_DATA')
        ax_names = setting(name + '_AX_EXTRA_DATA')
        data = self.values_from_response(response, sreg_names, ax_names)
        return data
Пример #27
0
 def auth_extra_arguments(self):
     """Return extra arguments needed on auth process, setting is per
     backend and defined by:
         <backend name in uppercase>_AUTH_EXTRA_ARGUMENTS.
     """
     backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
     return setting(backend_name + '_AUTH_EXTRA_ARGUMENTS', {})
Пример #28
0
    def extra_data(self, user, uid, response, details):
        """Return defined extra data names to store in extra_data field.
        Settings will be inspected to get more values names that should be
        stored on extra_data field. Setting name is created from current
        backend name (all uppercase) plus _SREG_EXTRA_DATA and
        _AX_EXTRA_DATA because values can be returned by SimpleRegistration
        or AttributeExchange schemas.

        Both list must be a value name and an alias mapping similar to
        SREG_ATTR, OLD_AX_ATTRS or AX_SCHEMA_ATTRS
        """
        name = self.name.replace('-', '_').upper()
        sreg_names = setting(name + '_SREG_EXTRA_DATA')
        ax_names = setting(name + '_AX_EXTRA_DATA')
        data = self.values_from_response(response, sreg_names, ax_names)
        return data
Пример #29
0
 def request_token_extra_arguments(self):
     """Return extra arguments needed on request-token process,
     setting is per backend and defined by:
         <backend name in uppercase>_REQUEST_TOKEN_EXTRA_ARGUMENTS.
     """
     backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
     return setting(backend_name + '_REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
Пример #30
0
 def get_user_id(self, details, response):
     """Use google email or id as unique id"""
     user_id = super(GoogleOAuth2Backend, self).get_user_id(details,
                                                            response)
     if setting('GOOGLE_OAUTH2_USE_UNIQUE_USER_ID', False):
         return response['id']
     return user_id
Пример #31
0
    def expiration_datetime(self):
        """Return provider session live seconds. Returns a timedelta ready to
        use with session.set_expiry().

        If provider returns a timestamp instead of session seconds to live, the
        timedelta is inferred from current time (using UTC timezone). None is
        returned if there's no value stored or it's invalid.
        """
        name = setting('SOCIAL_AUTH_EXPIRATION', 'expires')
        if self.extra_data and name in self.extra_data:
            try:
                expires = int(self.extra_data.get(name))
            except (ValueError, TypeError):
                return None

            now = datetime.now()
            now_timestamp = time.mktime(now.timetuple())

            # Detect if expires is a timestamp
            if expires > now_timestamp:  # expires is a datetime
                return datetime.utcfromtimestamp(expires) \
                               .replace(tzinfo=utc) - \
                       now.replace(tzinfo=utc)
            else:  # expires is a timedelta
                return timedelta(seconds=expires)
Пример #32
0
    def auth_complete(self, *args, **kwargs):
        """Performs check of authentication in VKontakte, returns User if
        succeeded"""
        app_cookie = 'vk_app_' + self.APP_ID

        if not 'id' in self.request.GET or \
           not app_cookie in self.request.COOKIES:
            raise ValueError('VKontakte authentication is not completed')

        cookie_dict = dict(item.split('=') for item in
                                self.request.COOKIES[app_cookie].split('&'))
        check_str = ''.join(item + '=' + cookie_dict[item]
                                for item in ['expire', 'mid', 'secret', 'sid'])

        hash = md5(check_str + setting('VKONTAKTE_APP_SECRET')).hexdigest()

        if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time():
            raise ValueError('VKontakte authentication failed: invalid hash')
        else:
            kwargs.update({
                'auth': self,
                'response': self.user_data(cookie_dict['mid']),
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)
Пример #33
0
def parse_currency(on_date=None):
    f = lambda x: Decimal(x.replace(',', '.'))
    sdate = on_date or strftime("%d.%m.%Y", localtime())
    d, m, y = map(lambda x: int(x), sdate.split('.'))
    rate_date = datetime.date(y, m, d)
    lst_currency = parse_xml_currency(currency_xml_input(sdate))
    from nnmware.apps.money.models import ExchangeRate, Currency
    currencies = Currency.objects.all().values_list('code', flat=True)
    for currency in lst_currency:
        charcode = currency['CharCode']
        if charcode in currencies and charcode != setting(
                'DEFAULT_CURRENCY', 'RUB'):
            curr = Currency.objects.get(code=charcode)
            # noinspection PyBroadException
            try:
                rate = ExchangeRate.objects.get(date=rate_date, currency=curr)
            except:
                rate = ExchangeRate()
                rate.date = rate_date
                rate.currency = curr
            rate.nominal = currency['Nominal']
            rate.official_rate = f(currency['Value'])
            if not rate.rate:
                rate.rate = f(currency['Value'])
            rate.save()
    return None
Пример #34
0
    def add(self, user, email):
        """
        Add a new validation process entry
        """
        while True:
            key = get_user_model().objects.make_random_password(70)
            try:
                EmailValidation.objects.get(key=key)
            except EmailValidation.DoesNotExist as emerr:
                self.key = key
                break

        if setting('REQUIRE_EMAIL_CONFIRMATION', True):
            template_body = "email/validation.txt"
            template_subject = "email/validation_subject.txt"
            site_name, domain = Site.objects.get_current(
            ).name, Site.objects.get_current().domain
            body = loader.get_template(template_body).render(Context(locals()))
            subject = loader.get_template(template_subject)
            subject = subject.render(Context(locals())).strip()
            send_mail(subject=subject,
                      message=body,
                      from_email=None,
                      recipient_list=[email])
            user = get_user_model().objects.get(username=str(user))
            self.filter(user=user).delete()
        return self.create(user=user, key=key, email=email)
Пример #35
0
 def request_token_extra_arguments(self):
     """Return extra arguments needed on request-token process,
     setting is per backend and defined by:
         <backend name in uppercase>_REQUEST_TOKEN_EXTRA_ARGUMENTS.
     """
     backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
     return setting(backend_name + '_REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
Пример #36
0
def comment_add_oldver(request, content_type, object_id, parent_id=None):
    """
    Its Ajax posted comments
    """
    # noinspection PyBroadException
    try:
        if not request.user.is_authenticated():
            raise AccessError
        comment = Nnmcomment()
        comment.user = request.user
        comment.content_type = ContentType.objects.get_for_id(
            int(content_type))
        comment.object_id = int(object_id)
        comment.ip = request.META['REMOTE_ADDR']
        comment.user_agent = request.META['HTTP_USER_AGENT']
        comment.comment = request.POST['comment']
        if not len(comment.comment):
            raise AccessError
        kwargs = {'content_type': content_type, 'object_id': object_id}
        if parent_id is not None:
            comment.parent_id = int(parent_id)
        comment.save()
        action.send(request.user,
                    verb=_('commented'),
                    action_type=ACTION_COMMENTED,
                    description=comment.comment,
                    target=comment.content_object,
                    request=request)
        avatar_id = False
        kwargs['parent_id'] = comment.pk
        reply_link = reverse("jcomment_parent_add", kwargs=kwargs)
        comment_text = linebreaksbr(comment.comment)
        comment_date = comment.created_date.strftime(
            setting('COMMENT_DATE_FORMAT', '%d %b %Y %H:%M %p'))
        # noinspection PyBroadException
        try:
            avatar_id = comment.user.avatar.pk
        except:
            pass
        # noinspection PyUnresolvedReferences
        payload = {
            'success': True,
            'id': comment.pk,
            'username': comment.user.get_name,
            'username_url': comment.get_absolute_url(),
            'comment': comment_text,
            'avatar_id': avatar_id,
            'comment_date': comment_date,
            'reply_link': reply_link,
            'object_comments': comment.content_object.comments
        }
    except AccessError as aerr:
        payload = {
            'success': False,
            'error': _('You are not allowed for add comment')
        }
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
Пример #37
0
def room_rates(request):
    try:
        json_data = json.loads(request.body)
        currency = Currency.objects.get(code=setting('DEFAULT_CURRENCY', 'RUB'))
        room = Room.objects.get(id=int(json_data['room_id']))
        if request.user not in room.hotel.admins.all() and not request.user.is_superuser:
            raise UserNotAllowed
            # find settlements keys in data
        all_settlements, all_discounts = [], []
        for k in json_data.keys():
            if k[0] == 's':
                all_settlements.append(k)
            elif k[0] == 'd':
                all_discounts.append(k)
        for i, v in enumerate(json_data['dates']):
            on_date = datetime.fromtimestamp(time.mktime(time.strptime(v, "%d%m%Y")))
            if 'placecount' in json_data.keys():
                try:
                    placecount = int(json_data['placecount'][i])
                    try:
                        min_days = int(json_data['min_days'][i])
                    except:
                        min_days = None
                        # store availability
                    availability, created = Availability.objects.get_or_create(date=on_date, room=room)
                    availability.placecount = placecount
                    if min_days is not None:
                        availability.min_days = min_days
                    availability.save()
                except ValueError:
                    pass
            for k in all_discounts:
                try:
                    discount_id = int(k[1:])
                    discount = Discount.objects.get(id=discount_id)
                    value = int(json_data[k][i])
                    room_discount, created = RoomDiscount.objects.get_or_create(date=on_date, discount=discount,
                                                                                room=room)
                    room_discount.value = value
                    room_discount.save()
                except ValueError:
                    pass
            for k in all_settlements:
                try:
                    settlement_id = int(k[1:])
                    settlement = SettlementVariant.objects.get(id=settlement_id)
                    price = int(json_data[k][i])
                    placeprice, created = PlacePrice.objects.get_or_create(date=on_date, settlement=settlement)
                    placeprice.amount = price
                    placeprice.currency = currency
                    placeprice.save()
                except ValueError:
                    pass
        payload = {'success': True}
    except UserNotAllowed:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
Пример #38
0
 def build_absolute_uri(self, path=None):
     """Build absolute URI for given path. Replace http:// schema with
     https:// if SOCIAL_AUTH_REDIRECT_IS_HTTPS is defined.
     """
     uri = self.request.build_absolute_uri(path)
     if setting('SOCIAL_AUTH_REDIRECT_IS_HTTPS'):
         uri = uri.replace('http://', 'https://')
     return uri
Пример #39
0
 def build_absolute_uri(self, path=None):
     """Build absolute URI for given path. Replace http:// schema with
     https:// if SOCIAL_AUTH_REDIRECT_IS_HTTPS is defined.
     """
     uri = self.request.build_absolute_uri(path)
     if setting('SOCIAL_AUTH_REDIRECT_IS_HTTPS'):
         uri = uri.replace('http://', 'https://')
     return uri
Пример #40
0
 def __init__(self, filetype='file', upload_dir='files', size_limit=10485760):
     self._upload_dir = os.path.join(settings.MEDIA_ROOT, upload_dir, get_date_directory())
     self._filetype = filetype
     if filetype == 'image':
         self._save_format = setting('IMAGE_UPLOAD_FORMAT', 'JPEG')
     else:
         self._save_format = None
     self._size_limit = size_limit
Пример #41
0
def dsa_urlopen(*args, **kwargs):
    """Like urllib2.urlopen but sets a timeout defined by
    SOCIAL_AUTH_URLOPEN_TIMEOUT setting if defined (and not already in
    kwargs)."""
    timeout = setting('SOCIAL_AUTH_URLOPEN_TIMEOUT')
    if timeout and 'timeout' not in kwargs:
        kwargs['timeout'] = timeout
    return urlopen(*args, **kwargs)
Пример #42
0
 def __init__(self, filetype="file", uploadDirectory="files", sizeLimit=10485760):
     self._upload_dir = os.path.join(settings.MEDIA_ROOT, uploadDirectory, get_date_directory())
     self._filetype = filetype
     if filetype == "image":
         self._save_format = setting("IMAGE_UPLOAD_FORMAT", "JPEG")
     else:
         self._save_format = None
     self._size_limit = sizeLimit
Пример #43
0
def make_thumbnail(photo_url,
                   width=None,
                   height=None,
                   aspect=None,
                   root=settings.MEDIA_ROOT,
                   url_root=settings.MEDIA_URL):
    """ create thumbnail """

    # one of width/height is required
    assert (width is not None) or (height is not None)

    if not photo_url:
        return None

    th_url = _get_thumbnail_path(photo_url, width, height, aspect)
    th_path = get_path_from_url(th_url, root, url_root)
    photo_path = get_path_from_url(photo_url, root, url_root)

    if _has_thumbnail(photo_url, width, height, root, url_root, aspect):
        # thumbnail already exists
        if not (os.path.getmtime(photo_path) > os.path.getmtime(th_path)):
            # if photo mtime is newer than thumbnail recreate thumbnail
            return th_url

    # make thumbnail

    # get original image size
    orig_w, orig_h = get_image_size(photo_url, root, url_root)
    if (orig_w is None) and (orig_h is None):
        # something is wrong with image
        return photo_url

    # make proper size
    if (width is not None) and (height is not None):
        if (orig_w == width) and (orig_h == height):
            # same dimensions
            return None
        size = (width, height)
    elif width is not None:
        if orig_w == width:
            # same dimensions
            return None
        size = (width, orig_h)
    elif height is not None:
        if orig_h == height:
            # same dimensions
            return None
        size = (orig_w, height)

    try:
        img = Image.open(photo_path).copy()
        if aspect:
            img = ImageOps.fit(img, size, Image.ANTIALIAS, (0.5, 0.5))
        img.thumbnail(size, Image.ANTIALIAS)
        img.save(th_path, quality=setting('THUMBNAIL_QUALITY', 85))
    except:
        return photo_url
    return th_url
Пример #44
0
def convert_to_client_currency(amount, rate):
    try:
        if setting('OFFICIAL_RATE', True):
            exchange = rate.official_rate
        else:
            exchange = rate.rate
        return int((amount * rate.nominal) / exchange)
    except:
        return int(amount)
Пример #45
0
def convert_to_client_currency(amount, rate):
    try:
        if setting('OFFICIAL_RATE', True):
            exchange = rate.official_rate
        else:
            exchange = rate.rate
        return int((amount * rate.nominal) / exchange)
    except:
        return int(amount)
Пример #46
0
 def extra_data(self, user, uid, response, details):
     """Return users extra data"""
     # BrowserID sends timestamp for expiration date, here we
     # convert it to the remaining seconds
     expires = (response['expires'] / 1000) - time.mktime(now().timetuple())
     return {
         'audience': response['audience'],
         'issuer': response['issuer'],
         setting('SOCIAL_AUTH_EXPIRATION', 'expires'): expires
     }
Пример #47
0
 def extra_data(self, user, uid, response, details):
     """Return users extra data"""
     # BrowserID sends timestamp for expiration date, here we
     # convert it to the remaining seconds
     expires = (response['expires'] / 1000) - time.mktime(now().timetuple())
     return {
         'audience': response['audience'],
         'issuer': response['issuer'],
         setting('SOCIAL_AUTH_EXPIRATION', 'expires'): expires
     }
Пример #48
0
def room_rates(request):
    try:
        json_data = json.loads(request.body)
        currency = Currency.objects.get(code=setting('DEFAULT_CURRENCY', 'RUB'))
        hotel = Hotel.objects.get(id=int(json_data['hotel']))
        if request.user not in hotel.admins.all() and not request.user.is_superuser:
            raise UserNotAllowed
            # find settlements keys in data
        all_rooms, all_avail, all_limits = [], [], []
        for k in json_data.keys():
            if k[0] == 'r':
                all_rooms.append(k)
            elif k[0] == 'a':
                all_avail.append(k)
            elif k[0] == 'l':
                all_limits.append(k)
        for i, v in enumerate(json_data['dates']):
            on_date = datetime.fromtimestamp(time.mktime(time.strptime(v, "%d%m%Y")))
            for k in all_rooms:
                try:
                    settlement_id = int(k[1:])
                    settlement = SettlementVariant.objects.get(id=settlement_id)
                    price = int(json_data[k][i])
                    placeprice, created = PlacePrice.objects.get_or_create(date=on_date, settlement=settlement)
                    placeprice.amount = price
                    placeprice.currency = currency
                    placeprice.save()
                except ValueError:
                    pass
            for k in all_avail:
                try:
                    room_id = int(k[1:])
                    room = Room.objects.get(pk=room_id)
                    p = json_data[k][i]
                    if len(p.strip()) == 0:
                        placecount = 0
                    else:
                        placecount = int(p)
                    availability, created = Availability.objects.get_or_create(date=on_date, room=room)
                    availability.placecount = placecount
                    try:
                        min_days = int(json_data['l' + k[1:]][i])
                    except:
                        min_days = None
                    if min_days is not None:
                        availability.min_days = min_days
                    availability.save()
                except ValueError:
                    pass
        payload = {'success': True}
    except UserNotAllowed:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
Пример #49
0
def room_rates(request):
    try:
        json_data = json.loads(request.body)
        currency = Currency.objects.get(code=setting('DEFAULT_CURRENCY', 'RUB'))
        hotel = Hotel.objects.get(id=int(json_data['hotel']))
        if request.user not in hotel.admins.all() and not request.user.is_superuser:
            raise UserNotAllowed
            # find settlements keys in data
        all_rooms, all_avail, all_limits = [], [], []
        for k in json_data.keys():
            if k[0] == 'r':
                all_rooms.append(k)
            elif k[0] == 'a':
                all_avail.append(k)
            elif k[0] == 'l':
                all_limits.append(k)
        for i, v in enumerate(json_data['dates']):
            on_date = datetime.fromtimestamp(time.mktime(time.strptime(v, "%d%m%Y")))
            for k in all_rooms:
                try:
                    settlement_id = int(k[1:])
                    settlement = SettlementVariant.objects.get(id=settlement_id)
                    price = int(json_data[k][i])
                    placeprice, created = PlacePrice.objects.get_or_create(date=on_date, settlement=settlement)
                    placeprice.amount = price
                    placeprice.currency = currency
                    placeprice.save()
                except ValueError as valerr:
                    pass
            for k in all_avail:
                try:
                    room_id = int(k[1:])
                    room = Room.objects.get(pk=room_id)
                    p = json_data[k][i]
                    if len(p.strip()) == 0:
                        placecount = 0
                    else:
                        placecount = int(p)
                    availability, created = Availability.objects.get_or_create(date=on_date, room=room)
                    availability.placecount = placecount
                    try:
                        min_days = int(json_data['l' + k[1:]][i])
                    except:
                        min_days = None
                    if min_days is not None:
                        availability.min_days = min_days
                    availability.save()
                except ValueError as valerr:
                    pass
        payload = {'success': True}
    except UserNotAllowed as naerr:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
Пример #50
0
 def user_data(self, access_token, *args, **kwargs):
     """Return user data provided"""
     fields_selectors = LINKEDIN_FIELD_SELECTORS + \
                        setting('LINKEDIN_EXTRA_FIELD_SELECTORS', [])
     url = LINKEDIN_CHECK_AUTH + ':(%s)' % ','.join(fields_selectors)
     request = self.oauth_request(access_token, url)
     raw_xml = self.fetch_response(request)
     try:
         return to_dict(ElementTree.fromstring(raw_xml))
     except (ExpatError, KeyError, IndexError):
         return None
Пример #51
0
 def user_data(self, access_token, *args, **kwargs):
     """Loads user data from Orkut service"""
     fields = ORKUT_DEFAULT_DATA
     if setting("ORKUT_EXTRA_DATA"):
         fields += "," + setting("ORKUT_EXTRA_DATA")
     scope = ORKUT_SCOPE + setting("ORKUT_EXTRA_SCOPE", [])
     params = {
         "method": "people.get",
         "id": "myself",
         "userId": "@me",
         "groupId": "@self",
         "fields": fields,
         "scope": " ".join(scope),
     }
     request = self.oauth_request(access_token, ORKUT_REST_ENDPOINT, params)
     response = dsa_urlopen(request.to_url()).read()
     try:
         return json.loads(response)["data"]
     except (ValueError, KeyError):
         return None
Пример #52
0
def amount_request_currency(request, amount):
    try:
        currency = Currency.objects.get(code=request.COOKIES['currency'])
        rate = ExchangeRate.objects.filter(currency=currency).filter(date__lte=now()).order_by('-date')[0]
        if setting('OFFICIAL_RATE', True):
            exchange = rate.official_rate
        else:
            exchange = rate.rate
        return int((amount * rate.nominal) / exchange)
    except:
        return int(amount)
Пример #53
0
def user_rate_from_request(request):
    try:
        user_currency = request.COOKIES['currency']
    except:
        user_currency = setting('CURRENCY', 'RUB')
    try:
        rate = ExchangeRate.objects.select_related().filter(currency__code=user_currency).\
            filter(date__lte=now()).order_by('-date')[0]
        return rate
    except:
        return None
Пример #54
0
def user_rate_from_request(request):
    try:
        user_currency = request.COOKIES['currency']
    except:
        user_currency = setting('CURRENCY', 'RUB')
    try:
        rate = ExchangeRate.objects.select_related().filter(currency__code=user_currency).\
            filter(date__lte=now()).order_by('-date')[0]
        return rate
    except:
        return None
Пример #55
0
def make_thumbnail(photo_url, width=None, height=None, aspect=None,
                   root=settings.MEDIA_ROOT, url_root=settings.MEDIA_URL):
    """ create thumbnail """

    # one of width/height is required
    assert (width is not None) or (height is not None)

    if not photo_url:
        return None

    th_url = _get_thumbnail_path(photo_url, width, height, aspect)
    th_path = get_path_from_url(th_url, root, url_root)
    photo_path = get_path_from_url(photo_url, root, url_root)

    if _has_thumbnail(photo_url, width, height, root, url_root, aspect):
        # thumbnail already exists
        if not (os.path.getmtime(photo_path) > os.path.getmtime(th_path)):
            # if photo mtime is newer than thumbnail recreate thumbnail
            return th_url

    # make thumbnail

    # get original image size
    orig_w, orig_h = get_image_size(photo_url, root, url_root)
    if (orig_w is None) and (orig_h is None):
        # something is wrong with image
        return photo_url

    # make proper size
    if (width is not None) and (height is not None):
        if (orig_w == width) and (orig_h == height):
            # same dimensions
            return None
        size = (width, height)
    elif width is not None:
        if orig_w == width:
            # same dimensions
            return None
        size = (width, orig_h)
    elif height is not None:
        if orig_h == height:
            # same dimensions
            return None
        size = (orig_w, height)

    try:
        img = Image.open(photo_path).copy()
        if aspect:
            img = ImageOps.fit(img, size, Image.ANTIALIAS, (0.5, 0.5))
        img.thumbnail(size, Image.ANTIALIAS)
        img.save(th_path, quality=setting('THUMBNAIL_QUALITY', 85))
    except:
        return photo_url
    return th_url
Пример #56
0
class VKontakteAuth(BaseAuth):
    """VKontakte OpenAPI authorization mechanism"""
    AUTH_BACKEND = VKontakteBackend
    APP_ID = setting('VKONTAKTE_APP_ID')

    def user_data(self, access_token, *args, **kwargs):
        return dict(self.request.GET)

    def auth_html(self):
        """Returns local VK authentication page, not necessary for
        VK to authenticate.
        """
        from django.template import RequestContext, loader

        dict = {'VK_APP_ID': self.APP_ID, 'VK_COMPLETE_URL': self.redirect}

        vk_template = loader.get_template(LOCAL_HTML)
        context = RequestContext(self.request, dict)

        return vk_template.render(context)

    def auth_complete(self, *args, **kwargs):
        """Performs check of authentication in VKontakte, returns User if
        succeeded"""
        app_cookie = 'vk_app_' + self.APP_ID

        if not 'id' in self.request.GET or \
           not app_cookie in self.request.COOKIES:
            raise ValueError('VKontakte authentication is not completed')

        cookie_dict = dict(
            item.split('=')
            for item in self.request.COOKIES[app_cookie].split('&'))
        check_str = ''.join(item + '=' + cookie_dict[item]
                            for item in ['expire', 'mid', 'secret', 'sid'])

        hash = md5(check_str + setting('VKONTAKTE_APP_SECRET')).hexdigest()

        if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time():
            raise ValueError('VKontakte authentication failed: invalid hash')
        else:
            kwargs.update({
                'auth': self,
                'response': self.user_data(cookie_dict['mid']),
                self.AUTH_BACKEND.name: True
            })
            return authenticate(*args, **kwargs)

    @property
    def uses_redirect(self):
        """VKontakte does not require visiting server url in order
        to do authentication, so auth_xxx methods are not needed to be called.
        Their current implementation is just an example"""
        return False