Exemplo n.º 1
0
    def createUser(
        self,
        login,
        password,
        displayName="",
        email="",
        admin=False,
        lastName=None,
        firstName=None
    ): # 🔥 delete lastName once fully deprecated
        currentUser = self.getCurrentUser()

        regPolicy = Setting().get(SettingKey.REGISTRATION_POLICY)

        if not currentUser or not currentUser['admin']:
            admin = False
            if regPolicy == 'closed':
                raise RestException(
                    'Registration on this instance is closed. Contact an '
                    'administrator to create an account for you.')

        user = self._model.createUser(
            login=login, password=password, email=email,
            firstName=displayName if len(
                displayName
            ) else firstName if firstName is not None else "",
            lastName=lastName, admin=admin, currentUser=currentUser) # 🔥 delete firstName and lastName once fully deprecated

        if not currentUser and self._model.canLogin(user):
            setCurrentUser(user)
            token = self.sendAuthTokenCookie(user)
            user['authToken'] = {
                'token': token['_id'],
                'expires': token['expires']
            }

        # Assign all new users to a "New Users" Group
        newUserGroup = GroupModel().findOne({'name': 'New Users'})
        newUserGroup = newUserGroup if (
            newUserGroup is not None and bool(newUserGroup)
        ) else GroupModel(
        ).createGroup(
            name="New Users",
            creator=UserModel().findOne(
                query={'admin': True},
                sort=[('created', SortDir.ASCENDING)]
            ),
            public=False
        )
        group = GroupModel().addUser(
            newUserGroup,
            user,
            level=AccessType.READ
        )
        group['access'] = GroupModel().getFullAccessList(group)
        group['requests'] = list(GroupModel().getFullRequestList(group))

        return(user)
Exemplo n.º 2
0
 def assignGroup(self, folder, group, role, subject):
     applet = folder
     if role not in USER_ROLE_KEYS:
         raise ValidationException('Invalid role.', 'role')
     thisUser = self.getCurrentUser()
     group = GroupModel().load(group, level=AccessType.WRITE, user=thisUser)
     return (AppletModel().setGroupRole(applet,
                                        group,
                                        role,
                                        currentUser=thisUser,
                                        force=False,
                                        subject=subject))
Exemplo n.º 3
0
    def __init__(self):
        super(Group, self).__init__()
        self.resourceName = 'group'
        self._model = GroupModel()

        self.route('DELETE', (':id',), self.deleteGroup)
        self.route('DELETE', (':id', 'member'), self.removeFromGroup)
        self.route('DELETE', (':id', 'moderator'), self.demote)
        self.route('DELETE', (':id', 'admin'), self.demote)
        self.route('GET', (), self.find)
        self.route('GET', ('open',), self.getOpenGroups)
        self.route('GET', (':id',), self.getGroup)
        self.route('GET', (':id', 'access'), self.getGroupAccess)
        self.route('GET', (':id', 'invitation'), self.getGroupInvitations)
        self.route('GET', (':id', 'member'), self.listMembers)
        self.route('POST', (), self.createGroup)
        self.route('POST', (':id', 'invitation'), self.inviteToGroup)
        self.route('POST', (':id', 'member'), self.joinGroup)
        self.route('POST', (':id', 'moderator'), self.promoteToModerator)
        self.route('POST', (':id', 'admin'), self.promoteToAdmin)
        self.route('PUT', (':id',), self.updateGroup)
        self.route('PUT', (':id', 'access'), self.updateGroupAccess)
Exemplo n.º 4
0
 def getAppletGroups(self, applet, arrayOfObjects=False):
     # get role list for applet
     roleList = self.getFullRolesList(applet)
     # query groups from role list`& return
     appletGroups = {
         role:
         {g.get("_id"): g.get("name")
          for g in roleList[role]['groups']}
         for role in roleList
     }
     return ([{
         "id":
         groupId,
         "name":
         role,
         "openRegistration":
         GroupModel().load(groupId, force=True).get('openRegistration',
                                                    False)
     } if role == 'user' else {
         "id": groupId,
         "name": role
     } for role in appletGroups for groupId in appletGroups[role].keys()]
             if arrayOfObjects else appletGroups)
Exemplo n.º 5
0
    def createApplet(self,
                     name,
                     protocol={},
                     user=None,
                     roles=None,
                     constraints=None):
        """
        Method to create an Applet.

        :param name: Name for the Applet
        :type name: str
        :param protocol: Protocol to link to this Applet, with one or both
            keys: {`_id`, `url`}
        :type protocol: dict
        :param user: User creating Applet
        :type user: dict
        :param roles: Roles to set to this Applet
        :type roles: dict or None
        :param constraints: Constraints to set to this Applet
        :type constraints: dict or None
        """
        from girderformindlogger.utility import jsonld_expander

        if user == None:
            raise AccessException("You must be logged in to create an applet.")
        appletsCollection = CollectionModel().findOne({"name": "Applets"})

        # create the Applets collection if it isn't there!
        if not appletsCollection:
            CollectionModel().createCollection('Applets')
            appletsCollection = CollectionModel().findOne({"name": "Applets"})

        # create new applet
        applet = self.setMetadata(
            folder=self.createFolder(parent=appletsCollection,
                                     name=name,
                                     parentType='collection',
                                     public=True,
                                     creator=user,
                                     allowRename=True),
            metadata={
                'protocol': protocol,
                'applet': constraints if constraints is not None
                and isinstance(constraints, dict) else {}
            })

        appletGroupName = "Default {} ({})".format(name,
                                                   str(applet.get('_id', '')))

        print("Name: {}".format(appletGroupName))
        # Create user groups
        for role in USER_ROLES.keys():
            try:
                group = GroupModel().createGroup(
                    name="{} {}s".format(appletGroupName, role.title()),
                    creator=user,
                    public=False if role == 'user' else True)
            except ValidationException:
                numero = 0
                numberedName = appletGroupName
                while GroupModel().findOne(query={'name': numberedName}):
                    numero += 1
                    numberedName = "{} {} {}s".format(appletGroupName,
                                                      str(numero),
                                                      role.title())
                group = GroupModel().createGroup(
                    name=numberedName,
                    creator=user,
                    public=False if role == 'user' else True)
            self.setGroupRole(doc=applet,
                              group=group,
                              role=role,
                              currentUser=user,
                              force=False)
        return (jsonld_expander.formatLdObject(applet, 'applet', user))
Exemplo n.º 6
0
def _invite(applet, user, role, rsvp, subject):
    """
    Helper function to invite a user to an applet.

    :param applet: Applet to invite user to
    :type applet: AppletModel
    :param user: ID (canonical or applet-specific) or email address of user to
                 invite
    :type user: string
    :param role: Role to invite user to
    :type role: string
    :param rsvp: Require user acceptance?
    :type rsvp: boolean
    :param subject: Subject about 'user' role can inform or about which
                    'reviewer' role can review
    :type subject: string or literal
    :returns: New assignment (dictionary)
    """
    if role not in USER_ROLE_KEYS:
        raise ValidationException('Invalid role.', 'role')
    thisUser = Applet().getCurrentUser()
    user = user if user else str(thisUser['_id'])

    if mail_utils.validateEmailAddress(user):
        user = UserModel().hash(user)

    if bool(rsvp):
        groupName = {'title': '{} {}s'.format(str(applet.get('_id')), role)}
        groupName['lower'] = groupName.get('title', '').lower()
        group = GroupModel().findOne(query={'lowerName': groupName['lower']})
        if not group or group is None:
            group = GroupModel().createGroup(
                name=groupName['title'],
                creator=thisUser,
                public=bool(role in ['manager', 'reviewer']))
    try:
        assignments = CollectionModel().createCollection(name="Assignments",
                                                         public=True,
                                                         reuseExisting=True)
        assignmentType = 'collection'
    except AccessException:
        assignments, assignmentType = selfAssignment()
    appletAssignment = list(FolderModel().childFolders(
        parent=assignments,
        parentType=assignmentType,
        user=thisUser,
        filters={
            'meta.applet.@id': str(applet['_id']) if '_id' in applet else None
        }))
    appletAssignment = appletAssignment[0] if len(
        appletAssignment) else FolderModel().setMetadata(
            FolderModel().createFolder(
                parent=assignments,
                name=FolderModel().preferredName(applet),
                parentType=assignmentType,
                public=False,
                creator=thisUser,
                allowRename=True,
                reuseExisting=False), {
                    'applet': {
                        '@id': str(applet['_id']) if '_id' in applet else None
                    }
                })
    meta = appletAssignment.get('meta', {})
    members = meta.get('members',
                       []) if meta.get('members') is not None else []
    cUser = getUserCipher(appletAssignment, user)
    subject = subject.upper() if subject is not None and subject.upper(
    ) in SPECIAL_SUBJECTS else getUserCipher(
        appletAssignment,
        str(thisUser['_id']) if subject is None else subject)
    thisAppletAssignment = {
        '@id': str(cUser),
        'roles': {
            role: True if role not in ['reviewer', 'user'] else [subject]
        }
    }
    for i, u in enumerate(members):
        if '@id' in u and u["@id"] == str(cUser):
            thisAppletAssignment = members.pop(i)
            if 'roles' not in thisAppletAssignment:
                thisAppletAssignment['roles'] = {}
            thisAppletAssignment['roles'][role] = True if role not in [
                'reviewer', 'user'
            ] else [subject] if (subject in SPECIAL_SUBJECTS) or (
                'reviewer' not in thisAppletAssignment['roles']) else list(
                    set(thisAppletAssignment['roles']['reviewer'] +
                        [subject]).difference(set(SPECIAL_SUBJECTS))
                ) if "ALL" not in thisAppletAssignment['roles'][
                    'reviewer'] else ["ALL"]
    members.append(thisAppletAssignment)
    meta['members'] = members
    appletAssignment = FolderModel().setMetadata(appletAssignment, meta)
    authorizeReviewers(appletAssignment)
    return (appletAssignment)
Exemplo n.º 7
0
    def createApplet(self,
                     name,
                     protocol={},
                     user=None,
                     roles=None,
                     constraints=None,
                     appletName=None):
        """
        Method to create an Applet.

        :param name: Name for the Applet
        :type name: str
        :param protocol: Protocol to link to this Applet, with one or both
            keys: {`_id`, `url`}
        :type protocol: dict
        :param user: User creating Applet
        :type user: dict
        :param roles: Roles to set to this Applet
        :type roles: dict or None
        :param constraints: Constraints to set to this Applet
        :type constraints: dict or None
        """
        from girderformindlogger.utility import jsonld_expander

        if user == None:
            raise AccessException("You must be logged in to create an applet.")
        appletsCollection = CollectionModel().findOne({"name": "Applets"})

        # create the Applets collection if it isn't there!
        if not appletsCollection:
            CollectionModel().createCollection('Applets')
            appletsCollection = CollectionModel().findOne({"name": "Applets"})

        appletName = self.validateAppletName(appletName, appletsCollection,
                                             user)

        # create new applet
        applet = self.setMetadata(
            folder=self.createFolder(parent=appletsCollection,
                                     name=name,
                                     parentType='collection',
                                     public=True,
                                     creator=user,
                                     allowRename=True,
                                     appletName=appletName),
            metadata={
                'protocol': protocol,
                'applet': constraints if constraints is not None
                and isinstance(constraints, dict) else {}
            })

        appletGroupName = "Default {} ({})".format(name,
                                                   str(applet.get('_id', '')))

        print("Name: {}".format(appletGroupName))
        # Create user groups
        role2AccessLevel = {
            'user': AccessType.READ,
            'coordinator': AccessType.ADMIN,
            'manager': AccessType.ADMIN,
            'editor': AccessType.WRITE,
            'reviewer': AccessType.READ
        }
        accessList = applet.get('access', {})
        accessList['groups'] = []

        for role in USER_ROLES.keys():
            try:
                group = GroupModel().createGroup(
                    name="{} {}s".format(appletGroupName, role.title()),
                    creator=user,
                    public=False if role == 'user' else True)
                accessList['groups'].append({
                    'id': ObjectId(group['_id']),
                    'level': role2AccessLevel[role]
                })

            except ValidationException:
                numero = 0
                numberedName = appletGroupName
                while GroupModel().findOne(query={'name': numberedName}):
                    numero += 1
                    numberedName = "{} {} {}s".format(appletGroupName,
                                                      str(numero),
                                                      role.title())
                group = GroupModel().createGroup(
                    name=numberedName,
                    creator=user,
                    public=False if role == 'user' else True)
            self.setGroupRole(doc=applet,
                              group=group,
                              role=role,
                              currentUser=user,
                              force=False)

        self.setAccessList(applet, accessList)
        self.update({'_id': ObjectId(applet['_id'])},
                    {'$set': {
                        'access': applet.get('access', {})
                    }})

        from girderformindlogger.models.profile import Profile

        # give all roles to creator of an applet
        profile = Profile().createProfile(applet, user, 'manager')
        profile = Profile().load(profile['_id'], force=True)

        profile['roles'] = list(USER_ROLES.keys())
        Profile().save(profile, False)

        UserModel().appendApplet(UserModel().load(user['_id'], force=True),
                                 applet['_id'], USER_ROLES.keys())

        return (jsonld_expander.formatLdObject(applet,
                                               'applet',
                                               user,
                                               refreshCache=False))