コード例 #1
0
def childByParent(parent, applet, parentProfile=None):
    from girderformindlogger.models.profile import Profile

    parentProfile = Profile().getProfile(
        Profile().createProfile(
            applet['applet']['_id'].split('applet/')[-1],
            parent,
            "user"
        ).get('_id'),
        user=parent
    ) if parentProfile is None else parentProfile
    parentKnows = parentProfile.get('schema:knows', {})
    children = [Profile().displayProfileFields(
        Profile().load(
            p,
            force=True
        ),
        parent
    ) for p in list(
            set(parentKnows.get('rel:parentOf', {})).union(
                set(parentKnows.get('schema:children', {}))
            )
        )
    ]
    return([
        formatChildApplet(child, deepcopy(applet)) for child in children
    ])
コード例 #2
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())
コード例 #3
0
    def acceptInvitation(self, invitation, user, userEmail = ''): # we need to save coordinator/manager's email as plain text
        from girderformindlogger.models.applet import Applet
        from girderformindlogger.models.ID_code import IDCode
        from girderformindlogger.models.profile import Profile
        from girderformindlogger.utility import mail_utils

        applet = Applet().load(invitation['appletId'], force=True)
        profiles = None
        if 'idCode' in invitation:
            profiles = IDCode().findProfile(invitation['idCode'])
        if profiles and len(profiles):
            profile = [
                pro for pro in profiles if str(
                    pro.get('userId')
                )==str(user['_id'])
            ]
            profile = profile[0] if len(profile) else None
        else:
            profile = None
            Profile().removeWithQuery({ '_id': ObjectId(invitation['_id']) })

        if profile==None or not len(profile):
            profile = Profile().createProfile(
                applet,
                user,
                role=invitation.get('role', 'user')
            )
            IDCode().createIdCode(profile, invitation.get('idCode'))
        if 'schema:knows' in invitation:
            if 'schema:knows' not in profile:
                profile['schema:knows'] = invitation['schema:knows']
            else:
                for k in invitation['schema:knows']:
                    if k in profile['schema:knows']:
                        profile['schema:knows'][k].extend([
                            r for r in invitation['schema:knows'][
                                k
                            ] if r not in profile['schema:knows'][k]
                        ])
                    else:
                        profile['schema:knows'][k] = invitation['schema:knows'][
                            k
                        ]

        # append role value
        profile = Profile().load(profile['_id'], force=True)
        profile['roles'] = profile.get('roles', [])
        invited_role = invitation.get('role','user')

        new_roles = []
        # manager has get all roles by default
        for role in USER_ROLES.keys():
            if role not in profile['roles']:
                if invited_role == 'manager' or invited_role == role or role == 'user':
                    new_roles.append(role)
                    profile['roles'].append(role)

        profile['firstName'] = invitation.get('firstName', '')
        profile['lastName'] = invitation.get('lastName', '')
        profile['MRN'] = invitation.get('MRN', '')

        Profile().save(profile, validate=False)

        from girderformindlogger.models.user import User as UserModel
        
        if not mail_utils.validateEmailAddress(userEmail):
            raise ValidationException(
                'Invalid email address.',
                'email'
            )
        if invited_role != 'user' and user.get('email_encrypted', False):
            if UserModel().hash(userEmail) != user['email']:
                raise ValidationException(
                    'Invalid email address.',
                    'email'
                )
            user['email'] = userEmail
            user['email_encrypted'] = False

            UserModel().save(user)

        UserModel().appendApplet(user, applet['_id'], new_roles)

        self.remove(invitation)        
        return(Profile().displayProfileFields(
            Profile().load(profile['_id'], force=True),
            user
        ))
コード例 #4
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())