Enhance tools.py PEP8 compliancy

This commit is contained in:
Richard Vézina
2017-06-21 11:27:54 -04:00
parent 2f0b429f9e
commit 7ada2cf89a
+46 -42
View File
@@ -1128,7 +1128,6 @@ def addrow(form, a, b, c, style, _id, position=-1):
class AuthJWT(object): class AuthJWT(object):
""" """
Experimental! Experimental!
@@ -1538,7 +1537,8 @@ class Auth(AuthAPI):
# ## these are messages that can be customized # ## these are messages that can be customized
default_messages = dict(AuthAPI.default_messages, default_messages = dict(AuthAPI.default_messages,
access_denied='Insufficient privileges', access_denied='Insufficient privileges',
bulk_invite_body='You have been invited to join %(site)s, click %(link)s to complete the process', bulk_invite_body='You have been invited to join %(site)s, click %(link)s to complete '
'the process',
bulk_invite_subject='Invitation to join %(site)s', bulk_invite_subject='Invitation to join %(site)s',
delete_label='Check to delete', delete_label='Check to delete',
email_sent='Email sent', email_sent='Email sent',
@@ -1841,14 +1841,15 @@ class Auth(AuthAPI):
# ## these are messages that can be customized # ## these are messages that can be customized
messages = self.messages = Messages(current.T) messages = self.messages = Messages(current.T)
messages.update(Auth.default_messages) messages.update(Auth.default_messages)
messages.update(ajax_failed_authentication=DIV(H4('NOT AUTHORIZED'), messages.update(ajax_failed_authentication=
'Please ', DIV(H4('NOT AUTHORIZED'),
A('login', 'Please ',
_href=self.settings.login_url + A('login',
('?_next=' + urllib_quote(current.request.env.http_web2py_component_location)) _href=self.settings.login_url +
if current.request.env.http_web2py_component_location else ''), ('?_next=' + urllib_quote(current.request.env.http_web2py_component_location))
' to view this content.', if current.request.env.http_web2py_component_location else ''),
_class='not-authorized alert alert-block')) ' to view this content.',
_class='not-authorized alert alert-block'))
messages.lock_keys = True messages.lock_keys = True
# for "remember me" option # for "remember me" option
@@ -1877,7 +1878,7 @@ class Auth(AuthAPI):
# _next variable in the request. # _next variable in the request.
if next: if next:
parts = next.split('/') parts = next.split('/')
if not ':' in parts[0]: if ':' not in parts[0]:
return next return next
elif len(parts) > 2 and parts[0].endswith(':') and parts[1:3] == ['', host]: elif len(parts) > 2 and parts[0].endswith(':') and parts[1:3] == ['', host]:
return next return next
@@ -2009,8 +2010,7 @@ class Auth(AuthAPI):
items.append({'name': T('Lost password?'), items.append({'name': T('Lost password?'),
'href': href('request_reset_password'), 'href': href('request_reset_password'),
'icon': 'icon-lock'}) 'icon': 'icon-lock'})
if (self.settings.use_username and not if self.settings.use_username and 'retrieve_username' not in self.settings.actions_disabled:
'retrieve_username' in self.settings.actions_disabled):
items.append({'name': T('Forgot username?'), items.append({'name': T('Forgot username?'),
'href': href('retrieve_username'), 'href': href('retrieve_username'),
'icon': 'icon-edit'}) 'icon': 'icon-edit'})
@@ -2182,9 +2182,7 @@ class Auth(AuthAPI):
current_record.replace('_', ' ').title()) current_record.replace('_', ' ').title())
for table in tables: for table in tables:
fieldnames = table.fields() fieldnames = table.fields()
if ('id' in fieldnames and if 'id' in fieldnames and 'modified_on' in fieldnames and current_record not in fieldnames:
'modified_on' in fieldnames and
not current_record in fieldnames):
table._enable_record_versioning(archive_db=archive_db, table._enable_record_versioning(archive_db=archive_db,
archive_name=archive_names, archive_name=archive_names,
current_record=current_record, current_record=current_record,
@@ -2214,7 +2212,8 @@ class Auth(AuthAPI):
fake_migrate = db._fake_migrate fake_migrate = db._fake_migrate
settings = self.settings settings = self.settings
settings.enable_tokens = enable_tokens settings.enable_tokens = enable_tokens
signature_list = super(Auth, self).define_tables(username, signature, migrate, fake_migrate)._table_signature_list signature_list = \
super(Auth, self).define_tables(username, signature, migrate, fake_migrate)._table_signature_list
now = current.request.now now = current.request.now
reference_table_user = 'reference %s' % settings.table_user_name reference_table_user = 'reference %s' % settings.table_user_name
@@ -2361,7 +2360,7 @@ class Auth(AuthAPI):
if callable(basic_auth_realm): if callable(basic_auth_realm):
basic_auth_realm = basic_auth_realm() basic_auth_realm = basic_auth_realm()
elif isinstance(basic_auth_realm, (unicode, str)): elif isinstance(basic_auth_realm, (unicode, str)):
basic_realm = unicode(basic_auth_realm) basic_realm = unicode(basic_auth_realm) # Warning python 3.5 does not have method unicod
elif basic_auth_realm is True: elif basic_auth_realm is True:
basic_realm = u'' + current.request.application basic_realm = u'' + current.request.application
http_401 = HTTP(401, u'Not Authorized', **{'WWW-Authenticate': u'Basic realm="' + basic_realm + '"'}) http_401 = HTTP(401, u'Not Authorized', **{'WWW-Authenticate': u'Basic realm="' + basic_realm + '"'})
@@ -2463,7 +2462,7 @@ class Auth(AuthAPI):
_href=service + query_sep + "ticket=" + ticket) _href=service + query_sep + "ticket=" + ticket)
else: else:
redirect(service + query_sep + "ticket=" + ticket) redirect(service + query_sep + "ticket=" + ticket)
if self.is_logged_in() and not 'renew' in request.vars: if self.is_logged_in() and 'renew' not in request.vars:
return allow_access() return allow_access()
elif not self.is_logged_in() and 'gateway' in request.vars: elif not self.is_logged_in() and 'gateway' in request.vars:
redirect(session._cas_service) redirect(session._cas_service)
@@ -2780,7 +2779,7 @@ class Auth(AuthAPI):
# If auth.settings.auth_two_factor_enabled it will enable two factor # If auth.settings.auth_two_factor_enabled it will enable two factor
# for all the app. Another way to anble two factor is that the user # for all the app. Another way to anble two factor is that the user
# must be part of a group that is called auth.settings.two_factor_authentication_group # must be part of a group that is called auth.settings.two_factor_authentication_group
if user and self.settings.auth_two_factor_enabled == True: if user and self.settings.auth_two_factor_enabled is True:
session.auth_two_factor_enabled = True session.auth_two_factor_enabled = True
elif user and self.settings.two_factor_authentication_group: elif user and self.settings.two_factor_authentication_group:
role = self.settings.two_factor_authentication_group role = self.settings.two_factor_authentication_group
@@ -2810,7 +2809,7 @@ class Auth(AuthAPI):
# Set the way we generate the code or we send the code. For example using SMS... # Set the way we generate the code or we send the code. For example using SMS...
two_factor_methods = self.settings.two_factor_methods two_factor_methods = self.settings.two_factor_methods
if two_factor_methods == []: if not two_factor_methods:
# TODO: Add some error checking to handle cases where email cannot be sent # TODO: Add some error checking to handle cases where email cannot be sent
self.settings.mailer.send( self.settings.mailer.send(
to=user.email, to=user.email,
@@ -2833,47 +2832,49 @@ class Auth(AuthAPI):
hideerror=settings.hideerror): hideerror=settings.hideerror):
accepted_form = True accepted_form = True
''' """
The lists is executed after form validation for each of the corresponding action. The lists is executed after form validation for each of the corresponding action.
For example, in your model: For example, in your model:
In your models copy and paste: In your models copy and paste:
#Before define tables, we add some extra field to auth_user # Before define tables, we add some extra field to auth_user
auth.settings.extra_fields['auth_user'] = [ auth.settings.extra_fields['auth_user'] = [
Field('motp_secret', 'password', length=512, default='', label='MOTP Secret'), Field('motp_secret', 'password', length=512, default='', label='MOTP Secret'),
Field('motp_pin', 'string', length=128, default='', label='MOTP PIN')] Field('motp_pin', 'string', length=128, default='', label='MOTP PIN')]
OFFSET = 60 #Be sure is the same in your OTP Client OFFSET = 60 # Be sure is the same in your OTP Client
#Set session.auth_two_factor to None. Because the code is generated by external app. # Set session.auth_two_factor to None. Because the code is generated by external app.
# This will avoid to use the default setting and send a code by email. # This will avoid to use the default setting and send a code by email.
def _set_two_factor(user, auth_two_factor): def _set_two_factor(user, auth_two_factor):
return None return None
def verify_otp(user, otp): def verify_otp(user, otp):
import time import time
from hashlib import md5 from hashlib import md5
epoch_time = int(time.time()) epoch_time = int(time.time())
time_start = int(str(epoch_time - OFFSET)[:-1]) time_start = int(str(epoch_time - OFFSET)[:-1])
time_end = int(str(epoch_time + OFFSET)[:-1]) time_end = int(str(epoch_time + OFFSET)[:-1])
for t in range(time_start - 1, time_end + 1): for t in range(time_start - 1, time_end + 1):
to_hash = str(t) + user.motp_secret + user.motp_pin to_hash = str(t) + user.motp_secret + user.motp_pin
hash = md5(to_hash).hexdigest()[:6] hash = md5(to_hash).hexdigest()[:6]
if otp == hash: if otp == hash:
return hash return hash
auth.settings.auth_two_factor_enabled = True auth.settings.auth_two_factor_enabled = True
auth.messages.two_factor_comment = "Verify your OTP Client for the code." auth.messages.two_factor_comment = "Verify your OTP Client for the code."
auth.settings.two_factor_methods = [lambda user, auth_two_factor: _set_two_factor(user, auth_two_factor)] auth.settings.two_factor_methods = [lambda user,
auth_two_factor: _set_two_factor(user, auth_two_factor)]
auth.settings.two_factor_onvalidation = [lambda user, otp: verify_otp(user, otp)] auth.settings.two_factor_onvalidation = [lambda user, otp: verify_otp(user, otp)]
''' """
if self.settings.two_factor_onvalidation != []: if self.settings.two_factor_onvalidation:
for two_factor_onvalidation in self.settings.two_factor_onvalidation: for two_factor_onvalidation in self.settings.two_factor_onvalidation:
try: try:
session.auth_two_factor = two_factor_onvalidation(session.auth_two_factor_user, form.vars['authentication_code']) session.auth_two_factor = \
two_factor_onvalidation(session.auth_two_factor_user, form.vars['authentication_code'])
except: except:
pass pass
else: else:
@@ -4147,7 +4148,7 @@ class Auth(AuthAPI):
archive_table = table._db[archive_table_name] archive_table = table._db[archive_table_name]
new_record = {current_record: form.vars.id} new_record = {current_record: form.vars.id}
for fieldname in archive_table.fields: for fieldname in archive_table.fields:
if not fieldname in ['id', current_record]: if fieldname not in ['id', current_record]:
if archive_current and fieldname in form.vars: if archive_current and fieldname in form.vars:
new_record[fieldname] = form.vars[fieldname] new_record[fieldname] = form.vars[fieldname]
elif form.record and fieldname in form.record: elif form.record and fieldname in form.record:
@@ -4957,7 +4958,10 @@ class Service(object):
Then call it with: Then call it with:
wget --post-data '{"jsonrpc": "2.0", "id": 1, "method": "myfunction", "params": {"a": 1, "b": 2}}' http://..../app/default/call/jsonrpc2 wget --post-data '{"jsonrpc": "2.0",
"id": 1,
"method": "myfunction",
"params": {"a": 1, "b": 2}}' http://..../app/default/call/jsonrpc2
""" """
self.jsonrpc2_procedures[f.__name__] = f self.jsonrpc2_procedures[f.__name__] = f
@@ -5781,7 +5785,7 @@ class Expose(object):
return os.path.realpath(f) return os.path.realpath(f)
def issymlink_out(self, f): def issymlink_out(self, f):
"True if f is a symlink and is pointing outside of self.base" """True if f is a symlink and is pointing outside of self.base"""
return os.path.islink(f) and not self.in_base(f) return os.path.islink(f) and not self.in_base(f)
@staticmethod @staticmethod