-
Notifications
You must be signed in to change notification settings - Fork 1
/
first.py
309 lines (260 loc) · 9.93 KB
/
first.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""Flask Simple Login - Login Extension for Flask"""
__version__ = '0.0.7'
__author__ = 'Bruno Rocha'
__email__ = '[email protected]'
import logging
import os
from functools import wraps
from uuid import uuid4
from warnings import warn
from flask import (Blueprint, current_app, flash, redirect, render_template,
request, session, url_for)
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired
logger = logging.getLogger(__name__)
class LoginForm(FlaskForm):
"Default login form"
username = StringField('name', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
def default_login_checker(user):
"""user must be a dictionary here default is
checking username/password
if login is ok returns True else False
:param user: dict {'username':'', 'password': ''}
"""
username = user.get('username')
password = user.get('password')
the_username = os.environ.get(
'SIMPLELOGIN_USERNAME',
current_app.config.get('SIMPLELOGIN_USERNAME', 'admin')
)
the_password = os.environ.get(
'SIMPLELOGIN_PASSWORD',
current_app.config.get('SIMPLELOGIN_PASSWORD', 'secret')
)
if username == the_username and password == the_password:
return True
return False
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list"""
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_username() in username
return 'simple_logged_in' in session
def get_username():
"""Get current logged in username"""
return session.get('simple_username')
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function])
"""
if function and not callable(function):
raise ValueError(
'Decorator receives only named arguments, '
'try login_required(username="foo")'
)
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return SimpleLogin.get_message('auth_error', error), 403
def dispatch(fun, *args, **kwargs):
if basic and request.is_json:
return dispatch_basic_auth(fun, *args, **kwargs)
if is_logged_in(username=username):
return check(must) or fun(*args, **kwargs)
elif is_logged_in():
return SimpleLogin.get_message('access_denied'), 403
else:
flash(SimpleLogin.get_message('login_required'), 'warning')
return redirect(url_for('simplelogin.login', next=request.path))
def dispatch_basic_auth(fun, *args, **kwargs):
simplelogin = current_app.extensions['simplelogin']
auth_response = simplelogin.basic_auth()
if auth_response is True:
return check(must) or fun(*args, **kwargs)
else:
return auth_response
if function:
@wraps(function)
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs)
return simple_decorator
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap
return decorator
class SimpleLogin(object):
"""Simple Flask Login"""
messages = {
'login_success': 'login success!',
'login_failure': 'invalid credentials',
'is_logged_in': 'already logged in',
'logout': 'Logged out!',
'login_required': 'You need to login first',
'access_denied': 'Access Denied',
'auth_error': 'Authentication Error: {0}'
}
@staticmethod
def get_message(message, *args, **kwargs):
"""Helper to get internal messages outside this instance"""
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg
def __init__(self, app=None, login_checker=None,
login_form=None, messages=None):
self.config = {
'blueprint': 'simplelogin',
'login_url': '/login/',
'logout_url': '/logout/',
'home_url': '/'
}
self.app = None
self._login_checker = login_checker or default_login_checker
self._login_form = login_form or LoginForm
if app is not None:
self.init_app(
app=app, login_checker=login_checker,
login_form=login_form, messages=messages
)
def login_checker(self, f):
"""To set login_checker as decorator:
@simple.login_checher
def foo(user): ...
"""
self._login_checker = f
return f
def init_app(self, app, login_checker=None,
login_form=None, messages=None):
if login_checker:
self._login_checker = login_checker
if login_form:
self._login_form = login_form
if messages and isinstance(messages, dict):
self.messages.update(messages)
self._register(app)
self._load_config()
self._set_default_secret()
self._register_views()
self._register_extras()
def _register(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
if 'simplelogin' in app.extensions:
raise RuntimeError("Flask extension already initialized")
app.extensions['simplelogin'] = self
self.app = app
def _load_config(self):
config = self.app.config.get_namespace(
namespace='SIMPLELOGIN_',
lowercase=True,
trim_namespace=True
)
# backwards compatibility
old_config = self.app.config.get_namespace(
namespace='SIMPLE_LOGIN_',
lowercase=True,
trim_namespace=True
)
config.update(old_config)
if old_config:
msg = (
"Settings defined as SIMPLE_LOGIN_ will be deprecated. "
"Please, use SIMPLELOGIN_ instead."
)
warn(msg, FutureWarning)
self.config.update(old_config)
self.config.update(
dict((key, value) for key, value in config.items() if value)
)
def _set_default_secret(self):
if self.app.config.get('SECRET_KEY') is None:
secret_key = str(uuid4())
logger.warning((
'Using random SECRET_KEY: {0}, '
'please set it on your app.config["SECRET_KEY"]'
).format(secret_key))
self.app.config['SECRET_KEY'] = secret_key
def _register_views(self):
self.blueprint = Blueprint(
self.config['blueprint'],
__name__,
template_folder='templates'
)
self.blueprint.add_url_rule(
self.config['login_url'],
endpoint='login',
view_func=self.login,
methods=['GET', 'POST']
)
self.blueprint.add_url_rule(
self.config['logout_url'],
endpoint='logout',
view_func=self.logout,
methods=['GET']
)
self.app.register_blueprint(self.blueprint)
def _register_extras(self):
self.app.add_template_global(is_logged_in)
self.app.add_template_global(get_username)
def basic_auth(self, response=None):
"""Support basic_auth via /login or login_required(basic=True)"""
auth = request.authorization
if auth and self._login_checker({'username': auth.username,
'password': auth.password}):
session['simple_logged_in'] = True
session['simple_basic_auth'] = True
session['simple_username'] = auth.username
return response or True
else:
headers = {'WWW-Authenticate': 'Basic realm="Login Required"'}
return 'Invalid credentials', 401, headers
def login(self):
destiny = request.args.get(
'next',
default=request.form.get(
'next',
default=self.config.get('home_url', '/')
)
)
if is_logged_in():
flash(self.messages['is_logged_in'], 'primary')
return redirect(destiny)
if request.is_json:
# recommended to use `login_required(basic=True)` instead this
return self.basic_auth(destiny=redirect(destiny))
form = self._login_form()
ret_code = 200
if form.validate_on_submit():
if self._login_checker(form.data):
flash(self.messages['login_success'], 'success')
session['simple_logged_in'] = True
session['simple_username'] = form.data.get('username')
return redirect(destiny)
else:
flash(self.messages['login_failure'], 'danger')
ret_code = 401 # <-- invalid credentials RFC7235
return render_template('login.html', form=form, next=destiny), ret_code
def logout(self):
session.clear()
flash(self.messages['logout'], 'primary')
return redirect(self.config.get('home_url', '/'))