def to_representation(self, *args, **kwargs): ret = super(LongUserPublicRetrieveSerializer, self).to_representation(*args, **kwargs) is_bookmarked_projects_on_user_enabled = int(get_channel_setting(self.context['request'].channel, "ENABLE_PUBLIC_USER_BOOKMARKED_PROJECTS")[0]) if not is_bookmarked_projects_on_user_enabled: ret["bookmarked_projects"] = None return ret
def required_organization(request, pk): allow_no_org = int( get_channel_setting(request.channel, "CAN_CREATE_PROJECTS_WITHOUT_ORGANIZATION")[0]) if not allow_no_org and not pk and request.method.upper() != "PATCH": raise exceptions.ValidationError( {'organization': 'This field is required.'})
def get_bookmark_count(self, instance): is_bookmark_count_enabled = int( get_channel_setting(self.context['request'].channel, "ENABLE_PROJECT_BOOKMARK_COUNT")[0]) if is_bookmark_count_enabled: return instance.bookmark_count() return None
def check(self, user, password): amount = int(get_channel_setting(user.channel.slug, "CANT_REUSE_LAST_PASSWORDS")[0]) if amount: history = PasswordHistory.objects.filter(user=user).order_by('-id')[:amount] for item in history: algorithm = item.hashed_password.split("$")[0] hasher = get_hasher(algorithm=algorithm) matches = hasher.verify(password, item.hashed_password) if matches: raise serializers.ValidationError("You cannot reuse the last {} used passwords.".format(amount))
def filter_out(queryset, setting_name, channel): """ Remove unwanted results from queryset """ kwargs = {} excluded_list = get_channel_setting(channel, setting_name) for excluded in excluded_list: key, value = excluded.split(":") key = key.strip().strip("\"").strip("''") value = value.strip().strip("\"").strip("''") kwargs[key] = value queryset = queryset.exclude(**kwargs) return queryset
def get_permissions(self): request = self.get_serializer_context()['request'] if self.action == 'create': if int( get_channel_setting( request.channel, "CAN_CREATE_PROJECTS_IN_ANY_ORGANIZATION")[0]): self.permission_classes = (permissions.IsAuthenticated, ) else: self.permission_classes = ( permissions.IsAuthenticated, ProjectCreateOwnsOrIsOrganizationMember) if self.action == 'partial_update': self.permission_classes = ( permissions.IsAuthenticated, ProjectRetrieveOwnsOrIsOrganizationMember) if self.action == 'retrieve': self.permission_classes = () if self.action == 'manageable': self.permission_classes = (permissions.IsAuthenticated, ) if self.action == 'close': self.permission_classes = ( permissions.IsAuthenticated, ProjectRetrieveOwnsOrIsOrganizationMember) if self.action in ['bookmark', 'unbookmark', 'bookmarked']: self.permission_classes = self.get_bookmark_permissions() if self.action == 'export_applied_users': self.permission_classes = ( permissions.IsAuthenticated, ProjectRetrieveOwnsOrIsOrganizationMember) if self.action == 'post': self.permission_classes = ( permissions.IsAuthenticated, ProjectRetrieveOwnsOrIsOrganizationMember) if self.action == 'post_patch_delete': self.permission_classes = ( permissions.IsAuthenticated, ProjectRetrieveOwnsOrIsOrganizationMember) return super(ProjectResourceViewSet, self).get_permissions()
def get_permissions(self): request = self.get_serializer_context()['request'] if self.action in ['list', 'partial_update']: self.permission_classes = (permissions.IsAuthenticated, ProjectApplyPermission) if self.action == 'apply': if int( get_channel_setting(request.channel, "UNAUTHENTICATED_APPLY")[0]): self.permission_classes = () else: self.permission_classes = (permissions.IsAuthenticated, ) if self.action == 'unapply': self.permission_classes = (permissions.IsAuthenticated, ) return super(ApplyResourceViewSet, self).get_permissions()
def wrapper(self, *args, **kwargs): representation = function(self, *args, **kwargs) request = self.context["request"] expiry_time = int( get_channel_setting(request.channel, "EXPIRE_PASSWORD_IN")[0]) if expiry_time: representation["expired_password"] = False entry = PasswordHistory.objects.filter( user=request.user).order_by('-pk').first() if not entry: representation["expired_password"] = True else: delta = relativedelta(seconds=expiry_time) if timezone.now() - delta > entry.created_date: representation["expired_password"] = True return representation
def is_email_enabled(channel, email): """ Emails are activated by default. Create a ChannelSetting object with the email name to disable it. You can also control enabled emails through OVP_CORE.OVERRIDE_ENABLED_EMAILS, OVP_CORE.OVERRIDE_DISABLED_EMAILS and OVP_CORE.DISABLE_EMAILS_BY_DEFAULT. """ disabled_emails = get_channel_setting(channel, "DISABLE_EMAIL") override_disabled = get_settings().get('OVERRIDE_DISABLED_EMAILS', []) override_enabled = get_settings().get('OVERRIDE_ENABLED_EMAILS', []) disable_by_default = get_settings().get('DISABLE_EMAILS_BY_DEFAULT', False) if email in override_disabled: return False if email in override_enabled: return True if disable_by_default: return False if email in disabled_emails: return False return True
def check_user_search_enabled(self, channel): if int(get_channel_setting(channel, "ENABLE_USER_SEARCH")[0]) == 0: raise PermissionDenied
def inject_client_url(channel, ctx): ctx['CLIENT_URL'] = get_channel_setting(channel, "CLIENT_URL")[0] return ctx
def __init__(self, organization, async_mail=None, locale=None): email = get_channel_setting(organization.channel.slug, "ADMIN_MAIL")[0] super(OrganizationAdminMail, self).__init__(email, channel=organization.channel.slug, async_mail=async_mail, locale=locale)
def update_address(sender, instance, **kwargs): if kwargs.get('raw', False): # pragma: no cover return None maps_language = get_channel_setting(instance.channel.slug, "MAPS_API_LANGUAGE")[0] addressline = instance.typed_address url = 'https://maps.googleapis.com/maps/api/geocode/json?language={}&address={}'.format( maps_language, addressline) key = os.environ.get('GOOGLE_MAPS_KEY', None) if key: #pragma: no cover url = '{}&key={}'.format(url, key) with vcr.use_cassette("/tmp/google-address", record_mode="new_episodes"): r = requests.get(url) data = r.json() # Iterate through address components instance.address_components.clear() if len(data['results']) > 0: for component in data['results'][0]['address_components']: # TODO: Do not work only with first result # Look for component with same name and type ac = AddressComponent.objects.annotate( count=Count('types')).filter( long_name=component['long_name'], short_name=component['short_name']) for component_type in component['types']: ac = ac.filter(types__name=component_type) ac = ac.filter(count=len(component['types'])) if not ac.count(): # Component not found, creating ac = AddressComponent(long_name=component['long_name'], short_name=component['short_name']) ac.save(object_channel=instance.channel.slug) else: ac = ac.first() ac.types.clear() ac.save() # Add types for component for ctype in component['types']: try: at = AddressComponentType.objects.get(name=ctype) except ObjectDoesNotExist: at = AddressComponentType(name=ctype) at.save(object_channel=instance.channel.slug) ac.types.add(at) instance.address_components.add(ac) try: if data['results'][0]['geometry']: GoogleAddress.objects.filter(pk=instance.pk).update( lat=data['results'][0]['geometry']['location']['lat'], lng=data['results'][0]['geometry']['location']['lng']) except: #pragma: no cover pass # Using update to avoid post_save signal GoogleAddress.objects.filter(pk=instance.pk).update( address_line=instance.get_address(), city_state=instance.get_city_state())
def __init__(self, project, async_mail=None): email = get_channel_setting(organization.channel.slug, "ADMIN_MAIL")[0] super(ProjectAdminMail, self).__init__(email, channel=project.channel.slug, async_mail=async_mail)