We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Login attempt on roundcube triggers error 500 on /sso/login endpoint (ZeroDivisionError: division by zero)
Hi everybody!

Thanks in advance for your help!

## Before you open your issue
- [x] Check if no issue or pull-request for this already exists.
- [x] Check [documentation](https://mailu.io/master/) and [FAQ](https://mailu.io/master/faq.html). (Tip, use the search function on the documentation page)
- [x] You understand `Mailu` is made by volunteers in their **free time** — be conscise, civil and accept that delays can occur.
- [x] The title of the issue should be short and simple. It should contain specific terms related to the actual issue. Be specific while writing the title.

## Environment & Versions
### Environment
 - [x] docker-compose
 - [ ] kubernetes
 - [ ] docker swarm

### Versions
1.9

## Description
A user encountered an error 500 while trying to log into an account on roundcube. The 500 comes from a ZeroDivisionError in one of the jinja templates (see logs below).

## Replication Steps
Unfortunately I could not reproduce it so far. Apparently it happened on the first login attempt, even though I suspect that it had to do with rate limiting, since there was a message about rate limiting right before the error (see below). Apparently the number of fields on the sso form is zero?

The user also reports, that it is now working (also when rapidly logging out and logging in again).

## Expected behaviour
No error 500 and succesful login.

## Logs

````markdown
```
admin_1     | [2022-01-10 14:59:49,322] WARNING in limiter: Authentication attempt from <REDACTED IP OF USER> for <REDACTED MAIL ACCOUNT> has been rate-limited.
admin_1     | [2022-01-10 14:59:49,334] ERROR in app: Exception on /sso/login [POST]
admin_1     | Traceback (most recent call last):
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
admin_1     |     response = self.full_dispatch_request()
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
admin_1     |     rv = self.handle_user_exception(e)
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
admin_1     |     rv = self.dispatch_request()
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
admin_1     |     return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
admin_1     |   File "/app/mailu/sso/views/base.py", line 36, in login
admin_1     |     return flask.render_template('login.html', form=form)
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/templating.py", line 147, in render_template
admin_1     |     return _render(
admin_1     |   File "/usr/lib/python3.9/site-packages/flask/templating.py", line 128, in _render
admin_1     |     rv = template.render(context)
admin_1     |   File "/usr/lib/python3.9/site-packages/jinja2/environment.py", line 1304, in render
admin_1     |     self.environment.handle_exception()
admin_1     |   File "/usr/lib/python3.9/site-packages/jinja2/environment.py", line 925, in handle_exception
admin_1     |     raise rewrite_traceback_stack(source=source)
admin_1     |   File "/app/mailu/sso/templates/login.html", line 1, in top-level template code
admin_1     |     {%- extends "form_sso.html" %}
admin_1     |   File "/app/mailu/sso/templates/form_sso.html", line 1, in top-level template code
admin_1     |     {%- extends "base_sso.html" %}
admin_1     |   File "/app/mailu/sso/templates/base_sso.html", line 70, in top-level template code
admin_1     |     {%- block content %}{%- endblock %}
admin_1     |   File "/app/mailu/sso/templates/form_sso.html", line 4, in block 'content'
admin_1     |     {%- call macros.card() %}
admin_1     |   File "/usr/lib/python3.9/site-packages/jinja2/runtime.py", line 828, in _invoke
admin_1     |     rv = self._func(*arguments)
admin_1     |   File "/app/mailu/ui/templates/macros.html", line 84, in template
admin_1     |     {{- caller() }}
admin_1     |   File "/usr/lib/python3.9/site-packages/jinja2/runtime.py", line 828, in _invoke
admin_1     |     rv = self._func(*arguments)
admin_1     |   File "/app/mailu/sso/templates/form_sso.html", line 8, in template
admin_1     |     {{ macros.form_fields(fields, label=False, class="btn btn-default") }}
admin_1     |   File "/usr/lib/python3.9/site-packages/jinja2/runtime.py", line 828, in _invoke
admin_1     |     rv = self._func(*arguments)
admin_1     |   File "/app/mailu/ui/templates/macros.html", line 22, in template
admin_1     |     {%- set width = (12 / fields|length)|int %}
admin_1     | ZeroDivisionError: division by zero

```
````


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `core/admin/mailu/sso/views/base.py`
Content:
```
1 from werkzeug.utils import redirect
2 from mailu import models, utils
3 from mailu.sso import sso, forms
4 from mailu.ui import access
5 
6 from flask import current_app as app
7 import flask
8 import flask_login
9 
10 @sso.route('/login', methods=['GET', 'POST'])
11 def login():
12     client_ip = flask.request.headers.get('X-Real-IP', flask.request.remote_addr)
13     form = forms.LoginForm()
14     form.submitAdmin.label.text = form.submitAdmin.label.text + ' Admin'
15     form.submitWebmail.label.text = form.submitWebmail.label.text + ' Webmail'
16 
17     fields = []
18     if str(app.config["WEBMAIL"]).upper() != "NONE":
19         fields.append(form.submitWebmail)
20     if str(app.config["ADMIN"]).upper() != "FALSE":
21         fields.append(form.submitAdmin)
22     fields = [fields]
23 
24     if form.validate_on_submit():
25         if form.submitAdmin.data:
26             destination = app.config['WEB_ADMIN']
27         elif form.submitWebmail.data:
28             destination = app.config['WEB_WEBMAIL']
29         device_cookie, device_cookie_username = utils.limiter.parse_device_cookie(flask.request.cookies.get('rate_limit'))
30         username = form.email.data
31         if username != device_cookie_username and utils.limiter.should_rate_limit_ip(client_ip):
32             flask.flash('Too many attempts from your IP (rate-limit)', 'error')
33             return flask.render_template('login.html', form=form)
34         if utils.limiter.should_rate_limit_user(username, client_ip, device_cookie, device_cookie_username):
35             flask.flash('Too many attempts for this user (rate-limit)', 'error')
36             return flask.render_template('login.html', form=form)
37         user = models.User.login(username, form.pw.data)
38         if user:
39             flask.session.regenerate()
40             flask_login.login_user(user)
41             response = flask.redirect(destination)
42             response.set_cookie('rate_limit', utils.limiter.device_cookie(username), max_age=31536000, path=flask.url_for('sso.login'), secure=app.config['SESSION_COOKIE_SECURE'], httponly=True)
43             flask.current_app.logger.info(f'Login succeeded for {username} from {client_ip}.')
44             return response
45         else:
46             utils.limiter.rate_limit_user(username, client_ip, device_cookie, device_cookie_username) if models.User.get(username) else utils.limiter.rate_limit_ip(client_ip)
47             flask.current_app.logger.warn(f'Login failed for {username} from {client_ip}.')
48             flask.flash('Wrong e-mail or password', 'error')
49     return flask.render_template('login.html', form=form, fields=fields)
50 
51 @sso.route('/logout', methods=['GET'])
52 @access.authenticated
53 def logout():
54     flask_login.logout_user()
55     flask.session.destroy()
56     return flask.redirect(flask.url_for('.login'))
57 
58
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/core/admin/mailu/sso/views/base.py b/core/admin/mailu/sso/views/base.py
--- a/core/admin/mailu/sso/views/base.py
+++ b/core/admin/mailu/sso/views/base.py
@@ -30,10 +30,10 @@
         username = form.email.data
         if username != device_cookie_username and utils.limiter.should_rate_limit_ip(client_ip):
             flask.flash('Too many attempts from your IP (rate-limit)', 'error')
-            return flask.render_template('login.html', form=form)
+            return flask.render_template('login.html', form=form, fields=fields)
         if utils.limiter.should_rate_limit_user(username, client_ip, device_cookie, device_cookie_username):
             flask.flash('Too many attempts for this user (rate-limit)', 'error')
-            return flask.render_template('login.html', form=form)
+            return flask.render_template('login.html', form=form, fields=fields)
         user = models.User.login(username, form.pw.data)
         if user:
             flask.session.regenerate()

{"golden_diff": "diff --git a/core/admin/mailu/sso/views/base.py b/core/admin/mailu/sso/views/base.py\n--- a/core/admin/mailu/sso/views/base.py\n+++ b/core/admin/mailu/sso/views/base.py\n@@ -30,10 +30,10 @@\n         username = form.email.data\n         if username != device_cookie_username and utils.limiter.should_rate_limit_ip(client_ip):\n             flask.flash('Too many attempts from your IP (rate-limit)', 'error')\n-            return flask.render_template('login.html', form=form)\n+            return flask.render_template('login.html', form=form, fields=fields)\n         if utils.limiter.should_rate_limit_user(username, client_ip, device_cookie, device_cookie_username):\n             flask.flash('Too many attempts for this user (rate-limit)', 'error')\n-            return flask.render_template('login.html', form=form)\n+            return flask.render_template('login.html', form=form, fields=fields)\n         user = models.User.login(username, form.pw.data)\n         if user:\n             flask.session.regenerate()\n", "issue": "Login attempt on roundcube triggers error 500 on /sso/login endpoint (ZeroDivisionError: division by zero)\nHi everybody!\r\n\r\nThanks in advance for your help!\r\n\r\n## Before you open your issue\r\n- [x] Check if no issue or pull-request for this already exists.\r\n- [x] Check [documentation](https://mailu.io/master/) and [FAQ](https://mailu.io/master/faq.html). (Tip, use the search function on the documentation page)\r\n- [x] You understand `Mailu` is made by volunteers in their **free time** \u2014 be conscise, civil and accept that delays can occur.\r\n- [x] The title of the issue should be short and simple. It should contain specific terms related to the actual issue. Be specific while writing the title.\r\n\r\n## Environment & Versions\r\n### Environment\r\n - [x] docker-compose\r\n - [ ] kubernetes\r\n - [ ] docker swarm\r\n\r\n### Versions\r\n1.9\r\n\r\n## Description\r\nA user encountered an error 500 while trying to log into an account on roundcube. The 500 comes from a ZeroDivisionError in one of the jinja templates (see logs below).\r\n\r\n## Replication Steps\r\nUnfortunately I could not reproduce it so far. Apparently it happened on the first login attempt, even though I suspect that it had to do with rate limiting, since there was a message about rate limiting right before the error (see below). Apparently the number of fields on the sso form is zero?\r\n\r\nThe user also reports, that it is now working (also when rapidly logging out and logging in again).\r\n\r\n## Expected behaviour\r\nNo error 500 and succesful login.\r\n\r\n## Logs\r\n\r\n````markdown\r\n```\r\nadmin_1     | [2022-01-10 14:59:49,322] WARNING in limiter: Authentication attempt from <REDACTED IP OF USER> for <REDACTED MAIL ACCOUNT> has been rate-limited.\r\nadmin_1     | [2022-01-10 14:59:49,334] ERROR in app: Exception on /sso/login [POST]\r\nadmin_1     | Traceback (most recent call last):\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/app.py\", line 2073, in wsgi_app\r\nadmin_1     |     response = self.full_dispatch_request()\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/app.py\", line 1518, in full_dispatch_request\r\nadmin_1     |     rv = self.handle_user_exception(e)\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/app.py\", line 1516, in full_dispatch_request\r\nadmin_1     |     rv = self.dispatch_request()\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/app.py\", line 1502, in dispatch_request\r\nadmin_1     |     return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\r\nadmin_1     |   File \"/app/mailu/sso/views/base.py\", line 36, in login\r\nadmin_1     |     return flask.render_template('login.html', form=form)\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/templating.py\", line 147, in render_template\r\nadmin_1     |     return _render(\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/flask/templating.py\", line 128, in _render\r\nadmin_1     |     rv = template.render(context)\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/jinja2/environment.py\", line 1304, in render\r\nadmin_1     |     self.environment.handle_exception()\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/jinja2/environment.py\", line 925, in handle_exception\r\nadmin_1     |     raise rewrite_traceback_stack(source=source)\r\nadmin_1     |   File \"/app/mailu/sso/templates/login.html\", line 1, in top-level template code\r\nadmin_1     |     {%- extends \"form_sso.html\" %}\r\nadmin_1     |   File \"/app/mailu/sso/templates/form_sso.html\", line 1, in top-level template code\r\nadmin_1     |     {%- extends \"base_sso.html\" %}\r\nadmin_1     |   File \"/app/mailu/sso/templates/base_sso.html\", line 70, in top-level template code\r\nadmin_1     |     {%- block content %}{%- endblock %}\r\nadmin_1     |   File \"/app/mailu/sso/templates/form_sso.html\", line 4, in block 'content'\r\nadmin_1     |     {%- call macros.card() %}\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/jinja2/runtime.py\", line 828, in _invoke\r\nadmin_1     |     rv = self._func(*arguments)\r\nadmin_1     |   File \"/app/mailu/ui/templates/macros.html\", line 84, in template\r\nadmin_1     |     {{- caller() }}\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/jinja2/runtime.py\", line 828, in _invoke\r\nadmin_1     |     rv = self._func(*arguments)\r\nadmin_1     |   File \"/app/mailu/sso/templates/form_sso.html\", line 8, in template\r\nadmin_1     |     {{ macros.form_fields(fields, label=False, class=\"btn btn-default\") }}\r\nadmin_1     |   File \"/usr/lib/python3.9/site-packages/jinja2/runtime.py\", line 828, in _invoke\r\nadmin_1     |     rv = self._func(*arguments)\r\nadmin_1     |   File \"/app/mailu/ui/templates/macros.html\", line 22, in template\r\nadmin_1     |     {%- set width = (12 / fields|length)|int %}\r\nadmin_1     | ZeroDivisionError: division by zero\r\n\r\n```\r\n````\r\n\n", "before_files": [{"content": "from werkzeug.utils import redirect\nfrom mailu import models, utils\nfrom mailu.sso import sso, forms\nfrom mailu.ui import access\n\nfrom flask import current_app as app\nimport flask\nimport flask_login\n\n@sso.route('/login', methods=['GET', 'POST'])\ndef login():\n    client_ip = flask.request.headers.get('X-Real-IP', flask.request.remote_addr)\n    form = forms.LoginForm()\n    form.submitAdmin.label.text = form.submitAdmin.label.text + ' Admin'\n    form.submitWebmail.label.text = form.submitWebmail.label.text + ' Webmail'\n\n    fields = []\n    if str(app.config[\"WEBMAIL\"]).upper() != \"NONE\":\n        fields.append(form.submitWebmail)\n    if str(app.config[\"ADMIN\"]).upper() != \"FALSE\":\n        fields.append(form.submitAdmin)\n    fields = [fields]\n\n    if form.validate_on_submit():\n        if form.submitAdmin.data:\n            destination = app.config['WEB_ADMIN']\n        elif form.submitWebmail.data:\n            destination = app.config['WEB_WEBMAIL']\n        device_cookie, device_cookie_username = utils.limiter.parse_device_cookie(flask.request.cookies.get('rate_limit'))\n        username = form.email.data\n        if username != device_cookie_username and utils.limiter.should_rate_limit_ip(client_ip):\n            flask.flash('Too many attempts from your IP (rate-limit)', 'error')\n            return flask.render_template('login.html', form=form)\n        if utils.limiter.should_rate_limit_user(username, client_ip, device_cookie, device_cookie_username):\n            flask.flash('Too many attempts for this user (rate-limit)', 'error')\n            return flask.render_template('login.html', form=form)\n        user = models.User.login(username, form.pw.data)\n        if user:\n            flask.session.regenerate()\n            flask_login.login_user(user)\n            response = flask.redirect(destination)\n            response.set_cookie('rate_limit', utils.limiter.device_cookie(username), max_age=31536000, path=flask.url_for('sso.login'), secure=app.config['SESSION_COOKIE_SECURE'], httponly=True)\n            flask.current_app.logger.info(f'Login succeeded for {username} from {client_ip}.')\n            return response\n        else:\n            utils.limiter.rate_limit_user(username, client_ip, device_cookie, device_cookie_username) if models.User.get(username) else utils.limiter.rate_limit_ip(client_ip)\n            flask.current_app.logger.warn(f'Login failed for {username} from {client_ip}.')\n            flask.flash('Wrong e-mail or password', 'error')\n    return flask.render_template('login.html', form=form, fields=fields)\n\n@sso.route('/logout', methods=['GET'])\n@access.authenticated\ndef logout():\n    flask_login.logout_user()\n    flask.session.destroy()\n    return flask.redirect(flask.url_for('.login'))\n\n", "path": "core/admin/mailu/sso/views/base.py"}], "after_files": [{"content": "from werkzeug.utils import redirect\nfrom mailu import models, utils\nfrom mailu.sso import sso, forms\nfrom mailu.ui import access\n\nfrom flask import current_app as app\nimport flask\nimport flask_login\n\n@sso.route('/login', methods=['GET', 'POST'])\ndef login():\n    client_ip = flask.request.headers.get('X-Real-IP', flask.request.remote_addr)\n    form = forms.LoginForm()\n    form.submitAdmin.label.text = form.submitAdmin.label.text + ' Admin'\n    form.submitWebmail.label.text = form.submitWebmail.label.text + ' Webmail'\n\n    fields = []\n    if str(app.config[\"WEBMAIL\"]).upper() != \"NONE\":\n        fields.append(form.submitWebmail)\n    if str(app.config[\"ADMIN\"]).upper() != \"FALSE\":\n        fields.append(form.submitAdmin)\n    fields = [fields]\n\n    if form.validate_on_submit():\n        if form.submitAdmin.data:\n            destination = app.config['WEB_ADMIN']\n        elif form.submitWebmail.data:\n            destination = app.config['WEB_WEBMAIL']\n        device_cookie, device_cookie_username = utils.limiter.parse_device_cookie(flask.request.cookies.get('rate_limit'))\n        username = form.email.data\n        if username != device_cookie_username and utils.limiter.should_rate_limit_ip(client_ip):\n            flask.flash('Too many attempts from your IP (rate-limit)', 'error')\n            return flask.render_template('login.html', form=form, fields=fields)\n        if utils.limiter.should_rate_limit_user(username, client_ip, device_cookie, device_cookie_username):\n            flask.flash('Too many attempts for this user (rate-limit)', 'error')\n            return flask.render_template('login.html', form=form, fields=fields)\n        user = models.User.login(username, form.pw.data)\n        if user:\n            flask.session.regenerate()\n            flask_login.login_user(user)\n            response = flask.redirect(destination)\n            response.set_cookie('rate_limit', utils.limiter.device_cookie(username), max_age=31536000, path=flask.url_for('sso.login'), secure=app.config['SESSION_COOKIE_SECURE'], httponly=True)\n            flask.current_app.logger.info(f'Login succeeded for {username} from {client_ip}.')\n            return response\n        else:\n            utils.limiter.rate_limit_user(username, client_ip, device_cookie, device_cookie_username) if models.User.get(username) else utils.limiter.rate_limit_ip(client_ip)\n            flask.current_app.logger.warn(f'Login failed for {username} from {client_ip}.')\n            flask.flash('Wrong e-mail or password', 'error')\n    return flask.render_template('login.html', form=form, fields=fields)\n\n@sso.route('/logout', methods=['GET'])\n@access.authenticated\ndef logout():\n    flask_login.logout_user()\n    flask.session.destroy()\n    return flask.redirect(flask.url_for('.login'))\n\n", "path": "core/admin/mailu/sso/views/base.py"}]}