Ejemplo n.º 1
0
    def deactivateApplet(self, folder):
        from girderformindlogger.models.profile import Profile

        applet = folder
        user = Applet().getCurrentUser()
        applet['meta']['applet']['deleted'] = True
        applet = AppletModel().setMetadata(applet, applet.get('meta'), user)
        if applet.get('meta', {}).get('applet', {}).get('deleted') == True:
            message = 'Successfully deactivated applet {} ({}).'.format(
                AppletModel().preferredName(applet), applet.get('_id'))

            users = list(Profile().find(
                {
                    'appletId': ObjectId(applet['_id']),
                    'deactivated': {
                        '$ne': True
                    }
                },
                fields=['userId']))
            Profile().deactivateProfile(applet['_id'], None)

            for user in users:
                if 'userId' in user:
                    UserModel().removeApplet(
                        UserModel().findOne({'_id': ObjectId(user['userId'])}),
                        applet['_id'])
        else:
            message = 'Could not deactivate applet {} ({}).'.format(
                AppletModel().preferredName(applet), applet.get('_id'))
            Description().errorResponse(message, 403)
        return (message)
Ejemplo n.º 2
0
 def deactivateApplet(self, folder):
     applet = folder
     user = Applet().getCurrentUser()
     applet['meta']['applet']['deleted'] = True
     applet = AppletModel().setMetadata(applet, applet.get('meta'), user)
     if applet.get('meta', {}).get('applet', {}).get('deleted') == True:
         message = 'Successfully deactivated applet {} ({}).'.format(
             AppletModel().preferredName(applet), applet.get('_id'))
     else:
         message = 'Could not deactivate applet {} ({}).'.format(
             AppletModel().preferredName(applet), applet.get('_id'))
         Description().errorResponse(message, 403)
     return (message)
Ejemplo n.º 3
0
def _setConstraints(applet, activity, schedule, user, refreshCache=False):
    """
    Helper function for method recursion.

    :param applet: applet Object
    :type applet: dict
    :param activity: Activity ID
    :type activity: str, list, or None
    :param schedule: schedule data
    :type schedule: dict, list, or None
    :param user: user making the call
    :type user: dict
    :returns: updated applet Object
    """
    if activity is None:
        if schedule is not None:
            appletMeta = applet.get('meta', {})
            appletMeta['applet']['schedule'] = schedule
            applet = AppletModel().setMetadata(applet, appletMeta)
        return (applet)
    if isinstance(activity, str) and activity.startswith('['):
        try:
            activity = [
                activity_.replace("'", "").replace('"', '').strip()
                for activity_ in activity[1:-1].split(',')
            ]
        except (TypeError, AttributeError) as e:
            print(e)
    if isinstance(activity, list):
        for activity_ in activity:
            applet = _setConstraints(applet, activity_, schedule, user)
        return (applet)
    try:
        activityLoaded = ActivityModel().getFromUrl(activity, 'activity',
                                                    thisUser, refreshCache)[0]
    except:
        activityLoaded = ActivityModel().load(activity, AccessType.WRITE, user)
    try:
        activityMeta = activityLoaded['meta'].get('activity')
    except AttributeError:
        raise ValidationException('Invalid activity.', 'activity')
    activityKey = activityMeta.get(
        'url', activityMeta.get('@id', activityLoaded.get('_id')))
    if activityKey is None:
        raise ValidationException('Invalid activity.', 'activity')
    else:
        activityKey = jsonld_expander.reprolibPrefix(activityKey)
    protocolExpanded = jsonld_expander.formatLdObject(applet, 'applet',
                                                      user).get('applet', {})
    protocolOrder = protocolExpanded.get('ui', {}).get('order', [])
    framedActivityKeys = [
        protocolOrder[i] for i, v in enumerate(
            protocolExpanded.get("reprolib:terms/order")[0].get("@list"))
        if jsonld_expander.reprolibPrefix(v.get("@id")) == activityKey
    ]
    if schedule is not None:
        appletMeta = applet.get('meta', {})
        scheduleInApplet = appletMeta.get('applet', {}).get('schedule', {})
        for k in framedActivityKeys:
            scheduleInApplet[k] = schedule
        appletMeta['applet']['schedule'] = scheduleInApplet
        applet = AppletModel().setMetadata(applet, appletMeta)
    return (applet)
Ejemplo n.º 4
0
    def createProfile(self, applet, user, role="user"):
        """
        Create a new profile to store information specific to a given (applet ∩
            user)

        :param applet: The applet for which this profile exists
        :type applet: dict
        :param user: The user for which this profile exists
        :type user: dict
        :returns: The profile document that was created.
        """
        from girderformindlogger.models.applet import Applet
        from girderformindlogger.models.group import Group

        if not isinstance(applet, dict):
            applet = Applet().load(applet, force=True)
        user = self._canonicalUser(applet["_id"], user)
        returnFields = ["_id", "appletId", "coordinatorDefined", "userDefined"]
        existing = self.findOne(
            {
                'appletId': applet['_id'],
                'userId': user['_id'],
                'profile': True
            },
            fields=[*returnFields, "deactivated"])

        if applet['_id'] not in [
                a.get('_id') for a in Applet().getAppletsForUser(role, user)
        ]:
            appletGroups = Applet().getAppletGroups(applet)

            roles = ['user', 'editor', 'reviewer', 'coordinator', 'manager'
                     ] if role == 'manager' else [role]
            if 'user' not in roles:
                roles.append('user')

            for role in roles:
                groups = appletGroups.get(role)
                if bool(groups):
                    group = Group().load(ObjectId(list(groups.keys())[0]),
                                         force=True)

                    if group['_id'] not in user.get('groups', []):
                        Group().inviteUser(group, user, level=AccessType.READ)
                        Group().joinGroup(group, user)
                else:
                    raise ValidationException(
                        "User does not have role \"{}\" in this \"{}\" applet "
                        "({})".format(role,
                                      Applet().preferredName(applet),
                                      str(applet['_id'])))

        if existing and not existing.get('deactivated', False):
            if "deactivated" in existing:
                existing.pop("deactivated")

            return existing

        now = datetime.datetime.utcnow()

        managers = list(
            self.find(query={
                'appletId': applet['_id'],
                'roles': 'manager'
            },
                      fields=['_id']))
        profile = {
            k: v
            for k, v in {
                'appletId':
                ObjectId(applet['_id']),
                'userId':
                ObjectId(user['_id']),
                'profile':
                True,
                'badge':
                0,
                'created':
                now,
                'updated':
                now,
                'deviceId':
                user['deviceId'],
                'timezone':
                user['timezone'],
                'individual_events':
                0,
                'completed_activities': [{
                    'activity_id': activity_id,
                    'completed_time': None
                } for activity_id in applet.get('meta', {}).get(
                    'protocol', {}).get('activities', [])],
                'accountId':
                applet.get('accountId', None),
                'size':
                0,
                'coordinatorDefined': {},
                'userDefined': {
                    'displayName':
                    user.get('displayName', user.get('firstName')),
                    'email':
                    user.get('email'
                             ) if not user.get('email_encrypted', None) else ''
                },
                'reviewers': [manager['_id'] for manager in managers]
            }.items() if v is not None
        }

        if existing:
            profile['_id'] = existing['_id']

        self.setPublic(profile, False, save=False)

        # Save the profile.
        self.save(profile, validate=False)
        return ({k: v for k, v in profile.items() if k in returnFields})
Ejemplo n.º 5
0
    def htmlInvitation(
        self,
        invitation,
        invitee=None,
        fullDoc=False,
        includeLink=True
    ):
        """
        Returns an HTML document rendering the invitation.

        :param invitation: Invitation to render
        :type invitation: dict
        :param invitee: Invited user
        :type invitee: dict or None

        :returns: html document
        """
        from girderformindlogger.models.applet import Applet
        from girderformindlogger.models.profile import Profile
        from girderformindlogger.models.protocol import Protocol
        from girderformindlogger.models.token import Token
        from girderformindlogger.models.user import User
        from girderformindlogger.exceptions import GirderException
        from girderformindlogger.api.rest import getApiUrl
        from girderformindlogger.utility import context as contextUtil,        \
            mail_utils

        accept = (
            "To accept or decline, visit <a href=\"{u}\">{u}</a>".format(
                u="https://web.mindlogger.org/#/invitation/{}".format(str(
                    invitation['_id']
                ))
            )
        ) if includeLink else ""
        applet = Applet().load(ObjectId(invitation['appletId']), force=True)
        appletName = applet.get(
            'displayName',
            'a new applet'
        )
        try:
            skin = contextUtil.getSkin()
        except:
            skin = {}
        instanceName = skin.get("name", "MindLogger")
        role = invitation.get("role", "user")
        try:
            coordinator = Profile().coordinatorProfile(
                applet['_id'],
                invitation["invitedBy"]
            )
        except:
            coordinator = None
        displayProfile = Profile().displayProfileFields(invitation, invitee)
        description = applet.get('meta', {}).get(
            'applet',
            {}
        ).get(
            "schema:desciription",
            Protocol().load(
                applet['meta']['protocol']['_id'].split('protocol/')[-1],
                force=True
            ).get('meta', {}).get('protocol') if 'protocol' in applet.get(
                'meta',
                {}
            ) else {}
        ).get("schema:description", "")
        managers = mail_utils.htmlUserList(
            Applet().listUsers(applet, 'manager', force=True)
        )
        coordinators = mail_utils.htmlUserList(
            Applet().listUsers(applet, 'coordinator', force=True)
        )
        reviewers = mail_utils.htmlUserList(
            Applet().listUsers(applet, 'reviewer', force=True)
        )
        body = """
{greeting}ou were invited {byCoordinator}to be {role} of <b>{appletName}</b>{instanceName}.
<br/>
Below are the users that have access to your data:
{reviewers}
{managers}
{coordinators}
<br/>
{accept}
        """.format(
            accept=accept,
            appletName=appletName,
            byCoordinator="by {} ({}) ".format(
                coordinator.get("displayName", "an anonymous entity"),
                "<a href=\"mailto:{email}\">{email}</a>".format(
                    email=coordinator["email"]
                ) if "email" in coordinator and coordinator["email"] is not None else "email not available"
            ) if isinstance(coordinator, dict) else "",
            coordinators="<h3>Users who can change this applet's settings, "
                "but who cannot change who can see your data: </h3>{}"
                "".format(
                    coordinators if len(
                        coordinators
                    ) else "<ul><li>None</li></ul>"
                ),
            greeting="Welcome to MindLogger! Y",
            instanceName=" on {}".format(
                instanceName
            ) if instanceName is not None and len(instanceName) else "",
            managers="<h3>Users who can change this applet's settings, "
                " including who can access your data: </h3>{}"
                "".format(
                    managers if len(managers) else "<ul><li>None</li></ul>"
                ),
            reviewers="<h3>Users who can see your data for this "
                "applet: </h3>{}"
                "".format(
                    reviewers if len(reviewers) else "<ul><li>None</li></ul>"
                ),
            role="an editor" if role=="editor" else "a {}".format(role)
        ).strip()
        return(body if not fullDoc else """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Invitation to {appletName} on {instanceName}</title>
</head>
<body>
{body}
</body>
</html>
        """.format(
            appletName=appletName,
            instanceName=instanceName,
            body=body
        ).strip())
Ejemplo n.º 6
0
    def htmlInvitation(self,
                       invitation,
                       invitee=None,
                       fullDoc=False,
                       includeLink=True):
        """
        Returns an HTML document rendering the invitation.

        :param invitation: Invitation to render
        :type invitation: dict
        :param invitee: Invited user
        :type invitee: dict or None

        :returns: html document
        """
        from girderformindlogger.models.applet import Applet
        from girderformindlogger.models.profile import Profile
        from girderformindlogger.models.protocol import Protocol
        from girderformindlogger.models.token import Token
        from girderformindlogger.models.user import User
        from girderformindlogger.exceptions import GirderException
        from girderformindlogger.api.rest import getApiUrl
        from girderformindlogger.utility import context as contextUtil,        \
            mail_utils

        web_url = os.getenv('WEB_URI') or 'localhost:8082'

        accept = ("To accept or decline, visit <a href=\"{u}\">{u}</a>".format(
            u=f"https://{web_url}/#/invitation/{str(invitation['_id'])}")
                  ) if includeLink else ""
        applet = Applet().load(ObjectId(invitation['appletId']), force=True)
        appletName = applet['meta']['applet'].get(
            'displayName', applet.get('displayName', 'new applet'))
        try:
            skin = contextUtil.getSkin()
        except:
            skin = {}
        instanceName = skin.get("name", "MindLogger")
        role = invitation.get("role", "user")
        try:
            coordinator = Profile().coordinatorProfile(applet['_id'],
                                                       invitation["invitedBy"])
        except:
            coordinator = None
        displayProfile = Profile().displayProfileFields(invitation, invitee)
        description = applet.get('meta', {}).get('applet', {}).get(
            "schema:description",
            Protocol().load(
                applet['meta']['protocol']['_id'].split('protocol/')[-1],
                force=True).get('meta', {}).get('protocol') if 'protocol'
            in applet.get('meta', {}) else {}).get("schema:description", "")
        managers = mail_utils.htmlUserList(Applet().listUsers(applet,
                                                              'manager',
                                                              force=True))
        coordinators = mail_utils.htmlUserList(Applet().listUsers(
            applet, 'coordinator', force=True))
        reviewers = mail_utils.htmlUserList(Applet().listUsers(applet,
                                                               'reviewer',
                                                               force=True))

        body = mail_utils.renderTemplate(
            f'welcome{"Owner" if role == "owner" else ""}.{invitation.get("lang", "en")}.mako',
            {
                'accept':
                accept,
                'appletName':
                appletName,
                'byCoordinator':
                "by {} ({}) ".format(
                    coordinator.get("displayName", "an anonymous entity"),
                    "<a href=\"mailto:{email}\">{email}</a>".format(
                        email=coordinator["email"]) if "email" in coordinator
                    and coordinator["email"] is not None
                    else "email not available") if isinstance(
                        coordinator, dict) else "",
                'coordinators':
                "{}".format(coordinators if len(coordinators) else
                            "<ul><li>None</li></ul>"),
                'instanceName':
                " on {}".format(instanceName)
                if instanceName is not None and len(instanceName) else "",
                'managers':
                "{}".format(
                    managers if len(managers) else "<ul><li>None</li></ul>"),
                'reviewers':
                "{}".format(
                    reviewers if len(reviewers) else "<ul><li>None</li></ul>"),
                'role':
                "an editor" if role == "editor" else "a {}".format(role),
                'url':
                f'https://{web_url}/#/invitation/{str(invitation["_id"])}'
            })

        return (body if not fullDoc else """
            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="UTF-8">
            <title>Invitation to {appletName} on {instanceName}</title>
            </head>
            <body>
            {body}
            </body>
            </html>
        """.format(appletName=appletName, instanceName=instanceName,
                   body=body).strip())