Ejemplo n.º 1
0
    def generateTemporaryPassword(self, email):
        user = self._model.findOne({'email': self._model.hash(email.lower()), 'email_encrypted': True})

        if not user:
            user = self._model.findOne({'email': email.lower(), 'email_encrypted': {'$ne': True}})

        if not user:
            raise RestException('That email is not registered.')

        token = Token().createToken(user, days=(15/1440.0), scope=TokenScope.TEMPORARY_USER_AUTH)

        url = '%s#useraccount/%s/token/%s' % (
            mail_utils.getEmailUrlPrefix(), str(user['_id']), str(token['_id']))

        html = mail_utils.renderTemplate('temporaryAccess.mako', {
            'url': url,
            'token': str(token['_id'])
        })

        mail_utils.sendMail(
            '%s: Temporary access' % Setting().get(SettingKey.BRAND_NAME),
            html,
            [email]
        )
        return {'message': 'Sent temporary access email.'}
Ejemplo n.º 2
0
def _uploadComplete(event):
    """
    Called after an upload finishes. We check if our current token is a special
    authorized upload token, and if so, delete it.

    TODO we could alternatively keep a reference count inside each token that authorized
    more than a single upload at a time, and just decrement it here.
    """
    token = getCurrentToken()
    if token and 'authorizedUploadId' in token:
        user = User().load(token['userId'], force=True)
        item = Item().load(event.info['file']['itemId'], force=True)

        # Save the metadata on the item
        item['description'] = token['authorizedUploadDescription']
        item['authorizedUploadEmail'] = token['authorizedUploadEmail']
        Item().save(item)

        text = mail_utils.renderTemplate('authorized_upload.uploadFinished.mako', {
            'itemId': item['_id'],
            'itemName': item['name'],
            'itemDescription': item.get('description', '')
        })
        mail_utils.sendMail('Authorized upload complete', text, [user['email']])
        Token().remove(token)
Ejemplo n.º 3
0
 def _sendApprovedEmail(self, user):
     text = mail_utils.renderTemplate('accountApproved.mako', {
         'user': user,
         'url': mail_utils.getEmailUrlPrefix()
     })
     mail_utils.sendMail('Girder: Account approved', text,
                         [user.get('email')])
Ejemplo n.º 4
0
 def _sendCreateAccountEmail(self, user, email):
     # from girderformindlogger.models.token import Token
     #
     # token = Token().createToken(
     #     user, days=1, scope=TokenScope.EMAIL_VERIFICATION)
     url = 'https://web.mindlogger.org/#/signup?email={}'.format(email)
     text = mail_utils.renderTemplate('emailCreateAccount.mako',
                                      {'url': url})
     mail_utils.sendMail(to=email,
                         subject='MindLogger: Invitation',
                         text=text)
Ejemplo n.º 5
0
    def _sendVerificationEmail(self, user, email):
        from girderformindlogger.models.token import Token

        token = Token().createToken(user,
                                    days=1,
                                    scope=TokenScope.EMAIL_VERIFICATION)
        url = '%s#useraccount/%s/verification/%s' % (
            mail_utils.getEmailUrlPrefix(), str(user['_id']), str(
                token['_id']))
        text = mail_utils.renderTemplate('emailVerification.mako',
                                         {'url': url})
        mail_utils.sendMail('Girder: Email verification', text, [email])
Ejemplo n.º 6
0
 def _sendCreateAccountEmail(self, user, email):
     # from girderformindlogger.models.token import Token
     #
     # token = Token().createToken(
     #     user, days=1, scope=TokenScope.EMAIL_VERIFICATION)
     web_url = os.getenv('WEB_URI') or 'localhost:8082'
     url = f'https://{web_url}/#/signup?email={email}'
     text = mail_utils.renderTemplate('emailCreateAccount.mako', {
         'url': url
     })
     mail_utils.sendMail(
         to=email,
         subject='MindLogger: Invitation',
         text=text)
    def createAppletFromUrl(self,
                            name,
                            protocolUrl,
                            user=None,
                            roles=None,
                            constraints=None,
                            sendEmail=True):
        from girderformindlogger.models.protocol import Protocol
        # get a protocol from a URL
        protocol = Protocol().getFromUrl(protocolUrl,
                                         'protocol',
                                         user,
                                         thread=False,
                                         refreshCache=True)
        protocol = protocol[0].get('protocol', protocol[0])

        displayName = Protocol().preferredName(protocol)

        name = name if name is not None and len(name) else displayName
        if len(displayName) == 0:
            displayName = name if len(name) else "activity"

        applet = self.createApplet(
            name=name,
            protocol={
                '_id':
                'protocol/{}'.format(str(protocol.get('_id')).split('/')[-1]),
                'url':
                protocol.get('meta', {}).get('protocol',
                                             {}).get('url', protocolUrl)
            },
            user=user,
            roles=roles,
            constraints=constraints,
            displayName=displayName)
        emailMessage = "Your applet, {}, has been successfully created. The "  \
            "applet's ID is {}".format(
                name,
                str(applet.get('applet', applet).get('_id')
            )
        )
        if sendEmail and 'email' in user:
            from girderformindlogger.utility.mail_utils import sendMail
            sendMail(subject=name, text=emailMessage, to=[user['email']])
        print(emailMessage)
Ejemplo n.º 8
0
    def inviteToGroup(
        self,
        group,
        userToInvite=None,
        email=None,
        level=AccessType.READ,
        quiet=False,
        force=False
    ):
        if ((
            userToInvite is None and email is None
        ) or (
            userToInvite is not None and email is not None
        )):
            raise ValidationException(
                "`POST /group/{id}/invitation` requires exactly one of `userID`"
                "and `email`."
            )
        groupModel = self._model
        user = self.getCurrentUser()
        if email is not None:
            userToInvite = User().findOne(query={"email": email}, force=True)
        if userToInvite is None:
            try:
                group["queue"] = list(set([email, *group.get("queue", [])]))
            except:
                group["queue"] = list(set([email]))
            groupModel.updateGroup(group)
            userToInvite = ProtoUser().createProtoUser(email=email)
            # TODO: send email to invite user
            return(group)
        if force:
            if not user['admin']:
                mustBeAdmin = True
                addPolicy = Setting().get(SettingKey.ADD_TO_GROUP_POLICY)
                addGroup = group.get('addAllowed', 'default')
                if addGroup not in ['no', 'yesadmin', 'yesmod']:
                    addGroup = addPolicy
                if (groupModel.hasAccess(
                        group, user, AccessType.ADMIN)
                        and ('mod' in addPolicy or 'admin' in addPolicy)
                        and addGroup.startswith('yes')):
                    mustBeAdmin = False
                elif (groupModel.hasAccess(
                        group, user, AccessType.WRITE)
                        and 'mod' in addPolicy
                        and addGroup == 'yesmod'):
                    mustBeAdmin = False
                if mustBeAdmin:
                    self.requireAdmin(user)
            groupModel.addUser(group, userToInvite, level=level)
        else:
            # Can only invite into access levels that you yourself have
            groupModel.requireAccess(group, user, level)
            groupModel.inviteUser(group, userToInvite, level)

            if not quiet:
                html = mail_utils.renderTemplate('groupInvite.mako', {
                    'userToInvite': userToInvite,
                    'user': user,
                    'group': group
                })
                mail_utils.sendMail(
                    "%s: You've been invited to a group" % Setting().get(SettingKey.BRAND_NAME),
                    html,
                    [userToInvite['email']]
                )

        group['access'] = groupModel.getFullAccessList(group)
        group['requests'] = list(groupModel.getFullRequestList(group))
        return(group)
Ejemplo n.º 9
0
    def inviteUser(self,
                   applet,
                   role="user",
                   email='',
                   firstName='',
                   lastName='',
                   MRN=''):
        from girderformindlogger.models.invitation import Invitation
        from girderformindlogger.models.profile import Profile

        if not mail_utils.validateEmailAddress(email):
            raise ValidationException('invalid email', 'email')

        thisUser = self.getCurrentUser()

        encryptedEmail = UserModel().hash(email)
        invitedUser = UserModel().findOne({
            'email': encryptedEmail,
            'email_encrypted': True
        })

        if not invitedUser:
            invitedUser = UserModel().findOne({
                'email': email,
                'email_encrypted': {
                    '$ne': True
                }
            })

        if not AppletModel().isCoordinator(applet['_id'], thisUser):
            raise AccessException(
                "Only coordinators and managers can invite users.")

        if role not in USER_ROLE_KEYS:
            raise ValidationException('Invalid role.', 'role')

        invitation = Invitation().createInvitationForSpecifiedUser(
            applet=applet,
            coordinator=thisUser,
            role=role,
            user=invitedUser,
            firstName=firstName,
            lastName=lastName,
            MRN=MRN,
            userEmail=encryptedEmail)

        url = 'web.mindlogger.org/#/invitation/%s' % (str(invitation['_id'], ))

        managers = mail_utils.htmlUserList(AppletModel().listUsers(applet,
                                                                   'manager',
                                                                   force=True))
        coordinators = mail_utils.htmlUserList(AppletModel().listUsers(
            applet, 'coordinator', force=True))
        reviewers = mail_utils.htmlUserList(AppletModel().listUsers(
            applet, 'reviewer', force=True))

        html = mail_utils.renderTemplate(
            'userInvite.mako'
            if invitedUser else 'inviteUserWithoutAccount.mako', {
                'url': url,
                'userName': firstName,
                'coordinatorName': thisUser['firstName'],
                'appletName': applet['displayName'],
                'MRN': MRN,
                'managers': managers,
                'coordinators': coordinators,
                'reviewers': reviewers
            })

        mail_utils.sendMail('invitation for an applet', html, [email])

        return 'sent invitation mail to {}'.format(email)