Exemplo n.º 1
0
def confirmEmails(qConfirmEmails):
    """
    Process Event and send an Email to the user to confirm his/her email
    """
    # db connection is shared between threads
    dbconnection = connect()
    while True:
        try:
            event = Event(qConfirmEmails.get())
        except Exception as e:
            logger.exception(e)
            logger.error("Problem with event: {}".format(e))
            continue
        else:
            if event.notify:
                # We try to send the email only once
                event.notify = False
                dispatch(dbconnection, event)
                try:
                    # Recipients
                    # Status did NOT changed
                    if event.status == event.previous_status:
                        logger.warning("TODO: send specific emails with messages")
                    recipients = set()

                    url = s.web['url']
                    if s.web['port'] and s.web['port'] != 80:
                        url = url +':'+ s.web['port']

                    # Look for the user email in the Event
                    if event.object.type == ObjectType.USER:
                        recipients.add(User(event.data))
                    elif event.object.type == ObjectType.AUTHORITY:
                        for user in event.data['users']:
                            recipients.add(User(user))
                    else:
                        for user in event.data['pi_users']:
                            recipients.add(User(user))

                    url = url+'/confirm/'+event.id
                    subject, template = build_subject_and_template('confirm', event)
                    buttonLabel = "Confirm Email"

                    sendEmail(event, recipients, subject, template, url, buttonLabel)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    msg = "Error in event {} while trying to send a confirmation email: {}".format(event.id, e)
                    logger.error(msg)
                    event.logWarning(msg)
                    continue
                finally:
                    dispatch(dbconnection, event)
Exemplo n.º 2
0
def emails_run(qEmails):
    """
    Process Requests and send Emails accordingly
    """

    # db connection is shared between threads
    dbconnection = connect()
    while True:
        try:
            event = Event(qEmails.get())
        except Exception as e:
            logger.error("Problem with event: {}".format(e))
            continue
        else:
            if event.notify:
                # We try to send the email only once
                event.notify = False
                dispatch(dbconnection, event)

                # Recipients
                # TODO: Send specific emails
                # Status did NOT changed
                # Comments about an event with a message
                if event.status == event.previous_status:
                    logger.warning("TODO: send specific emails with messages")
                recipients = set()

                url = s.web['url']
                if s.web['port'] and s.web['port'] != 80:
                    url = url +':'+ s.web['port']

                buttonLabel = "View details"
                if event.object.type == ObjectType.PASSWORD:
                    recipients.add(User(event.object.id))
                    url = url+'/password/'+event.data['hashing']
                    subject, template = build_subject_and_template('password', event)
                    buttonLabel = "Change password"
                else:
                    if event.isPending():
                        # Find the authority of the event object
                        # Then according the authority, put the pi_emails in pis_email
                        try:
                            authority_id = event.data['authority']
                        except KeyError:
                            msg = 'Authority id not specified ({})'.format(event.id)
                            logger.error(msg)
                            event.logWarning('Authority not specified in event {}, email not sent'.format(event.id))
                            pass
                        else:
                            authority = Authority(db.get(dbconnection, table='authorities', id=authority_id))
                            if not authority:
                                # get admin users
                                users = db.get(dbconnection, table='users')
                                for u in users:
                                    user = User(u)
                                    if user.isAdmin():
                                        logger.debug("user %s is admin" % user.id)
                                        recipients.add(user)
                            else:
                                for pi_id in authority.pi_users:
                                    recipients.add(User(pi_id))

                            if not recipients:
                                msg = 'Emails cannot be sent because no one is the PI of {}'.format(event.object.id)
                                logger.error(msg)
                                event.logWarning('No recipients could be found for event {}, email not sent'.format(event.id))
                            
                            subject, template = build_subject_and_template('request', event)
                            buttonLabel = "Approve / Deny"
                            url = url + '/activity'
                    else:
                        if event.user:
                            recipients.add(User(event.user))
                        else:
                            # Look for the user email in the Event
                            if event.object.type == ObjectType.USER:
                                recipients.add(User({'email':event.data['email'], 'first_name':event.data['first_name'], 'last_name':event.data['last_name']}))
                            elif event.object.type == ObjectType.AUTHORITY:
                                for user in event.data['users']:
                                    recipients.add(User(user))
                            else:
                                for user in event.data['pi_users']:
                                    recipients.add(User(user))

                        if event.isSuccess():
                            subject, template = build_subject_and_template('approve', event)

                        elif event.isDenied():
                            subject, template = build_subject_and_template('deny', event)

                try:
                    sendEmail(event, recipients, subject, template, url, buttonLabel)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    msg = "Error in event {} while trying to send an email: {} {}".format(event.id, e, traceback.print_exc())
                    logger.error(msg)
                    event.logWarning(msg)
                    continue
                finally:
                    dispatch(dbconnection, event)
Exemplo n.º 3
0
    def put(self, id):
        """
        PUT /requests/<id>
        { action: <approve|deny|message>, message: <string> }
        :return:
        """
        current_user = self.get_current_user()
        if not current_user:
            self.userError("not authenticated")
            return

        user = User(current_user)

        if id is None:
            self.userError("wrong ID missing")

        try:
            action = escape.json_decode(self.request.body)['action']
        except json.decoder.JSONDecodeError as e:
            self.userError("malformed request", e.message)
            return

        try:
            if 'message' in escape.json_decode(self.request.body):
                message = escape.json_decode(self.request.body)['message']
            else:
                message = None
        except json.decoder.JSONDecodeError as e:
            self.userError("malformed request", e.message)
            return

        if action != 'approve' and action != 'deny':
            self.userError("action must be approve or deny")
            return

        # retrieve the event from db, and see if it is in pending status
        ev = yield r.table('activity').get(id).run(self.dbconnection)
        if not ev:
            self.userError("request not found {}".format(id))
            return

        event = Event(ev)
        if not event.isPending():
            self.serverError("malformed request")
            return

        # TODO: if message, user that created Event can send a message 
        if not user.has_privilege(event):
            self.userError("Permission denied")
            return

        # Manager that approve / deny the Event
        # Used to save the object using manager's credentials
        event.setManager(user.id)

        if action == 'approve':
            event.setApproved()

        if action == 'deny':
            event.setDenied()

        event.notify = True

        if message:
            event.message(user.id, message)

        yield dispatch(self.dbconnection, event)

        requests = []
        # Get the updated event after dispatch
        ev = yield r.table('activity').get(id).run(self.dbconnection)
        requests.append(ev)        

        self.finish(json.dumps({"result": requests}, cls=myJSONEncoder))