Exemple #1
0
class Users(Document):
	created_at = fields.DateTimeField(
		default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 
		required=True, editable=False,unique=False
	)
	user_id = fields.StringField(max_length=36,required=True,unique=True)
	username = fields.StringField(unique=True, max_length=30)
	email_id = fields.EmailField(unique=True, max_length=254)
	first_name = fields.StringField(max_length=30, required=False, allow_null=True,unique=False)
	last_name = fields.StringField(max_length=30, required=False, null=True,unique=False)
	profile_url = fields.StringField(
		default = "http://profile.ak.fbcdn.net/static-ak/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif",unique=False
	)
	followed_users_list = fields.EmbeddedDocumentListField(FollowingList, required=False, 
		default= [], blank=True,unique=False)
	follower_users_list = fields.EmbeddedDocumentListField(FollowerList, required=False, 
		default= [], blank=True,unique=False)
	gender = fields.StringField(default=None,unique=False, blank=True, required=False)
	push_notifications = fields.BooleanField(default=True, unique=False)
	token = fields.StringField(default=None, blank=True)
	# phone_number = fields.StringField(min_length=10, max_length=10,blank=True, default=None, required=False)
	notifications = fields.EmbeddedDocumentListField(Notifications, required=False, 
		default= [], blank=True,unique=False)
	is_unread_notification = fields.BooleanField(default=False)
	user_bio = fields.StringField(default=None,unique=False, blank=True, required=False)
	favorite_genre = fields.StringField(default=None,unique=False, blank=True, required=False)
	favorite_artist = fields.StringField(default=None,unique=False, blank=True, required=False)
	favorite_instrument = fields.StringField(default=None,unique=False, blank=True, required=False)
	farorite_album = fields.StringField(default=None,unique=False, blank=True, required=False)
	date_of_birth = fields.StringField(default=None,blank=True, required=False)
	gender = fields.StringField(default=None,blank=True, required=False)
	pending_requests = fields.EmbeddedDocumentListField(PendingRequests, required=False, 
		default= [], blank=True,unique=False)
	requested_users = fields.EmbeddedDocumentListField(RequestedUsers, required=False, 
		default= [], blank=True,unique=False)
Exemple #2
0
class User(Document):
    email = fields.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username = fields.StringField(max_length=50, unique=True)
    password = fields.StringField(max_length=128, verbose_name=('password'))

    is_active = fields.BooleanField(default=True)
    is_staff = fields.BooleanField(default=False)
    is_admin = fields.BooleanField(default=False)
    is_superuser = fields.BooleanField(default=False)
    last_login = fields.DateTimeField(default=datetime.now,
                                      verbose_name=('last login'))
    date_joined = fields.DateTimeField(default=datetime.now,
                                       verbose_name=('date joined'))

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ["email"]

    #objects= UserManager()

    def __str__(self):
        return self.username

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self.save()
        return self

    @classmethod
    def create_user(cls, username, password, email):

        now = datetime.datetime.now()

        if email is not None:
            try:
                email_name, domain_part = email.strip().split('@', 1)
            except ValueError:
                pass
            else:
                email = '@'.join([email_name, domain_part.lower()])

        user = cls(username=username, email=email, date_joined=now)
        user.set_password(password)
        user.save()
        return user
class Profile(Document):

    #user = fields.ReferenceField('User')
    user_id = fields.IntField()
    full_name = fields.StringField(max_length=191, blank=True)
    location = fields.DictField({}, blank=True)
    settings = fields.DictField({}, blank=True)
    has_at_least_one_social_account = fields.BooleanField(default=False)
    social_accounts = fields.ListField(fields.DictField({}, blank=True),
                                       blank=True)
    associated_platforms = fields.ListField(fields.DictField(), blank=True)
    channels = fields.ListField(fields.DictField(blank=True), blank=True)
    authorized_devices = fields.ListField(fields.DictField(blank=True),
                                          blank=True)
    birth_date = fields.DateTimeField(blank=True)
    roles = fields.ListField(fields.DictField({}, blank=True), blank=True)
    permissions = fields.ListField(fields.DictField({}, blank=True),
                                   blank=True)
    signed_up_with = fields.StringField(defalut="email")
    signed_up_ip_address = fields.StringField(blank=True)
    singed_up_user_agent = fields.StringField(blank=True)
    logged_in_ip_address = fields.StringField(blank=True)
    logged_in_user_agent = fields.StringField(blank=True)

    meta = {"collection": "auth_profile"}

    def __str__(self):
        return self.mobile_number

    def check_otp(self, otp):
        return check_password(otp, self.otp)
class Status(Document):
    user_id = fields.IntField()
    criteria = fields.EmbeddedDocumentField(StatusCriteria)
    device_id = fields.StringField()
    active = fields.BooleanField()

    @property
    def device(self):
        return Device.objects.get(id=self.device_id)

    def current_value(self):
        return self.criteria.metric_value_for(self.device)

    def current_check(self):
        return self.criteria.operation_check(self.current_value())

    def __str__(self):
        return "{}{}".format(self.device_id, self.criteria)

    @staticmethod
    def only_triggered_for(user_id):
        active = Status.objects.filter(user_id=user_id, active=True)
        triggered_ids = []
        for obj in active:
            if obj.current_check():
                triggered_ids.append(str(obj.id))

        return Status.objects.filter(id__in=triggered_ids)

    @staticmethod
    def for_user(user_id):
        return Status.objects.filter(user_id=user_id)
class ExportedCompressedFile(Document):
    """ Represents exported files
    """
    file_name = fields.StringField()
    file = fields.FileField(
        blank=True, collection_name=GRIDFS_EXPORTED_COMPRESSED_FILE_COLLECTION)
    is_ready = fields.BooleanField(default=False)
    mime_type = fields.StringField()

    @staticmethod
    def get_by_id(object_id):
        """ Get Exported compressed file with the given id

        Args:
            object_id:

        Returns:

        """
        try:
            return ExportedCompressedFile.objects.get(pk=str(object_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as ex:
            raise exceptions.ModelError(ex.message)
Exemple #6
0
class TemplateVersion(Document):
    """
    Storage model for storing different versions of a template.

    :property name str:       the template name being versioned
    :property version seq:    the version for this template
    :property common ref:   a reference to the common information record 
                                in the Template collection
    :property label str:      the label to give to the root element
    :property spec  ref:      the TypeRenderSpec object to use to render the 
                              root element; if not set, this will be generated 
                              dynamically.
    :property tranforms ref:  a reference to a record in Transforms that 
                              identifies the XSL stylesheets
    :property deleted bool:   True if this version is currently deleted
    :property comment str:    A brief (displayable) comment noting what is 
                              different about this version.
    """
    name = fields.StringField(blank=False)
    version = fields.SequenceField(blank=False)
    common = fields.ReferenceField(TemplateCommon, blank=False)
    schema = fields.ReferenceField(SchemaVersion, blank=False)
    extschemas = fields.ListField(SchemaVersion, blank=True, default=[])
    label = fields.StringField()
    spec = fields.ReferenceField(TypeRenderSpec, blank=True)
    # transforms = fields.ReferenceField(Transforms, blank=True)
    deleted = fields.BooleanField(blank=False, default=False)
    comment = fields.StringField(default="")

    @classmethod
    def get_all_by_name(cls, name, include_deleted=False):
        """
        return a list of TemplateVersion records that have given name

        :param name str:  the name of the template to match
        :param include_deleted bool:  if False, return only records that 
                          have not been marked as deleted.
        """
        vers = TemplateVersion.objects.filter(name=name)
        if not include_deleted:
            vers = vers.filter(deleted=False)
        return vers

    @classmethod
    def get_by_version(cls, name, version, include_deleted=False):
        """
        return the TemplateVersion record with a given name and version.

        :param name    str:   the name of the schema to match
        :param version int:   the version of the schema to select
        :param include_deleted bool:  if False, return only records that 
                          have not been marked as deleted.
        
        """
        vers = cls.get_all_by_name(name,
                                   include_deleted).filter(version=version)
        if len(vers) > 0:
            return vers[0]
        return None
Exemple #7
0
class BioSubject(Feature):
    species = fields.ReferenceField(Species)
    subjectname = fields.StringField(max_length=255)
    subjectspeciesname = fields.StringField(max_length=1024)
    subjecttaxon = fields.IntField(default=None, null=True)
    strain = fields.StringField(max_length=1024, default=None, null=True)
    subjectdescription = fields.StringField(default="")
    dob = fields.DateTimeField(default=None, null=True)
    sex = fields.StringField(max_length=1, default=None, null=True)
    cohort = fields.StringField(max_length=10, default=None, null=True)
    changed = fields.BooleanField(default=False)
    comment = fields.StringField(max_length=1024, default=None, null=True)
    do_ignore = fields.BooleanField(default=False)
    centre = fields.StringField(max_length=255, default=None, null=True)

    def GetName(self):
        return self.subjectname
Exemple #8
0
class FormData(dme_Document):
    """Stores data being entered and not yet curated"""
    user = dme_fields.StringField()
    template = dme_fields.StringField()
    name = dme_fields.StringField(unique_with=['user', 'template'])
    schema_element_root = dme_fields.ReferenceField(SchemaElement, blank=True)
    xml_data = dme_fields.StringField(default='')
    xml_data_id = dme_fields.StringField(blank=True)
    isNewVersionOfRecord = dme_fields.BooleanField(default=False)
Exemple #9
0
class OaiSet(dme_Document):
    """
        A set object
    """
    setSpec = dme_fields.StringField(unique=True)
    setName = dme_fields.StringField(unique=True)
    raw = dme_fields.DictField()
    registry = dme_fields.StringField(blank=True)
    harvest = dme_fields.BooleanField(blank=True)
class DynQueryStep(Document):
    """
    Step object created by the administrator.
    """
    # Step name
    name = fields.StringField(blank=False, unique=False)
    # True if the step is not query-able, False else
    output_field = fields.BooleanField(blank=False, unique=False)
    # Relative path to the object, in dot notation
    xpath = fields.StringField(blank=False, unique=False)
    # Define the part of the node concerned by the
    target = fields.StringField(blank=False, unique=False)
    # query, could be name, attribute, or value
    value = fields.StringField(blank=True, unique=False)
    # Define the name of the attribute concerned by
    data_type = fields.StringField(blank=False, unique=False)
    # Define if the there is a restriction to the step
    restriction = fields.BooleanField(blank=True, unique=False)
    # Define the minimum range for multiple choices step
    data_min_range = fields.IntField(blank=True, unique=False)
    # Define the maximum range for multiple choices step
    data_max_range = fields.IntField(blank=True, unique=False)
    # Define the minimum range to infinity
    data_infinity = fields.BooleanField(blank=True, unique=False)  #
    # Define the number of days for date query
    date_range = fields.IntField(blank=True, unique=False)

    @staticmethod
    def get_by_id(dyn_query_step_id):
        """Return a DynQueryStep given its id.

        Args:
            dyn_query_step_id:

        Returns:

        """
        try:
            return DynQueryStep.objects.get(pk=str(dyn_query_step_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as ex:
            raise exceptions.ModelError(str(ex))
Exemple #11
0
class Event(Document):
    title = fields.StringField(max_length=255)
    description = fields.StringField(max_length=255)
    location = fields.StringField(max_length=255)
    landmark = fields.StringField(max_length=255)
    city = fields.StringField(max_length=255)
    coordinates = fields.ListField(fields.FloatField())
    start_timestamp = fields.DateTimeField()
    end_timestamp = fields.DateTimeField()
    banner = fields.StringField()
    #banner = fields.ImageField(upload_to='banners', default="images/None/no-img.jpeg")
    #banner = fields.ImageField(upload_to=fs, default="images/None/no-img.jpeg")
    tags = fields.ListField(fields.StringField())
    recurring = fields.BooleanField(default=False)
    open_event = fields.BooleanField(default=True)
    full_day_event = fields.BooleanField(default=False)
    created_by = fields.IntField()
    user_agent = fields.StringField(blank=True)
    timestamp = fields.DateTimeField(default=datetime.datetime.now)
    updated_at = fields.DateTimeField(default=datetime.datetime.now)
    slug = fields.StringField(blank=True)
    ip_address = fields.StringField(blank=True)
    channel = fields.ObjectIdField()
    deleted = fields.BooleanField(default=False)
    deleted_at = fields.DateTimeField(blank=True)

    meta = {'collection': 'events'}

    def __str__(self):
        return self.title

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.title = document.title.capitalize()
        document.description = document.description.capitalize()
        document.location = document.location.title()
        document.landmark = document.landmark.title()
        document.city = document.city.title()

        if not document.slug:
            document.slug = slugify(document.title)
Exemple #12
0
class Ontology(Document):
    ontology = 'unkown'
    name = fields.StringField(max_length=2048)
    tablename = fields.StringField(max_length=128)
    owner = fields.StringField(max_length=128, null=True, default='core')
    description = fields.StringField(max_length=2048, null=True, default='')
    classname = fields.StringField(max_length=128, null=True)
    is_entity = fields.BooleanField(default=True)
    group = fields.StringField(max_length=255, null=True, default='None')

    def __unicode__(self):
        return self.name
Exemple #13
0
class OaiMetadataFormat(dme_Document):
    """
        A OaiMetadataFormat object
    """
    metadataPrefix = dme_fields.StringField()
    schema = dme_fields.StringField()
    xmlSchema = dme_fields.StringField(blank=True)
    metadataNamespace = dme_fields.StringField()
    raw = dme_fields.DictField()
    template = dme_fields.ReferenceField(Template, reverse_delete_rule=PULL, blank=True)
    registry = dme_fields.StringField(blank=True)
    hash = dme_fields.StringField(blank=True)
    harvest = dme_fields.BooleanField(blank=True)
    lastUpdate = dme_fields.DateTimeField(blank=True)
Exemple #14
0
class Channel(Document):
    title = fields.StringField(max_lenght=100, blank=False)
    slug = fields.StringField(max_lenght=150, blank=False)
    platform = fields.StringField(default="Swachhata",
                                  choices=['Swachhata', 'ICMYC'])
    app_name = fields.StringField(blank=False)
    type = fields.StringField(blank=False)
    archived = fields.BooleanField(default=False)
    created_at = fields.DateTimeField(default=datetime.datetime.now)
    updated_at = fields.DateTimeField()

    meta = {'collection': 'channels'}

    def __str__(self):
        return self.title
Exemple #15
0
class DynQuery(Document):
    """
    Query object created by the administrator.
    """
    # Query name
    name = fields.StringField(blank=False, unique=True)
    # Limit the query to number_records records
    is_limited = fields.BooleanField(blank=False, default=False)
    # Records number to limit the query
    number_records = fields.IntField(blank=True)
    # Group query
    group = fields.StringField(blank=False)
    # Schema associated to the query
    # FIXME: replace by a reference field
    schema = fields.StringField(blank=False)
    # List of step links to the query
    steps = fields.ListField(
        fields.ReferenceField(DynQueryStep,
                              blank=False,
                              reverse_delete_rule=CASCADE))

    @staticmethod
    def get_by_id(dyn_query_id):
        """Return a DynQuery given its id.

        Args:
            dyn_query_id:

        Returns:

        """
        try:
            return DynQuery.objects.get(pk=str(dyn_query_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as ex:
            raise exceptions.ModelError(str(ex))

    @staticmethod
    def get_all():
        """Return all DynQueries.

        Returns:

        """
        return DynQuery.objects().all()
Exemple #16
0
class Type(Template):
    """Type class."""

    is_complex = fields.BooleanField(blank=False)

    @staticmethod
    def get_by_id(type_id):
        """Return a type given its id.

        Args:
            type_id:

        Returns:

        """
        try:
            return Type.objects().get(pk=str(type_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def get_all():
        """Return all types.

        Returns:

        """
        return Type.objects().all()

    @staticmethod
    def get_all_complex_type():
        """List all complex types.

        Returns:

        """
        return Type.objects(is_complex=True).all()
Exemple #17
0
class GlobalTypeAnnots(Document):
    """
    Storage model for annotations on a global element.  The purpose of this 
    model separate from GlobalType is so that these annotations can be 
    shared across the different versions of the type (from the different
    versions of the schema); in other words, when a new version of a schema
    is loaded, you don't loose all your annotations.

    :property name       str: the local name for the element
    :property namespace  str: the namespace URI of the schema within which the 
                              element is defined
    :property schemaname str: the unique name given to the schema document where 
                              the type is defined
    :property tag       list: a list of strings representing subject tags
    :property hide   boolean: True if this element should be normally hidden
                              when offering root elements for templates.
    """
    name = fields.StringField(unique_with=["namespace", "schemaname"])
    namespace = fields.StringField()
    schemaname = fields.StringField()
    tag = fields.ListField(fields.StringField(), default=[], blank=True)
    hide = fields.BooleanField(default=False)
Exemple #18
0
class RhythmPosts(Document):
	post_id = fields.StringField(max_length=36,required=True,unique=True)
	user_id = fields.StringField(required=True, max_length=36)
	poster_url = fields.StringField(
		default = "http://profile.ak.fbcdn.net/static-ak/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif",
		unique=False, required=True
	)
	created_at = fields.DateTimeField(
		default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		, required=True, unique=False
	)
	post_likes = fields.EmbeddedDocumentListField(LikeDetails, required=False, 
		default= [], blank=True,unique=False)
	total_likes = fields.IntField(default=0)
	post_comments = fields.EmbeddedDocumentListField(CommentDetails, required=False, 
		default= [], blank=True,unique=False)
	total_comments = fields.IntField(default=0)
	is_comment_allowed = fields.BooleanField(default=True)
	post_caption = fields.StringField(unique=False, required=False, null=True)
	song_name = fields.StringField(unique=False, required=True)
	album = fields.StringField(unique=False, required=False, null=True)
	ratings = fields.DecimalField(min_value=0, max_value=5, default=0)
Exemple #19
0
class OaiSettings(Document):
    """Represents the settings for Oai-Pmh Provider"""
    repository_name = fields.StringField()
    repository_identifier = fields.StringField()
    enable_harvesting = fields.BooleanField()

    @staticmethod
    def get():
        """ Get the settings.

        Returns: The OaiSettings instance.

        Raises:
            DoesNotExist: The settings doesn't exist.
            ModelError: Internal error during the process.

        """
        try:
            return OaiSettings.objects.get()
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as e:
            raise exceptions.ModelError(e.message)
Exemple #20
0
class User(document.Document):
    """A User document that aims to mirror most of the API specified by Django
    at http://docs.djangoproject.com/en/dev/topics/auth/#users
    """
    username = fields.StringField(
        max_length=30,
        required=True,
        verbose_name=_('username'),
        help_text=
        _("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"
          ))

    first_name = fields.StringField(max_length=30,
                                    verbose_name=_('first name'))

    last_name = fields.StringField(max_length=30, verbose_name=_('last name'))
    email = fields.EmailField(verbose_name=_('e-mail address'))
    password = fields.StringField(
        max_length=128,
        verbose_name=_('password'),
        help_text=
        _("Use '[algo]$[iterations]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."
          ))
    is_staff = fields.BooleanField(
        default=False,
        verbose_name=_('staff status'),
        help_text=_(
            "Designates whether the user can log into this admin site."))
    is_active = fields.BooleanField(
        default=True,
        verbose_name=_('active'),
        help_text=
        _("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."
          ))
    is_superuser = fields.BooleanField(
        default=False,
        verbose_name=_('superuser status'),
        help_text=
        _("Designates that this user has all permissions without explicitly assigning them."
          ))
    last_login = fields.DateTimeField(default=timezone.now,
                                      verbose_name=_('last login'))
    date_joined = fields.DateTimeField(default=timezone.now,
                                       verbose_name=_('date joined'))

    user_permissions = fields.ListField(
        fields.ReferenceField(Permission),
        verbose_name=_('user permissions'),
        help_text=_('Permissions for the user.'))

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    meta = {
        'allow_inheritance': True,
        'indexes': [{
            'fields': ['username'],
            'unique': True,
            'sparse': True
        }]
    }

    def __unicode__(self):
        return self.username

    def get_full_name(self):
        """Returns the users first and last names, separated by a space.
        """
        full_name = u'%s %s' % (self.first_name or '', self.last_name or '')
        return full_name.strip()

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def set_password(self, raw_password):
        """Sets the user's password - always use this rather than directly
        assigning to :attr:`~mongoengine.django.auth.User.password` as the
        password is hashed before storage.
        """
        self.password = make_password(raw_password)
        self.save()
        return self

    def check_password(self, raw_password):
        """Checks the user's password against a provided password - always use
        this rather than directly comparing to
        :attr:`~mongoengine.django.auth.User.password` as the password is
        hashed before storage.
        """
        return check_password(raw_password, self.password)

    @classmethod
    def create_user(cls, username, password, email=None):
        """Create (and save) a new user with the given username, password and
        email address.
        """
        now = timezone.now()

        # Normalize the address by lowercasing the domain part of the email
        # address.
        if email is not None:
            try:
                email_name, domain_part = email.strip().split('@', 1)
            except ValueError:
                pass
            else:
                email = '@'.join([email_name, domain_part.lower()])

        user = cls(username=username, email=email, date_joined=now)
        user.set_password(password)
        user.save()
        return user

    def get_group_permissions(self, obj=None):
        """
        Returns a list of permission strings that this user has through his/her
        groups. This method queries all available auth backends. If an object
        is passed in, only permissions matching this object are returned.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self, obj))
        return permissions

    def get_all_permissions(self, obj=None):
        return _user_get_all_permissions(self, obj)

    def has_perm(self, perm, obj=None):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends, but returns immediately if any
        backend returns True. Thus, a user who has permission from a single
        auth backend is assumed to have permission in general. If an object is
        provided, permissions for this specific object are checked.
        """

        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        return _user_has_perm(self, perm, obj)

    def has_module_perms(self, app_label):
        """
        Returns True if the user has any permissions in the given app label.
        Uses pretty much the same logic as has_perm, above.
        """
        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        return _user_has_module_perms(self, app_label)

    def email_user(self, subject, message, from_email=None):
        "Sends an e-mail to this User."
        from django.core.mail import send_mail
        send_mail(subject, message, from_email, [self.email])

    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MO'
                                              'DULE in your project settings')
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
            except ValueError:
                raise SiteProfileNotAvailable(
                    'app_label and model_name should'
                    ' be separated by a dot in the AUTH_PROFILE_MODULE set'
                    'ting')

            try:
                model = models.get_model(app_label, model_name)
                if model is None:
                    raise SiteProfileNotAvailable(
                        'Unable to load the profile '
                        'model, check AUTH_PROFILE_MODULE in your project sett'
                        'ings')
                self._profile_cache = model._default_manager.using(
                    self._state.db).get(user__id__exact=self.id)
                self._profile_cache.user = self
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache
class OaiHarvesterSet(OaiSet):
    """Represents a set for Oai-Pmh Harvester"""

    raw = fields.DictField()
    registry = fields.ReferenceField(
        OaiRegistry, reverse_delete_rule=CASCADE, unique_with="set_spec"
    )
    harvest = fields.BooleanField(blank=True)

    @staticmethod
    def get_all_by_registry_id(registry_id, order_by_field=None):
        """Return a list of OaiHarvesterSet by registry id. Possibility to order_by the list

        Args:
            registry_id: The registry id.
            order_by_field: Order by field.

        Returns:
            List of OaiHarvesterSet.

        """
        return OaiHarvesterSet.objects(registry=str(registry_id)).order_by(
            order_by_field
        )

    @staticmethod
    def get_all_by_registry_id_and_harvest(registry_id, harvest, order_by_field=None):
        """Return a list of OaiHarvesterSet by registry and harvest. Possibility to order_by the list.

        Args:
            registry_id: The registry id.
            harvest: Harvest (True/False).
            order_by_field: Order by field.

        Returns:
            List of OaiHarvesterSet.

        """
        return OaiHarvesterSet.objects(
            registry=str(registry_id), harvest=harvest
        ).order_by(order_by_field)

    @staticmethod
    def get_by_set_spec_and_registry_id(set_spec, registry_id):
        """Return a OaiHarvesterSet by set_spec and registry.

        Args:
            set_spec: The set spec
            registry_id: The registry id.

        Returns: OaiHarvesterSet instance.

        Raises:
            DoesNotExist: The OaiHarvesterSet doesn't exist.
            ModelError: Internal error during the process.

        """
        try:
            return OaiHarvesterSet.objects().get(
                set_spec=set_spec, registry=str(registry_id)
            )
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def delete_all_by_registry_id(registry_id):
        """Delete all OaiHarvesterSet used by a registry.

        Args:
            registry_id: The registry id.

        """
        OaiHarvesterSet.get_all_by_registry_id(registry_id).delete()

    @staticmethod
    def update_for_all_harvest_by_registry_id(registry_id, harvest):
        """Update the harvest for all OaiHarvesterSet used by the registry.

        Args:
            registry_id: The registry id.
            harvest: Harvest (True/False).

        """
        OaiHarvesterSet.get_all_by_registry_id(registry_id).update(set__harvest=harvest)

    @staticmethod
    def update_for_all_harvest_by_list_ids(list_oai_set_ids, harvest):
        """Update the harvest for all OaiHarvesterSet by a list of ids.

        Args:
            list_oai_set_ids: List of OaiHarvesterSet ids.
            harvest: Harvest (True/False)

        """
        OaiHarvesterSet.get_all_by_list_ids(list_oai_set_ids).update(
            set__harvest=harvest
        )
Exemple #22
0
class VersionManager(Document):
    """Version Manager"""
    title = fields.StringField(unique=True, regex=NOT_EMPTY_OR_WHITESPACES)
    user = fields.StringField(blank=True)
    versions = fields.ListField(default=[], blank=True)
    current = fields.StringField(blank=True)
    is_disabled = fields.BooleanField(default=False)
    disabled_versions = fields.ListField(default=[], blank=True)

    meta = {'allow_inheritance': True}

    def disable(self):
        """Disable the Version Manager.

        Returns:

        """
        self.is_disabled = True

    def restore(self):
        """Restore the Version Manager.

        Returns:

        """
        self.is_disabled = False

    def disable_version(self, version):
        """Disable a version.

        Args:
            version:

        Returns:

        """
        self.disabled_versions.append(str(version.id))

    def restore_version(self, version):
        """Restore a version.

        Args:
            version:

        Returns:

        """
        self.disabled_versions.remove(str(version.id))

    def set_current_version(self, version):
        """Set the current version.

        Args:
            version:

        Returns:

        """
        self.current = str(version.id)

    def get_version_number(self, version_id):
        """Return version number from version id.

        Args:
            version_id:

        Returns:

        Raises:
            DoesNotExist: Version does not exist.

        """
        try:
            return self.versions.index(str(version_id)) + 1
        except Exception as e:
            raise exceptions.DoesNotExist(e.message)

    def insert(self, version):
        """Insert a version in the Version Manager.

        Args:
            version:

        Returns:

        """
        self.versions.append(str(version.id))

    def get_disabled_versions(self):
        """Get the list disabled versions of the version manager.

        Returns:

        """
        return self.disabled_versions

    def get_version_by_number(self, version_number):
        """Return the version by its version number.

        Args:
            version_number: Number of the version.

        Returns:

        Raises:
            DoesNotExist: Version does not exist.

        """
        try:
            return self.versions[version_number - 1]
        except Exception as e:
            raise exceptions.DoesNotExist(e.message)

    @staticmethod
    def get_all():
        """Return all Version Managers.

        Returns:

        """
        return VersionManager.objects.all()

    @staticmethod
    def get_by_id(version_manager_id):
        """Return Version Managers by id.

        Args:
            version_manager_id:

        Returns:

        """
        try:
            return VersionManager.objects.get(pk=str(version_manager_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as e:
            raise exceptions.ModelError(e.message)

    @staticmethod
    def get_by_id_list(list_id):
        """Return Version Managers with the given id list.

        Args:
            list_id:

        Returns:

        """
        return VersionManager.objects(pk__in=list_id).all()

    @staticmethod
    def get_active_global_version_manager_by_title(version_manager_title):
        """Return active Version Manager by its title with user set to None.

        Args:
            version_manager_title: Version Manager title

        Returns:
            Version Manager instance

        """
        try:
            return VersionManager.objects.get(is_disabled=False,
                                              title=version_manager_title,
                                              user=None)
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as e:
            raise exceptions.ModelError(e.message)

    @staticmethod
    def get_global_version_managers():
        """Return all Version Managers with user set to None.

        Returns:

        """
        return VersionManager.objects(user=None).all()

    @staticmethod
    def get_active_global_version_manager():
        """ Return all active Version Managers with user set to None.

        Returns:

        """
        return VersionManager.objects(is_disabled=False, user=None).all()

    @staticmethod
    def get_disable_global_version_manager():
        """ Return all disabled Version Managers with user set to None.

        Returns:

        """
        return VersionManager.objects(is_disabled=True, user=None).all()

    @staticmethod
    def get_active_version_manager_by_user_id(user_id):
        """ Return all active Version Managers with given user id.

        Returns:

        """
        return VersionManager.objects(is_disabled=False,
                                      user=str(user_id)).all()

    @staticmethod
    def get_disable_version_manager_by_user_id(user_id):
        """ Return all disabled Version Managers with given user id.

        Returns:

        """
        return VersionManager.objects(is_disabled=True,
                                      user=str(user_id)).all()

    @staticmethod
    def get_all_version_manager_except_user_id(user_id):
        """ Return all Version Managers of all users except user with given user id.

        Args:
            user_id: user_id.

        Returns:

        """
        return VersionManager.objects(user__nin=str(user_id)).all()

    @staticmethod
    def get_all_version_manager_by_user_id(user_id):
        """ Return all Version Managers with given user id.

        Args:
            user_id: user_id.

        Returns:

        """
        return VersionManager.objects(user=str(user_id)).all()

    def save_version_manager(self):
        """ Custom save.

        Returns:
            Saved Instance.

        """
        try:
            return self.save()
        except mongoengine_errors.NotUniqueError as e:
            raise exceptions.NotUniqueError(e.message)
        except Exception as ex:
            raise exceptions.ModelError(ex.message)

    def clean(self):
        """ Clean is called before saving

        Returns:

        """
        self.title = self.title.strip()
Exemple #23
0
class VersionManager(Document):
    """Version Manager"""

    title = fields.StringField(unique=True, validation=not_empty_or_whitespaces)
    user = fields.StringField(blank=True)
    versions = fields.ListField(default=[], blank=True)
    current = fields.StringField(blank=True)
    is_disabled = fields.BooleanField(default=False)
    disabled_versions = fields.ListField(default=[], blank=True)

    meta = {"allow_inheritance": True}

    def disable(self):
        """Disable the Version Manager.

        Returns:

        """
        self.is_disabled = True

    def restore(self):
        """Restore the Version Manager.

        Returns:

        """
        self.is_disabled = False

    def disable_version(self, version):
        """Disable a version.

        Args:
            version:

        Returns:

        """
        # check if the version is not already disabled
        if str(version.id) not in list(self.disabled_versions):
            self.disabled_versions.append(str(version.id))

    def restore_version(self, version):
        """Restore a version.

        Args:
            version:

        Returns:

        """
        self.disabled_versions.remove(str(version.id))

    def set_current_version(self, version):
        """Set the current version.

        Args:
            version:

        Returns:

        """
        self.current = str(version.id)

    def insert(self, version):
        """Insert a version in the Version Manager.

        Args:
            version:

        Returns:

        """
        self.versions.append(str(version.id))

    def get_disabled_versions(self):
        """Get the list disabled versions of the version manager.

        Returns:

        """
        return self.disabled_versions

    @staticmethod
    def get_all():
        """Return all Version Managers.

        Returns:

        """
        return VersionManager.objects.all()

    @staticmethod
    def get_by_id(version_manager_id):
        """Return Version Managers by id.

        Args:
            version_manager_id:

        Returns:

        """
        try:
            return VersionManager.objects.get(pk=str(version_manager_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def get_by_id_list(list_id):
        """Return Version Managers with the given id list.

        Args:
            list_id:

        Returns:

        """
        return VersionManager.objects(pk__in=list_id).all()

    @staticmethod
    def get_active_global_version_manager_by_title(version_manager_title):
        """Return active Version Manager by its title with user set to None.

        Args:
            version_manager_title: Version Manager title

        Returns:
            Version Manager instance

        """
        try:
            return VersionManager.objects.get(
                is_disabled=False, title=version_manager_title, user=None
            )
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def get_global_version_managers():
        """Return all Version Managers with user set to None.

        Returns:

        """
        return VersionManager.objects(user=None).all()

    @staticmethod
    def get_active_global_version_manager():
        """Return all active Version Managers with user set to None.

        Returns:

        """
        return VersionManager.objects(is_disabled=False, user=None).all()

    @staticmethod
    def get_active_version_manager_by_user_id(user_id):
        """Return all active Version Managers with given user id.

        Returns:

        """
        return VersionManager.objects(is_disabled=False, user=str(user_id)).all()

    @staticmethod
    def get_all_version_manager_except_user_id(user_id):
        """Return all Version Managers of all users except user with given user id.

        Args:
            user_id: user_id.

        Returns:

        """
        return VersionManager.objects(user__nin=str(user_id)).all()

    @staticmethod
    def get_all_version_manager_by_user_id(user_id):
        """Return all Version Managers with given user id.

        Args:
            user_id: user_id.

        Returns:

        """
        return VersionManager.objects(user=str(user_id)).all()

    def save_version_manager(self):
        """Custom save.

        Returns:
            Saved Instance.

        """
        try:
            return self.save()
        except mongoengine_errors.NotUniqueError as e:
            raise exceptions.NotUniqueError(str(e))
        except Exception as ex:
            raise exceptions.ModelError(str(ex))

    def clean(self):
        """Clean is called before saving

        Returns:

        """
        self.title = self.title.strip()
class TempUserStep(Document):
    """
    Model which define the step associated to a user choice
    """
    step = fields.ReferenceField(DynQueryStep, blank=True)  # Base step

    # Attribute for query_management
    query_able = fields.BooleanField()  # True if the query is query able, false else
    # List of choices and files
    list_choices_id_file = fields.ListField(fields.ReferenceField(TempChoiceListFile, blank=True), blank=True)
    dict_choices_id_file = dict()  # Dict of choices and files id
    files = fields.ListField(blank=True)  # List of file for date step
    choices = fields.ListField(blank=True)  # User choices for the step
    form_type = fields.StringField()  # Form step type (radio, check, date)
    absolute_position = fields.IntField()  # Position in the list of steps for the query
    viewable_position = fields.IntField()  # Position in the list of query able steps for the query
    full_xpath = fields.StringField()  # Full path to the query

    @staticmethod
    def get_all():
        """Return all TempUserStep.

        Returns:

        """
        return TempUserStep.objects().all()

    def delete_database(self):
        """
        Delete function

        Delete each choices and the associated files.
        """

        for choices_id_file in self.list_choices_id_file:
            try:
                choices_id_file_obj = TempChoiceListFile.objects.get(id=choices_id_file.id)
                choices_id_file_obj.delete_database()
            except:
                pass

        self.delete()

    def initialize_step(self, step=None):
        """
            Initialise the query step.

            It initialize a step. If the step name is given, the information are loaded from the
            step define by the admin into step.

            :param step: The step to load.
            :return: The object initialized.
        """

        # Attribute for query_management
        self.list_choices_id_file = list()
        self.dict_choices_id_file = dict()
        self.files = list()  # List of file for date step
        self.choices = list()  # User choice for the step
        self.form_type = ''
        self.absolute_position = None
        self.viewable_position = None
        self.full_xpath = None
        self.query_able = False

        if step is not None:
            self.load_from_step_admin(step=step)

    def load_from_step_admin(self, step):
        """
            Load the step from the admin defined step.

            The information are loaded from the step define by the admin into the user's step.
            It is mainly used by the __init__.

            :param step: The step to load.
        """
        self.step = step

        self.query_able = not step.output_field

        if self.step.data_type == 'data':
            if self.step.data_min_range == 1 and self.step.data_max_range == 1:
                self.form_type = 'radio'
            else:
                self.form_type = 'check'
        else:
            self.form_type = 'date'

    def load_choices_and_xml_data(self, cursor_xml_data):
        """
            Load the dictionary of choices and files from the list of input files

            :param cursor_xml_data: List of input files
        """
        dict_choices_file = defaultdict(set)
        for file_xml_data in cursor_xml_data:
            data_dict = file_xml_data.to_mongo()
            self.get_choices(
                [data_dict['dict_content']],
                [x for x in self.full_xpath.split(".") if x],
                dict_choices_file,
                data_dict['_id']
            )
        for choices, set_files in dict_choices_file.iteritems():
            self.dict_choices_id_file[choices] = list(set_files)

        if len(self.dict_choices_id_file) == 0:
            raise EmptyChoicesFromQuery(x_path=self.full_xpath)

    def get_id_files_from_user_choices(self):
        """
        Get the list of unique files from the user choices and the list of choices and files.
        :return: List of unique files
        """
        unique_id_files = set()
        for temp_choice_list_file in self.list_choices_id_file:
            if temp_choice_list_file.choice in self.choices:
                for bucket in temp_choice_list_file.list_buckets:
                    for id_file in bucket.list_files:
                        unique_id_files.add(ObjectId(id_file))
        return list(unique_id_files)

    def get_choices_as_tuple(self):
        """
            Get list of choices.

            Get a list of possible choices for the user as tuple as
            [(choice1, choice1), (choice2, choice2), ...].

            :return: List of possible choices for the user as tuple or None if there is no choices.
        """
        if len(self.dict_choices_id_file) == 0:
            return None
        else:
            choices = set()
            for keys in self.dict_choices_id_file:
                choices.add((keys, keys))
            return sorted(tuple(choices))

    def update_choices_to_db(self):
        """
            Update the user choices for the step.
        """
        self.update(choices=self.choices)

    def update_choices_id_files_to_db(self):
        """
            Update the choices and the corresponding files to the db.

            Update the choices and the corresponding files to the db. Change also the way of data
             structure, from a dictionary based structure to a list based structure more suitable
             for database restriction.
        """
        choices_id_files_to_save = self.dict_choices_id_file

        # Delete old data in the DB
        for choice in self.list_choices_id_file:
            for bucket in choice.list_buckets:
                for files in bucket.list_files:
                    files.delete()
                bucket.delete()
            choice.delete()

        # Transform and update the data
        new_list_choices_list_files = list()
        for choice, list_value in choices_id_files_to_save.items():
            new_temp_choice_list_file = TempChoiceListFile()
            new_temp_choice_list_file.choice = choice
            list_bucket_temp = list()
            chunks = [list_value[x:x + 300] for x in xrange(0, len(list_value), 300)]
            for chunk in chunks:
                new_bucket = TempBucketIdFiles()
                new_bucket.list_files = chunk
                new_bucket.save()
                list_bucket_temp.append(new_bucket)

            new_temp_choice_list_file.list_buckets = list_bucket_temp
            new_temp_choice_list_file.save()
            new_list_choices_list_files.append(new_temp_choice_list_file)

        self.update(list_choices_id_file=new_list_choices_list_files)

    def transform_choices_files_list_to_dict(self):
        """
            Transform and return the possible choices-lists from db-list to use-dict

            Transform the choices-files list structure into a DB to a usable choices-files dict
            structure. It also delete old trace of existing choices-files dict structure.
        """
        self.dict_choices_id_file = dict()
        for list_choices_id_file in self.list_choices_id_file:
            self.dict_choices_id_file[list_choices_id_file.choice] = list()
            for buckets in list_choices_id_file.list_buckets:
                self.dict_choices_id_file[list_choices_id_file.choice].extend(buckets.list_files)

    def update_files_in_db(self):
        """
            Update the list  of files into the db
        """
        self.update(files=self.files)

    def clean_step(self):
        """
            Clean a specific step into the database.
        """
        self.update(choices=list())
        self.update(files=list())

        for list_choices_id_file in self.list_choices_id_file:
            for bucket in list_choices_id_file.list_buckets:
                bucket.delete()
            list_choices_id_file.delete()
        self.update(list_choices_id_file=list())

    def filter_user_choice_date(self, element, time_from, time_to, translate_dt):
        """
        Filter a specif element against it date value
        :param element: element too filter
        :param time_from: First threshold to filter
        :param time_to: Second threshold to filter
        :param translate_dt: Python translate for the element value
        :return: Return true is the element date is after the time_from and before the time_to
        """
        timestamp = str(element["@" + self.step.value])
        if timestamp[-1] == 'Z':
            timestamp = timestamp[:-1]
        timestamp = map(int, timestamp.translate(translate_dt).split())
        if (is_datetime_inf_or_equal(time_from, timestamp) and
                is_datetime_inf_or_equal(timestamp, time_to)) is False:
            return False
        else:
            return True

    def choose_filter_choice(self, list_elements, element_title, translate_dt, translate_bounds):
        """
        Choose a specific filter and apply it to a list of elements.
        :param list_elements: List of elements to filter
        :param element_title: Title of the elements
        :param translate_dt: Translate object for date comparison
        :param translate_bounds: Translate object for date comparison
        :return: Filtered list of elements
        """
        if self.query_able:
            if self.step.data_type == 'data':
                target = self.step.target
                choices = self.choices
                if target == 'attribute':
                    value = "@" + self.step.value
                    list_elements_cleaned = [x for x in list_elements if x[value] in choices]
                    return list_elements_cleaned
                elif target == 'name':
                    if element_title not in choices:
                        list_elements_cleaned = []
                    else:
                        list_elements_cleaned = list_elements
                    return list_elements_cleaned
                else:
                    # FIXME: #text was hardcoded, but elements don't have #text if the xml tag does not have any
                    # FIXME: attributes
                    list_elements_cleaned = [x for x in list_elements if isinstance(x, dict) and x['#text'] in choices
                                             or x in choices]
                    return list_elements_cleaned
            else:
                time_from = map(int, str(self.choices[0]).
                                translate(translate_bounds).split())
                time_to = map(int, str(self.choices[1]).
                              translate(translate_bounds).split())
                my_filter_date = self.filter_user_choice_date
                list_elements_cleaned = [
                    x
                    for x in list_elements
                    if my_filter_date(element=x, time_from=time_from, time_to=time_to,
                                      translate_dt=translate_dt)
                    ]
                return list_elements_cleaned
        else:
            return list_elements

    def get_choices(self, list_elements, list_keys_xpath, dict_choices_file, id_file):
        """
        Get possibles choices from a list of elements to explore.
        :param list_elements: List of elements to explore
        :param list_keys_xpath: List of elements from the xpath spliced
        :param dict_choices_file: Dictionary of choices, linked to a list of files
        :param id_file:Current if file
        :return:
        """
        element_title = list_keys_xpath[-1]

        while list_keys_xpath:
            key_xpath = list_keys_xpath.pop(0)
            if list_elements:
                if isinstance(list_elements[0], list):
                    list_elements = flat_list(list_elements)
            if key_xpath == "*":
                set_possibilities = explore_star(list_elements)
                for key_possible in set_possibilities:
                    list_key_param_star = [key_possible]
                    if len(list_keys_xpath) != 0:
                        list_key_param_star.extend(list_keys_xpath)
                    self.get_choices(
                        list_elements=list_elements,
                        list_keys_xpath=list_key_param_star,
                        dict_choices_file=dict_choices_file,
                        id_file=id_file
                    )
                return
            else:
                list_elements = [x.get(key_xpath) for x in list_elements if x.get(key_xpath)]

        target = self.step.target
        if target == 'name':
            dict_choices_file[element_title].add(id_file)
        else:
            if list_elements:
                if isinstance(list_elements[0], list):
                    list_elements = flat_list(list_elements)
            if target == 'attribute':
                value = "@" + self.step.value
                set_elements = (str(x.get(value)) for x in list_elements)
                for element in set_elements:
                    dict_choices_file[element].add(id_file)
            else:
                # FIXME: #text was hardcoded, but elements don't have #text if the xml tag does not have any attributes
                # set_elements = (x.get("#text") for x in list_elements)
                set_elements = (x.get("#text") if isinstance(x, dict) else str(x) for x in list_elements)
                for element in set_elements:
                    dict_choices_file[element].add(id_file)
        return
class User(document.Document):
    """A User document that aims to mirror most of the API specified by Django
    at http://docs.djangoproject.com/en/dev/topics/auth/#users
    """
    username = fields.StringField(
        max_length=30,
        required=True,
        verbose_name=_('username'),
        help_text=_("""Required. 30 characters or fewer.
Letters, numbers and @/./+/-/_ characters"""))
    first_name = fields.StringField(max_length=30,
                                    verbose_name=_('first name'))
    last_name = fields.StringField(max_length=30, verbose_name=_('last name'))
    email = fields.EmailField(verbose_name=_('e-mail address'))
    password = fields.StringField(max_length=128,
                                  verbose_name=_('password'),
                                  help_text=_("""Use
'[algo]$[iterations]$[salt]$[hexdigest]' or use the
<a href=\"password/\">change password form</a>."""))
    is_staff = fields.BooleanField(
        default=False,
        verbose_name=_('staff status'),
        help_text=_("""Designates whether the user can
log into this admin site."""))
    is_active = fields.BooleanField(
        default=True,
        verbose_name=_('active'),
        help_text=_("""Designates whether this user should
be treated as active. Unselect this instead of deleting accounts."""))
    is_superuser = fields.BooleanField(
        default=False,
        verbose_name=_('superuser status'),
        help_text=_("""Designates that this user has
all permissions without explicitly assigning them."""))
    last_login = fields.DateTimeField(default=datetime.datetime.now,
                                      verbose_name=_('last login'))
    date_joined = fields.DateTimeField(default=datetime.datetime.now,
                                       verbose_name=_('date joined'))

    meta = {
        'allow_inheritance': True,
        'indexes': [{
            'fields': ['username'],
            'unique': True
        }]
    }

    def __unicode__(self):
        return self.username

    def get_full_name(self):
        """Returns the users first and last names, separated by a space.
        """
        full_name = u'%s %s' % (self.first_name or '', self.last_name or '')
        return full_name.strip()

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def set_password(self, raw_password):
        """Sets the user's password - always use this rather than directly
        assigning to :attr:`~mongoengine.django.auth.User.password` as the
        password is hashed before storage.
        """
        self.password = make_password(raw_password)
        self.save()
        return self

    def check_password(self, raw_password):
        """Checks the user's password against a provided password - always use
        this rather than directly comparing to
        :attr:`~mongoengine.django.auth.User.password` as the password is
        hashed before storage.
        """
        return check_password(raw_password, self.password)

    @classmethod
    def create_user(cls, username, email, password):
        """Create (and save) a new user with the given username, password and
        email address.
        """
        now = datetime.datetime.now()

        # Normalize the address by lowercasing the domain part of the email
        # address.
        if email is not None:
            try:
                email_name, domain_part = email.strip().split('@', 1)
            except ValueError:
                pass
            else:
                email = '@'.join([email_name, domain_part.lower()])

        user = cls(username=username, email=email, date_joined=now)
        user.set_password(password)
        user.save()
        return user

    @classmethod
    def create_superuser(cls, username, email, password):
        u = cls.create_user(username, email, password)
        u.update(set__is_staff=True,
                 set__is_active=True,
                 set__is_superuser=True)
        return u

    def get_and_delete_messages(self):
        return []

    def has_perm(self, perm, obj=None):
        return True

    def has_perms(self, perm_list, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True
Exemple #26
0
class Workspace(Document):
    """
        Workspace class.
    """

    title = fields.StringField(blank=False, regex=NOT_EMPTY_OR_WHITESPACES)
    owner = fields.StringField(blank=True)
    read_perm_id = fields.StringField(blank=False)
    write_perm_id = fields.StringField(blank=False)
    is_public = fields.BooleanField(default=False)

    def clean(self):
        """

        Returns:
        """
        # Check the title
        if self.owner is not None and self.title.lower(
        ) == "global public workspace":
            raise exceptions.ModelError(
                "You can't create a workspace with the title: " + self.title)

    @staticmethod
    def get_all():
        """ Get all workspaces.

        Returns:

        """
        return Workspace.objects.all()

    @staticmethod
    def get_all_by_owner(user_id):
        """ Get all workspaces created by the given user id.

        Args:
            user_id

        Returns:

        """
        return Workspace.objects(owner=str(user_id)).all()

    @staticmethod
    def get_by_id(workspace_id):
        """ Return the workspace with the given id.

        Args:
            workspace_id

        Returns:
            Workspace (obj): Workspace object with the given id

        """
        try:
            return Workspace.objects.get(pk=str(workspace_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as ex:
            raise exceptions.ModelError(str(ex))

    @staticmethod
    def get_all_workspaces_with_read_access_by_user_id(user_id,
                                                       read_permissions):
        """ Get all workspaces with read access for the given user id.

        Args:
            user_id
            read_permissions

        Returns:

        """
        return Workspace.objects(
            Q(owner=str(user_id)) | Q(read_perm_id__in=read_permissions)
            | Q(is_public=True)).all()

    @staticmethod
    def get_all_workspaces_with_write_access_by_user_id(
            user_id, write_permissions):
        """ Get all workspaces with write access for the given user id.

        Args:
            user_id
            write_permissions

        Returns:

        """
        return Workspace.objects(
            Q(owner=str(user_id))
            | Q(write_perm_id__in=write_permissions)).all()

    @staticmethod
    def get_all_workspaces_with_read_access_not_owned_by_user_id(
            user_id, read_permissions):
        """ Get all workspaces with read access not owned by the given user id.

        Args:
            user_id
            read_permissions

        Returns:

        """

        return Workspace.objects(Q(read_perm_id__in=read_permissions)
                                 | Q(is_public=True),
                                 owner__ne=str(user_id)).all()

    @staticmethod
    def get_all_workspaces_with_write_access_not_owned_by_user_id(
            user_id, write_permissions):
        """ Get all workspaces with write access not owned by the given user id.

        Args:
            user_id
            write_permissions

        Returns:

        """
        return Workspace.objects(owner__ne=str(user_id),
                                 write_perm_id__in=write_permissions).all()

    @staticmethod
    def get_all_public_workspaces():
        """ Get all public workspaces.

        Args:

        Returns:

        """
        return Workspace.objects(is_public=True).all()

    @staticmethod
    def get_all_other_public_workspaces(user_id):
        """ Get all other public workspaces.

        Args:
            user_id

        Returns:

        """
        return Workspace.objects(owner__ne=str(user_id), is_public=True).all()

    @staticmethod
    def get_non_public_workspace_owned_by_user_id(user_id):
        """ Get the non public workspaces owned by the given user id.

        Args:
            user_id

        Returns:

        """
        return Workspace.objects(owner=str(user_id), is_public=False).all()

    @staticmethod
    def get_public_workspaces_owned_by_user_id(user_id):
        """ Get the public workspaces owned the given user id.

        Args:
            user_id

        Returns:

        """
        return Workspace.objects(owner=str(user_id), is_public=True).all()

    @staticmethod
    def get_global_workspace():
        """ Get global workspace.

        Returns:
        """
        try:
            return Workspace.objects.get(owner=None, is_public=True)
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as ex:
            raise exceptions.ModelError(str(ex))

    @property
    def is_global(self):
        """ Get is global.

        Returns:
        """
        return self.is_public and self.owner is None
class client_reposit(Document):
    manufacturer_name = fields.StringField()
    model_name = fields.StringField()
    model_no = fields.StringField()
    ue_mac = fields.StringField()
    os_type = fields.StringField()
    os_version = fields.StringField()
    ver_80211_support = fields.StringField()
    freq_support = fields.StringField()
    device_type = fields.StringField()
    serial_no = fields.StringField()
    release_year = fields.StringField()
    priority = fields.StringField()
    chrome_ver = fields.StringField()
    safari_ver = fields.StringField()
    edge_ver = fields.StringField()
    samsungBrowser_ver = fields.StringField()
    is_sticky = fields.BooleanField()
    TLS_ver = fields.StringField()
    is_11wC = fields.BooleanField()
    is_PMK = fields.BooleanField()
    is_OKC = fields.BooleanField()
    is_11r = fields.BooleanField()
    is_11k = fields.BooleanField()
    is_PMK_cache = fields.BooleanField()
    is_UNII_2A = fields.BooleanField()
    is_UNII_2C = fields.BooleanField()
    is_UNII_2B = fields.BooleanField()
    is_WPA3 = fields.BooleanField()

    def __str__(self):
        """A string representation of the model."""
        return self.model_name
Exemple #28
0
class Module(Document):
    """Represents a module, that will replace the default rendering of an element"""
    name = fields.StringField(unique=True)
    url = fields.StringField(unique=True)
    view = fields.StringField()
    multiple = fields.BooleanField(default=False)

    @staticmethod
    def get_by_id(module_id):
        """Returns a module by its id

        Args:
            module_id:

        Returns:

        """
        try:
            return Module.objects().get(pk=str(module_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as e:
            raise exceptions.ModelError(e.message)

    @staticmethod
    def get_by_url(module_url):
        """Returns a module by its id

        Args:
            module_url:

        Returns:

        """
        try:
            return Module.objects().get(url=module_url)
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(e.message)
        except Exception as e:
            raise exceptions.ModelError(e.message)

    @staticmethod
    def get_all():
        """Returns all modules

        Returns:

        """
        return Module.objects.all()

    @staticmethod
    def get_all_urls():
        """Returns all modules urls

        Returns:

        """
        return Module.objects.all().values_list('url')

    @staticmethod
    def delete_all():
        """Deletes all modules

        Returns:

        """
        Module.objects.all().delete()
Exemple #29
0
class SwachhToilet(Document):

    qci_id = fields.StringField(max_length=100, unique=True)
    toilet_id = fields.StringField(max_length=100, unique=True)
    address = fields.StringField()
    latitude = fields.FloatField()
    longitude = fields.FloatField()
    location = fields.PointField()
    state = fields.StringField(blank=True)
    city = fields.StringField()
    category = fields.StringField(blank=True)
    category_code = fields.StringField(blank=True)
    type = fields.StringField(blank=True)
    opening_time = fields.StringField(blank=True)
    closing_time = fields.StringField(blank=True)
    open_days = fields.StringField(default='All Seven Days')
    seats = fields.IntField(default=0)
    gender = fields.StringField(default='Gents and Ladies')
    child_friendly = fields.BooleanField(default=False)
    differntly_abled_friedly = fields.BooleanField(default=False)
    fee_type = fields.StringField(default='Free of Charge')
    cost = fields.StringField(blank=True)
    image = fields.StringField(blank=True)
    timestamp = fields.DateTimeField(default=datetime.now)
    comments = fields.ListField(fields.DictField(), blank=True, default=None)

    meta = {'collection': 'swachh_toilets'}

    def __str__(self):
        return self.qci_id

    def title(self):
        return 'Swachh Public Toilet'

    def get_api_url(self, request=None):
        return api_reverse("api-public-toilets:detail-toilet",
                           kwargs={'pk': str(self.pk)},
                           request=request)

    def get_comments_api_url(self, request=None):
        return self.get_api_url(request) + '/comments'

    def opened_today(self):
        days = week_days_in_short_format()

        open_days_from_db = self.open_days

        if open_days_from_db == 'Monday to Friday':
            open_days = days[:5]
        if open_days_from_db == 'Monday to Saturday':
            open_days = days[:6]
        elif open_days_from_db == 'Tuesday,Wednesday,Thursday,\
                                    Friday,Saturday,Sunday':
            open_days = days[1:7]
        else:
            open_days = days

        if today_name_in_short_form() in open_days:
            return True

    def opened_all_the_day(self):
        return (self.opening_time == '00:00' and self.closing_time == '23:59')
Exemple #30
0
class OaiRegistry(Document):
    """ A registry object for Oai-Pmh Harvester"""
    name = fields.StringField()
    url = fields.URLField(unique=True)
    harvest_rate = fields.IntField(blank=True)
    description = fields.StringField(blank=True)
    harvest = fields.BooleanField(default=False)
    last_update = fields.DateTimeField(blank=True)
    is_harvesting = fields.BooleanField(default=False)
    is_updating = fields.BooleanField(default=False)
    is_activated = fields.BooleanField(default=True)
    is_queued = fields.BooleanField(default=False)

    @staticmethod
    def get_by_id(oai_registry_id):
        """ Get an OaiRegistry by its id

        Args:
            oai_registry_id: OaiRegistry id.

        Returns: The OaiRegistry instance.

        Raises:
            DoesNotExist: The registry doesn't exist
            ModelError: Internal error during the process

        """
        try:
            return OaiRegistry.objects().get(pk=str(oai_registry_id))
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def get_by_name(oai_registry_name):
        """ Get an OaiRegistry by its name.

        Args:
            oai_registry_name: OaiRegistry name.

        Returns: The OaiRegistry instance.

        Raises:
            DoesNotExist: The registry doesn't exist
            ModelError: Internal error during the process

        """
        try:
            return OaiRegistry.objects().get(name=oai_registry_name)
        except mongoengine_errors.DoesNotExist as e:
            raise exceptions.DoesNotExist(str(e))
        except Exception as e:
            raise exceptions.ModelError(str(e))

    @staticmethod
    def get_all():
        """ Return all OaiRegistry

        Returns:
            List of OaiRegistry

        """
        return OaiRegistry.objects().all()

    @staticmethod
    def get_all_by_is_activated(is_activated, order_by_field=None):
        """ Return all OaiRegistry by their is_activated field

        Params:
            is_activated: True or False.
            order_by_field: Field to order on.

        Returns:
            List of OaiRegistry

        """
        return OaiRegistry.objects(
            is_activated=is_activated).order_by(order_by_field)

    @staticmethod
    def check_registry_url_already_exists(oai_registry_url):
        """ Check if an OaiRegistry with the given url already exists.

        Params:
            oai_registry_url: URL to check.

        Returns:
            Yes or No (bool).

        """
        return OaiRegistry.objects(url__exact=oai_registry_url).count() > 0