We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Internal server error when clicking any tags in the home page
Internal server error on clicking the tags (like #Conference #ScienceAnTechnology ) in the home page under each event.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `app/helpers/flask_helpers.py`
Content:
```
1 import re
2 from urllib2 import urlopen
3 
4 from flask import request
5 from flask.json import JSONEncoder
6 from jinja2 import Undefined
7 from slugify import SLUG_OK
8 from slugify import slugify as unicode_slugify
9 
10 
11 def get_real_ip(local_correct=False):
12     try:
13         if 'X-Forwarded-For' in request.headers:
14             ip = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
15         else:
16             ip = request.remote_addr or None
17 
18         if local_correct and (ip == '127.0.0.1' or ip == '0.0.0.0'):
19             ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments
20     except:
21         ip = None
22 
23     return ip
24 
25 
26 class MiniJSONEncoder(JSONEncoder):
27     """Minify JSON output."""
28     item_separator = ','
29     key_separator = ':'
30 
31 
32 class SilentUndefined(Undefined):
33     """
34     From http://stackoverflow.com/questions/6190348/
35     Don't break page loads because vars aren't there!
36     """
37 
38     def _fail_with_undefined_error(self, *args, **kwargs):
39         return False
40 
41     __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
42         __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
43         __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
44         __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
45         __float__ = __complex__ = __pow__ = __rpow__ = \
46         _fail_with_undefined_error
47 
48 
49 def slugify(text):
50     """Generates an ASCII-only slug."""
51     return unicode(unicode_slugify(text, ok=SLUG_OK + ',').replace(',', '--'))
52 
53 
54 def deslugify(text):
55     return text.replace('--', ',').replace('-', " ")
56 
57 
58 def camel_case(text):
59     text = deslugify(slugify(text))
60     return ''.join(x for x in text.title() if not x.isspace())
61
```

Path: `app/views/home.py`
Content:
```
1 import logging
2 import os
3 import random
4 import string
5 import urllib
6 from urllib2 import urlopen
7 
8 import geoip2.database
9 from flask import Blueprint
10 from flask import abort, render_template
11 from flask import url_for, redirect, request, session, flash
12 from flask.ext import login
13 from flask.ext.login import login_required
14 from flask.ext.scrypt import generate_password_hash
15 
16 from app.helpers.data import DataManager, save_to_db, get_google_auth, get_facebook_auth, create_user_password, \
17     user_logged_in, record_activity
18 from app.helpers.data_getter import DataGetter
19 from app.helpers.flask_helpers import get_real_ip, slugify
20 from app.helpers.helpers import send_email_with_reset_password_hash, send_email_confirmation, \
21     get_serializer, get_request_stats
22 from app.helpers.oauth import OAuth, FbOAuth
23 from app.models.user import User
24 from app.views.public.explore import erase_from_dict
25 
26 
27 def intended_url():
28     return request.args.get('next') or url_for('.index')
29 
30 
31 def record_user_login_logout(template, user):
32     req_stats = get_request_stats()
33     record_activity(
34         template,
35         user=user,
36         **req_stats
37     )
38 
39 
40 def str_generator(size=6, chars=string.ascii_uppercase + string.digits):
41     return ''.join(random.choice(chars) for _ in range(size))
42 
43 
44 home_routes = Blueprint('admin', __name__)
45 
46 
47 @home_routes.route('/')
48 def index():
49     call_for_speakers_events = DataGetter.get_call_for_speakers_events()
50     upcoming_events = DataGetter.get_all_published_events().limit(12).all()
51     placeholder_images = DataGetter.get_event_default_images()
52     custom_placeholder = DataGetter.get_custom_placeholders()
53     im_config = DataGetter.get_image_configs()
54     im_size = ''
55     for config in im_config:
56         if config.page == 'front':
57             im_size = config.size
58     return render_template('gentelella/index.html',
59                            call_for_speakers_events=call_for_speakers_events,
60                            upcoming_events=upcoming_events,
61                            placeholder_images=placeholder_images,
62                            custom_placeholder=custom_placeholder,
63                            im_size=im_size)
64 
65 
66 @home_routes.route('/login/', methods=('GET', 'POST'))
67 def login_view():
68     if login.current_user.is_authenticated:
69         return redirect(url_for('.index'))
70 
71     if request.method == 'GET':
72         google = get_google_auth()
73         auth_url, state = google.authorization_url(OAuth.get_auth_uri(), access_type='offline')
74         session['oauth_state'] = state
75 
76         # Add Facebook Oauth 2.0 login
77         facebook = get_facebook_auth()
78         fb_auth_url, state = facebook.authorization_url(FbOAuth.get_auth_uri(), access_type='offline')
79         session['fb_oauth_state'] = state
80         return render_template('gentelella/admin/login/login.html', auth_url=auth_url, fb_auth_url=fb_auth_url)
81     if request.method == 'POST':
82         email = request.form['email']
83         user = DataGetter.get_user_by_email(email)
84         if user is None:
85             logging.info('No such user')
86             return redirect(url_for('admin.login_view'))
87         if user.password != generate_password_hash(request.form['password'], user.salt):
88             logging.info('Password Incorrect')
89             flash('Incorrect Password', 'danger')
90             return redirect(url_for('admin.login_view'))
91         login.login_user(user)
92         record_user_login_logout('user_login', user)
93 
94         # Store user_id in session for socketio use
95         session['user_id'] = login.current_user.id
96 
97         logging.info('logged successfully')
98         user_logged_in(user)
99         return redirect(intended_url())
100 
101 
102 @home_routes.route('/register/', methods=('GET', 'POST'))
103 def register_view():
104     if request.method == 'GET':
105         return render_template('gentelella/admin/login/register.html')
106     if request.method == 'POST':
107         logging.info("Registration under process")
108         s = get_serializer()
109         data = [request.form['email'], request.form['password']]
110         user = DataManager.create_user(data)
111         form_hash = s.dumps([request.form['email'], str_generator()])
112         link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)
113         send_email_confirmation(request.form, link)
114         login.login_user(user)
115         record_user_login_logout('user_login', user)
116         logging.info('logged successfully')
117         user_logged_in(user)
118         return redirect(intended_url())
119 
120 
121 @home_routes.route('/resend/', methods=('GET',))
122 @login_required
123 def resend_email_confirmation():
124     user = login.current_user
125     if not user.is_verified:
126         s = get_serializer()
127         email = user.email
128         form_hash = s.dumps([email, str_generator()])
129         link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)
130         data = {
131             "email": email
132         }
133         send_email_confirmation(data, link)
134         flash('Confirmation email has been sent again.', 'info')
135     else:
136         flash('Your email has already been confirmed.', 'info')
137     return redirect(url_for('events.index_view'))
138 
139 
140 @home_routes.route('/account/create/<hash>', methods=('GET',))
141 def create_account_after_confirmation_view(hash):
142     s = get_serializer()
143     data = s.loads(hash)
144     user = User.query.filter_by(email=data[0]).first()
145     user.is_verified = True
146     save_to_db(user, 'User updated')
147     login.login_user(user)
148     record_user_login_logout('user_login', user)
149     user_logged_in(user)
150     flash('Thank you. Your new email is now confirmed', 'success')
151     return redirect(url_for('settings.contact_info_view'))
152 
153 
154 @home_routes.route('/password/new/<email>', methods=('GET', 'POST'))
155 def create_password_after_oauth_login(email):
156     s = get_serializer()
157     email = s.loads(email)
158     user = DataGetter.get_user_by_email(email)
159     if request.method == 'GET':
160         return render_template('gentelella/admin/login/create_password.html')
161     if request.method == 'POST':
162         user = create_user_password(request.form, user)
163         if user is not None:
164             login.login_user(user)
165             record_user_login_logout('user_login', user)
166             user_logged_in(user)
167             return redirect(intended_url())
168 
169 
170 @home_routes.route('/password/reset', methods=('GET', 'POST'))
171 def password_reset_view():
172     """Password reset view"""
173     if request.method == 'GET':
174         return render_template('gentelella/admin/login/password_reminder.html')
175     if request.method == 'POST':
176         email = request.form['email']
177         user = DataGetter.get_user_by_email(email)
178         if user:
179             link = request.host + url_for(".change_password_view", hash=user.reset_password)
180             return link
181             send_email_with_reset_password_hash(email, link)
182             flash('Please go to the link sent to your email to reset your password')
183         return redirect(url_for('.login_view'))
184 
185 
186 @home_routes.route('/reset_password/<hash>', methods=('GET', 'POST'))
187 def change_password_view(hash):
188     """Change password view"""
189     if request.method == 'GET':
190         return render_template('gentelella/admin/login/change_password.html')
191     if request.method == 'POST':
192         DataManager.reset_password(request.form, hash)
193         return redirect(url_for('.index'))
194 
195 
196 @home_routes.route('/logout/')
197 @login_required
198 def logout_view():
199     """Logout method which redirect to index"""
200     record_user_login_logout('user_logout', login.current_user)
201     login.logout_user()
202     return redirect(url_for('.index'))
203 
204 
205 @home_routes.route('/set_role', methods=('GET', 'POST'))
206 @login_required
207 def set_role():
208     """Set user role method"""
209     id = request.args['id']
210     role = request.args['roles']
211     user = DataGetter.get_user(id)
212     user.role = role
213     save_to_db(user, "User Role updated")
214     return redirect(url_for('.roles_manager'))
215 
216 
217 @home_routes.route('/forbidden/', methods=('GET',))
218 def forbidden_view():
219     return render_template('gentelella/errors/403.html')
220 
221 
222 @home_routes.route('/browse/', methods=('GET',))
223 def browse_view():
224     params = request.args.items()
225     params = dict((k, v) for k, v in params if v)
226 
227     def test_and_remove(key):
228         if request.args.get(key):
229             if request.args.get(key).lower() == request.args.get("query").lower():
230                 erase_from_dict(params, 'query')
231 
232     if not request.args.get("location"):
233         try:
234             reader = geoip2.database.Reader(os.path.realpath('.') + '/static/data/GeoLite2-Country.mmdb')
235             ip = get_real_ip()
236             if ip == '127.0.0.1' or ip == '0.0.0.0':
237                 ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments
238             response = reader.country(ip)
239             country = response.country.name
240         except:
241             country = "United States"
242     else:
243         country = request.args.get("location")
244 
245     test_and_remove("location")
246     test_and_remove("category")
247     erase_from_dict(params, 'location')
248 
249     return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' +
250                     urllib.urlencode(params))
251 
252 
253 @home_routes.route('/check_email/', methods=('POST', 'GET'))
254 def check_duplicate_email():
255     if request.method == 'GET':
256         email = request.args['email']
257         user = DataGetter.get_user_by_email(email, no_flash=True)
258         if user is None:
259             return '200 OK'
260         else:
261             return abort(404)
262 
263 
264 @home_routes.route('/resend_email/')
265 def resend_email_confirmation_old():
266     return resend_email_confirmation()
267
```
--- 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/app/helpers/flask_helpers.py b/app/helpers/flask_helpers.py
--- a/app/helpers/flask_helpers.py
+++ b/app/helpers/flask_helpers.py
@@ -56,5 +56,5 @@
 
 
 def camel_case(text):
-    text = deslugify(slugify(text))
+    text = slugify(text).replace('-', " ")
     return ''.join(x for x in text.title() if not x.isspace())
diff --git a/app/views/home.py b/app/views/home.py
--- a/app/views/home.py
+++ b/app/views/home.py
@@ -225,7 +225,7 @@
     params = dict((k, v) for k, v in params if v)
 
     def test_and_remove(key):
-        if request.args.get(key):
+        if request.args.get(key) and request.args.get("query"):
             if request.args.get(key).lower() == request.args.get("query").lower():
                 erase_from_dict(params, 'query')
 
@@ -246,8 +246,7 @@
     test_and_remove("category")
     erase_from_dict(params, 'location')
 
-    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' +
-                    urllib.urlencode(params))
+    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' + urllib.urlencode(params))
 
 
 @home_routes.route('/check_email/', methods=('POST', 'GET'))

{"golden_diff": "diff --git a/app/helpers/flask_helpers.py b/app/helpers/flask_helpers.py\n--- a/app/helpers/flask_helpers.py\n+++ b/app/helpers/flask_helpers.py\n@@ -56,5 +56,5 @@\n \n \n def camel_case(text):\n-    text = deslugify(slugify(text))\n+    text = slugify(text).replace('-', \" \")\n     return ''.join(x for x in text.title() if not x.isspace())\ndiff --git a/app/views/home.py b/app/views/home.py\n--- a/app/views/home.py\n+++ b/app/views/home.py\n@@ -225,7 +225,7 @@\n     params = dict((k, v) for k, v in params if v)\n \n     def test_and_remove(key):\n-        if request.args.get(key):\n+        if request.args.get(key) and request.args.get(\"query\"):\n             if request.args.get(key).lower() == request.args.get(\"query\").lower():\n                 erase_from_dict(params, 'query')\n \n@@ -246,8 +246,7 @@\n     test_and_remove(\"category\")\n     erase_from_dict(params, 'location')\n \n-    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' +\n-                    urllib.urlencode(params))\n+    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' + urllib.urlencode(params))\n \n \n @home_routes.route('/check_email/', methods=('POST', 'GET'))\n", "issue": "Internal server error when clicking any tags in the home page\nInternal server error on clicking the tags (like #Conference #ScienceAnTechnology ) in the home page under each event.\n", "before_files": [{"content": "import re\nfrom urllib2 import urlopen\n\nfrom flask import request\nfrom flask.json import JSONEncoder\nfrom jinja2 import Undefined\nfrom slugify import SLUG_OK\nfrom slugify import slugify as unicode_slugify\n\n\ndef get_real_ip(local_correct=False):\n    try:\n        if 'X-Forwarded-For' in request.headers:\n            ip = request.headers.getlist(\"X-Forwarded-For\")[0].rpartition(' ')[-1]\n        else:\n            ip = request.remote_addr or None\n\n        if local_correct and (ip == '127.0.0.1' or ip == '0.0.0.0'):\n            ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments\n    except:\n        ip = None\n\n    return ip\n\n\nclass MiniJSONEncoder(JSONEncoder):\n    \"\"\"Minify JSON output.\"\"\"\n    item_separator = ','\n    key_separator = ':'\n\n\nclass SilentUndefined(Undefined):\n    \"\"\"\n    From http://stackoverflow.com/questions/6190348/\n    Don't break page loads because vars aren't there!\n    \"\"\"\n\n    def _fail_with_undefined_error(self, *args, **kwargs):\n        return False\n\n    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \\\n        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \\\n        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \\\n        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \\\n        __float__ = __complex__ = __pow__ = __rpow__ = \\\n        _fail_with_undefined_error\n\n\ndef slugify(text):\n    \"\"\"Generates an ASCII-only slug.\"\"\"\n    return unicode(unicode_slugify(text, ok=SLUG_OK + ',').replace(',', '--'))\n\n\ndef deslugify(text):\n    return text.replace('--', ',').replace('-', \" \")\n\n\ndef camel_case(text):\n    text = deslugify(slugify(text))\n    return ''.join(x for x in text.title() if not x.isspace())\n", "path": "app/helpers/flask_helpers.py"}, {"content": "import logging\nimport os\nimport random\nimport string\nimport urllib\nfrom urllib2 import urlopen\n\nimport geoip2.database\nfrom flask import Blueprint\nfrom flask import abort, render_template\nfrom flask import url_for, redirect, request, session, flash\nfrom flask.ext import login\nfrom flask.ext.login import login_required\nfrom flask.ext.scrypt import generate_password_hash\n\nfrom app.helpers.data import DataManager, save_to_db, get_google_auth, get_facebook_auth, create_user_password, \\\n    user_logged_in, record_activity\nfrom app.helpers.data_getter import DataGetter\nfrom app.helpers.flask_helpers import get_real_ip, slugify\nfrom app.helpers.helpers import send_email_with_reset_password_hash, send_email_confirmation, \\\n    get_serializer, get_request_stats\nfrom app.helpers.oauth import OAuth, FbOAuth\nfrom app.models.user import User\nfrom app.views.public.explore import erase_from_dict\n\n\ndef intended_url():\n    return request.args.get('next') or url_for('.index')\n\n\ndef record_user_login_logout(template, user):\n    req_stats = get_request_stats()\n    record_activity(\n        template,\n        user=user,\n        **req_stats\n    )\n\n\ndef str_generator(size=6, chars=string.ascii_uppercase + string.digits):\n    return ''.join(random.choice(chars) for _ in range(size))\n\n\nhome_routes = Blueprint('admin', __name__)\n\n\n@home_routes.route('/')\ndef index():\n    call_for_speakers_events = DataGetter.get_call_for_speakers_events()\n    upcoming_events = DataGetter.get_all_published_events().limit(12).all()\n    placeholder_images = DataGetter.get_event_default_images()\n    custom_placeholder = DataGetter.get_custom_placeholders()\n    im_config = DataGetter.get_image_configs()\n    im_size = ''\n    for config in im_config:\n        if config.page == 'front':\n            im_size = config.size\n    return render_template('gentelella/index.html',\n                           call_for_speakers_events=call_for_speakers_events,\n                           upcoming_events=upcoming_events,\n                           placeholder_images=placeholder_images,\n                           custom_placeholder=custom_placeholder,\n                           im_size=im_size)\n\n\n@home_routes.route('/login/', methods=('GET', 'POST'))\ndef login_view():\n    if login.current_user.is_authenticated:\n        return redirect(url_for('.index'))\n\n    if request.method == 'GET':\n        google = get_google_auth()\n        auth_url, state = google.authorization_url(OAuth.get_auth_uri(), access_type='offline')\n        session['oauth_state'] = state\n\n        # Add Facebook Oauth 2.0 login\n        facebook = get_facebook_auth()\n        fb_auth_url, state = facebook.authorization_url(FbOAuth.get_auth_uri(), access_type='offline')\n        session['fb_oauth_state'] = state\n        return render_template('gentelella/admin/login/login.html', auth_url=auth_url, fb_auth_url=fb_auth_url)\n    if request.method == 'POST':\n        email = request.form['email']\n        user = DataGetter.get_user_by_email(email)\n        if user is None:\n            logging.info('No such user')\n            return redirect(url_for('admin.login_view'))\n        if user.password != generate_password_hash(request.form['password'], user.salt):\n            logging.info('Password Incorrect')\n            flash('Incorrect Password', 'danger')\n            return redirect(url_for('admin.login_view'))\n        login.login_user(user)\n        record_user_login_logout('user_login', user)\n\n        # Store user_id in session for socketio use\n        session['user_id'] = login.current_user.id\n\n        logging.info('logged successfully')\n        user_logged_in(user)\n        return redirect(intended_url())\n\n\n@home_routes.route('/register/', methods=('GET', 'POST'))\ndef register_view():\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/register.html')\n    if request.method == 'POST':\n        logging.info(\"Registration under process\")\n        s = get_serializer()\n        data = [request.form['email'], request.form['password']]\n        user = DataManager.create_user(data)\n        form_hash = s.dumps([request.form['email'], str_generator()])\n        link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)\n        send_email_confirmation(request.form, link)\n        login.login_user(user)\n        record_user_login_logout('user_login', user)\n        logging.info('logged successfully')\n        user_logged_in(user)\n        return redirect(intended_url())\n\n\n@home_routes.route('/resend/', methods=('GET',))\n@login_required\ndef resend_email_confirmation():\n    user = login.current_user\n    if not user.is_verified:\n        s = get_serializer()\n        email = user.email\n        form_hash = s.dumps([email, str_generator()])\n        link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)\n        data = {\n            \"email\": email\n        }\n        send_email_confirmation(data, link)\n        flash('Confirmation email has been sent again.', 'info')\n    else:\n        flash('Your email has already been confirmed.', 'info')\n    return redirect(url_for('events.index_view'))\n\n\n@home_routes.route('/account/create/<hash>', methods=('GET',))\ndef create_account_after_confirmation_view(hash):\n    s = get_serializer()\n    data = s.loads(hash)\n    user = User.query.filter_by(email=data[0]).first()\n    user.is_verified = True\n    save_to_db(user, 'User updated')\n    login.login_user(user)\n    record_user_login_logout('user_login', user)\n    user_logged_in(user)\n    flash('Thank you. Your new email is now confirmed', 'success')\n    return redirect(url_for('settings.contact_info_view'))\n\n\n@home_routes.route('/password/new/<email>', methods=('GET', 'POST'))\ndef create_password_after_oauth_login(email):\n    s = get_serializer()\n    email = s.loads(email)\n    user = DataGetter.get_user_by_email(email)\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/create_password.html')\n    if request.method == 'POST':\n        user = create_user_password(request.form, user)\n        if user is not None:\n            login.login_user(user)\n            record_user_login_logout('user_login', user)\n            user_logged_in(user)\n            return redirect(intended_url())\n\n\n@home_routes.route('/password/reset', methods=('GET', 'POST'))\ndef password_reset_view():\n    \"\"\"Password reset view\"\"\"\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/password_reminder.html')\n    if request.method == 'POST':\n        email = request.form['email']\n        user = DataGetter.get_user_by_email(email)\n        if user:\n            link = request.host + url_for(\".change_password_view\", hash=user.reset_password)\n            return link\n            send_email_with_reset_password_hash(email, link)\n            flash('Please go to the link sent to your email to reset your password')\n        return redirect(url_for('.login_view'))\n\n\n@home_routes.route('/reset_password/<hash>', methods=('GET', 'POST'))\ndef change_password_view(hash):\n    \"\"\"Change password view\"\"\"\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/change_password.html')\n    if request.method == 'POST':\n        DataManager.reset_password(request.form, hash)\n        return redirect(url_for('.index'))\n\n\n@home_routes.route('/logout/')\n@login_required\ndef logout_view():\n    \"\"\"Logout method which redirect to index\"\"\"\n    record_user_login_logout('user_logout', login.current_user)\n    login.logout_user()\n    return redirect(url_for('.index'))\n\n\n@home_routes.route('/set_role', methods=('GET', 'POST'))\n@login_required\ndef set_role():\n    \"\"\"Set user role method\"\"\"\n    id = request.args['id']\n    role = request.args['roles']\n    user = DataGetter.get_user(id)\n    user.role = role\n    save_to_db(user, \"User Role updated\")\n    return redirect(url_for('.roles_manager'))\n\n\n@home_routes.route('/forbidden/', methods=('GET',))\ndef forbidden_view():\n    return render_template('gentelella/errors/403.html')\n\n\n@home_routes.route('/browse/', methods=('GET',))\ndef browse_view():\n    params = request.args.items()\n    params = dict((k, v) for k, v in params if v)\n\n    def test_and_remove(key):\n        if request.args.get(key):\n            if request.args.get(key).lower() == request.args.get(\"query\").lower():\n                erase_from_dict(params, 'query')\n\n    if not request.args.get(\"location\"):\n        try:\n            reader = geoip2.database.Reader(os.path.realpath('.') + '/static/data/GeoLite2-Country.mmdb')\n            ip = get_real_ip()\n            if ip == '127.0.0.1' or ip == '0.0.0.0':\n                ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments\n            response = reader.country(ip)\n            country = response.country.name\n        except:\n            country = \"United States\"\n    else:\n        country = request.args.get(\"location\")\n\n    test_and_remove(\"location\")\n    test_and_remove(\"category\")\n    erase_from_dict(params, 'location')\n\n    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' +\n                    urllib.urlencode(params))\n\n\n@home_routes.route('/check_email/', methods=('POST', 'GET'))\ndef check_duplicate_email():\n    if request.method == 'GET':\n        email = request.args['email']\n        user = DataGetter.get_user_by_email(email, no_flash=True)\n        if user is None:\n            return '200 OK'\n        else:\n            return abort(404)\n\n\n@home_routes.route('/resend_email/')\ndef resend_email_confirmation_old():\n    return resend_email_confirmation()\n", "path": "app/views/home.py"}], "after_files": [{"content": "import re\nfrom urllib2 import urlopen\n\nfrom flask import request\nfrom flask.json import JSONEncoder\nfrom jinja2 import Undefined\nfrom slugify import SLUG_OK\nfrom slugify import slugify as unicode_slugify\n\n\ndef get_real_ip(local_correct=False):\n    try:\n        if 'X-Forwarded-For' in request.headers:\n            ip = request.headers.getlist(\"X-Forwarded-For\")[0].rpartition(' ')[-1]\n        else:\n            ip = request.remote_addr or None\n\n        if local_correct and (ip == '127.0.0.1' or ip == '0.0.0.0'):\n            ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments\n    except:\n        ip = None\n\n    return ip\n\n\nclass MiniJSONEncoder(JSONEncoder):\n    \"\"\"Minify JSON output.\"\"\"\n    item_separator = ','\n    key_separator = ':'\n\n\nclass SilentUndefined(Undefined):\n    \"\"\"\n    From http://stackoverflow.com/questions/6190348/\n    Don't break page loads because vars aren't there!\n    \"\"\"\n\n    def _fail_with_undefined_error(self, *args, **kwargs):\n        return False\n\n    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \\\n        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \\\n        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \\\n        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \\\n        __float__ = __complex__ = __pow__ = __rpow__ = \\\n        _fail_with_undefined_error\n\n\ndef slugify(text):\n    \"\"\"Generates an ASCII-only slug.\"\"\"\n    return unicode(unicode_slugify(text, ok=SLUG_OK + ',').replace(',', '--'))\n\n\ndef deslugify(text):\n    return text.replace('--', ',').replace('-', \" \")\n\n\ndef camel_case(text):\n    text = slugify(text).replace('-', \" \")\n    return ''.join(x for x in text.title() if not x.isspace())\n", "path": "app/helpers/flask_helpers.py"}, {"content": "import logging\nimport os\nimport random\nimport string\nimport urllib\nfrom urllib2 import urlopen\n\nimport geoip2.database\nfrom flask import Blueprint\nfrom flask import abort, render_template\nfrom flask import url_for, redirect, request, session, flash\nfrom flask.ext import login\nfrom flask.ext.login import login_required\nfrom flask.ext.scrypt import generate_password_hash\n\nfrom app.helpers.data import DataManager, save_to_db, get_google_auth, get_facebook_auth, create_user_password, \\\n    user_logged_in, record_activity\nfrom app.helpers.data_getter import DataGetter\nfrom app.helpers.flask_helpers import get_real_ip, slugify\nfrom app.helpers.helpers import send_email_with_reset_password_hash, send_email_confirmation, \\\n    get_serializer, get_request_stats\nfrom app.helpers.oauth import OAuth, FbOAuth\nfrom app.models.user import User\nfrom app.views.public.explore import erase_from_dict\n\n\ndef intended_url():\n    return request.args.get('next') or url_for('.index')\n\n\ndef record_user_login_logout(template, user):\n    req_stats = get_request_stats()\n    record_activity(\n        template,\n        user=user,\n        **req_stats\n    )\n\n\ndef str_generator(size=6, chars=string.ascii_uppercase + string.digits):\n    return ''.join(random.choice(chars) for _ in range(size))\n\n\nhome_routes = Blueprint('admin', __name__)\n\n\n@home_routes.route('/')\ndef index():\n    call_for_speakers_events = DataGetter.get_call_for_speakers_events()\n    upcoming_events = DataGetter.get_all_published_events().limit(12).all()\n    placeholder_images = DataGetter.get_event_default_images()\n    custom_placeholder = DataGetter.get_custom_placeholders()\n    im_config = DataGetter.get_image_configs()\n    im_size = ''\n    for config in im_config:\n        if config.page == 'front':\n            im_size = config.size\n    return render_template('gentelella/index.html',\n                           call_for_speakers_events=call_for_speakers_events,\n                           upcoming_events=upcoming_events,\n                           placeholder_images=placeholder_images,\n                           custom_placeholder=custom_placeholder,\n                           im_size=im_size)\n\n\n@home_routes.route('/login/', methods=('GET', 'POST'))\ndef login_view():\n    if login.current_user.is_authenticated:\n        return redirect(url_for('.index'))\n\n    if request.method == 'GET':\n        google = get_google_auth()\n        auth_url, state = google.authorization_url(OAuth.get_auth_uri(), access_type='offline')\n        session['oauth_state'] = state\n\n        # Add Facebook Oauth 2.0 login\n        facebook = get_facebook_auth()\n        fb_auth_url, state = facebook.authorization_url(FbOAuth.get_auth_uri(), access_type='offline')\n        session['fb_oauth_state'] = state\n        return render_template('gentelella/admin/login/login.html', auth_url=auth_url, fb_auth_url=fb_auth_url)\n    if request.method == 'POST':\n        email = request.form['email']\n        user = DataGetter.get_user_by_email(email)\n        if user is None:\n            logging.info('No such user')\n            return redirect(url_for('admin.login_view'))\n        if user.password != generate_password_hash(request.form['password'], user.salt):\n            logging.info('Password Incorrect')\n            flash('Incorrect Password', 'danger')\n            return redirect(url_for('admin.login_view'))\n        login.login_user(user)\n        record_user_login_logout('user_login', user)\n\n        # Store user_id in session for socketio use\n        session['user_id'] = login.current_user.id\n\n        logging.info('logged successfully')\n        user_logged_in(user)\n        return redirect(intended_url())\n\n\n@home_routes.route('/register/', methods=('GET', 'POST'))\ndef register_view():\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/register.html')\n    if request.method == 'POST':\n        logging.info(\"Registration under process\")\n        s = get_serializer()\n        data = [request.form['email'], request.form['password']]\n        user = DataManager.create_user(data)\n        form_hash = s.dumps([request.form['email'], str_generator()])\n        link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)\n        send_email_confirmation(request.form, link)\n        login.login_user(user)\n        record_user_login_logout('user_login', user)\n        logging.info('logged successfully')\n        user_logged_in(user)\n        return redirect(intended_url())\n\n\n@home_routes.route('/resend/', methods=('GET',))\n@login_required\ndef resend_email_confirmation():\n    user = login.current_user\n    if not user.is_verified:\n        s = get_serializer()\n        email = user.email\n        form_hash = s.dumps([email, str_generator()])\n        link = url_for('.create_account_after_confirmation_view', hash=form_hash, _external=True)\n        data = {\n            \"email\": email\n        }\n        send_email_confirmation(data, link)\n        flash('Confirmation email has been sent again.', 'info')\n    else:\n        flash('Your email has already been confirmed.', 'info')\n    return redirect(url_for('events.index_view'))\n\n\n@home_routes.route('/account/create/<hash>', methods=('GET',))\ndef create_account_after_confirmation_view(hash):\n    s = get_serializer()\n    data = s.loads(hash)\n    user = User.query.filter_by(email=data[0]).first()\n    user.is_verified = True\n    save_to_db(user, 'User updated')\n    login.login_user(user)\n    record_user_login_logout('user_login', user)\n    user_logged_in(user)\n    flash('Thank you. Your new email is now confirmed', 'success')\n    return redirect(url_for('settings.contact_info_view'))\n\n\n@home_routes.route('/password/new/<email>', methods=('GET', 'POST'))\ndef create_password_after_oauth_login(email):\n    s = get_serializer()\n    email = s.loads(email)\n    user = DataGetter.get_user_by_email(email)\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/create_password.html')\n    if request.method == 'POST':\n        user = create_user_password(request.form, user)\n        if user is not None:\n            login.login_user(user)\n            record_user_login_logout('user_login', user)\n            user_logged_in(user)\n            return redirect(intended_url())\n\n\n@home_routes.route('/password/reset', methods=('GET', 'POST'))\ndef password_reset_view():\n    \"\"\"Password reset view\"\"\"\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/password_reminder.html')\n    if request.method == 'POST':\n        email = request.form['email']\n        user = DataGetter.get_user_by_email(email)\n        if user:\n            link = request.host + url_for(\".change_password_view\", hash=user.reset_password)\n            return link\n            send_email_with_reset_password_hash(email, link)\n            flash('Please go to the link sent to your email to reset your password')\n        return redirect(url_for('.login_view'))\n\n\n@home_routes.route('/reset_password/<hash>', methods=('GET', 'POST'))\ndef change_password_view(hash):\n    \"\"\"Change password view\"\"\"\n    if request.method == 'GET':\n        return render_template('gentelella/admin/login/change_password.html')\n    if request.method == 'POST':\n        DataManager.reset_password(request.form, hash)\n        return redirect(url_for('.index'))\n\n\n@home_routes.route('/logout/')\n@login_required\ndef logout_view():\n    \"\"\"Logout method which redirect to index\"\"\"\n    record_user_login_logout('user_logout', login.current_user)\n    login.logout_user()\n    return redirect(url_for('.index'))\n\n\n@home_routes.route('/set_role', methods=('GET', 'POST'))\n@login_required\ndef set_role():\n    \"\"\"Set user role method\"\"\"\n    id = request.args['id']\n    role = request.args['roles']\n    user = DataGetter.get_user(id)\n    user.role = role\n    save_to_db(user, \"User Role updated\")\n    return redirect(url_for('.roles_manager'))\n\n\n@home_routes.route('/forbidden/', methods=('GET',))\ndef forbidden_view():\n    return render_template('gentelella/errors/403.html')\n\n\n@home_routes.route('/browse/', methods=('GET',))\ndef browse_view():\n    params = request.args.items()\n    params = dict((k, v) for k, v in params if v)\n\n    def test_and_remove(key):\n        if request.args.get(key) and request.args.get(\"query\"):\n            if request.args.get(key).lower() == request.args.get(\"query\").lower():\n                erase_from_dict(params, 'query')\n\n    if not request.args.get(\"location\"):\n        try:\n            reader = geoip2.database.Reader(os.path.realpath('.') + '/static/data/GeoLite2-Country.mmdb')\n            ip = get_real_ip()\n            if ip == '127.0.0.1' or ip == '0.0.0.0':\n                ip = urlopen('http://ip.42.pl/raw').read()  # On local test environments\n            response = reader.country(ip)\n            country = response.country.name\n        except:\n            country = \"United States\"\n    else:\n        country = request.args.get(\"location\")\n\n    test_and_remove(\"location\")\n    test_and_remove(\"category\")\n    erase_from_dict(params, 'location')\n\n    return redirect(url_for('explore.explore_view', location=slugify(country)) + '?' + urllib.urlencode(params))\n\n\n@home_routes.route('/check_email/', methods=('POST', 'GET'))\ndef check_duplicate_email():\n    if request.method == 'GET':\n        email = request.args['email']\n        user = DataGetter.get_user_by_email(email, no_flash=True)\n        if user is None:\n            return '200 OK'\n        else:\n            return abort(404)\n\n\n@home_routes.route('/resend_email/')\ndef resend_email_confirmation_old():\n    return resend_email_confirmation()\n", "path": "app/views/home.py"}]}