Repository: ckan/ckan

Issue:
Error emails are not sent in flask routes
### CKAN Version if known (or site URL)
2.8, master

### Please describe the expected behaviour
When some route generates an error and error emails are configured, stacktrace and other info are expected to be mailed in specified email address.

### Please describe the actual behaviour
If the route is migrated to flask, the error email is never sent. Most likely due to the that mailing is based on pylons error middleware https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/modules/middleware.html#pylons.middleware.ErrorHandler


### What steps can be taken to reproduce the issue? 
Configure error emails.
Insert syntax error to route migrated to flask. For example view/user.py.
Error page is generated, email is not sent.

Add simple email error logger to flask
Fixes #4611

### Proposed fixes:
Adds simple email error logger to flask app. Uses the same config parameters as pylons did so no extra configuration is required.

In case of error, the email will contain the following example:


Time:               2019-01-17 13:06:18,548
URL:                /user/admin
Method:             GET
Headers:            Cookie: Drupal.toolbar.collapsed=0; SSESS6b28b91ad717e967d3986b15c6c3ee12=ceSUx4deo_M3r5tAKe3wBmixI452mrREzjq-64VWu2I; ckan=d75907f3c439157af44e103541f8dfdee32519a494aa1e2d1a514a2e85f00abf48160a98
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Connection: close
Host: 10.10.10.10
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
X-Url-Scheme: https
Accept-Language: fi-FI,fi;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6
Accept-Encoding: gzip, deflate, br



Traceback (most recent call last):
  File "/usr/lib/ckan/default/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/lib/ckan/default/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/lib/ckan/default/src/ckan/ckan/views/user.py", line 131, in read
    asd
NameError: global name 'asd' is not defined


### Features:

- [ ] includes tests covering changes
- [ ] includes updated documentation
- [ ] includes user-visible changes
- [ ] includes API changes
- [x] includes bugfix for possible backport

Please [X] all the boxes above that apply



Discussion:
Yes, this was an internal Pylons feature so we lost it during the migration. It seems pretty easy to add an [email log handler](http://flask.pocoo.org/docs/1.0/logging/#email-errors-to-admins) that would replace this functionality. And perhaps there is an already existing Flask plugin that wraps this.

Marking as Good for Contribution in case @Zharktas or someone else wants to work on it.
:+1: Tested and merged

Resolving patch:
diff --git a/ckan/config/middleware/flask_app.py b/ckan/config/middleware/flask_app.py
--- a/ckan/config/middleware/flask_app.py
+++ b/ckan/config/middleware/flask_app.py
@@ -474,11 +474,17 @@ def filter(self, log_record):
             return True
 
     mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
+    credentials = None
+    if config.get('smtp.user'):
+        credentials = (config.get('smtp.user'), config.get('smtp.password'))
+    secure = () if asbool(config.get('smtp.starttls')) else None
     mail_handler = SMTPHandler(
         mailhost=mailhost,
         fromaddr=config.get('error_email_from'),
         toaddrs=[config.get('email_to')],
-        subject='Application Error'
+        subject='Application Error',
+        credentials=credentials,
+        secure=secure
     )
 
     mail_handler.setFormatter(logging.Formatter('''


Test patch: