Skip to content

Commit

Permalink
Reformat the code using black, and drop 1.10 from .travis.yml
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiask committed Jun 7, 2018
1 parent efcabed commit e6d03ec
Show file tree
Hide file tree
Showing 25 changed files with 454 additions and 543 deletions.
25 changes: 18 additions & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
language: python
sudo: false
# cache: pip
language: python
python:
- "3.5"
- "3.6"
- "3.6"
- "3.5"
env:
- REQ="Django>=1.10,<1.11"
- REQ="Django>=1.11,<2.0"
- REQ="Django>=2.0,<2.1"
- REQ="https://github.com/django/django/archive/master.zip#egg=Django"
matrix:
allow_failures:
- env: REQ="https://github.com/django/django/archive/master.zip#egg=Django"
install:
- pip install $REQ pytz requests_oauthlib
- python setup.py install
script: "cd tests && ./manage.py test testapp"
- pip install -U pip wheel
- pip install requests-oauthlib
- pip install $REQ
- python setup.py install
script: cd tests && ./manage.py test testapp && cd ..

jobs:
include:
- stage: style
env: REQ=none
install: skip
script:
- pip install flake8
- flake8 .
2 changes: 1 addition & 1 deletion authlib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
VERSION = (0, 6, 4)
__version__ = '.'.join(map(str, VERSION))
__version__ = ".".join(map(str, VERSION))
8 changes: 1 addition & 7 deletions authlib/admin_oauth/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,4 @@
from authlib.admin_oauth.views import admin_oauth


urlpatterns = [
url(
r'^admin/__oauth__/$',
admin_oauth,
name='admin_oauth',
),
]
urlpatterns = [url(r"^admin/__oauth__/$", admin_oauth, name="admin_oauth")]
25 changes: 10 additions & 15 deletions authlib/admin_oauth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from authlib.google import GoogleOAuth2Client


REDIRECT_SESSION_KEY = 'admin-oauth-next'
REDIRECT_SESSION_KEY = "admin-oauth-next"
ADMIN_OAUTH_PATTERNS = settings.ADMIN_OAUTH_PATTERNS


Expand All @@ -25,25 +25,21 @@ def is_safe_url(url, allowed_hosts):

def retrieve_next(request):
next = request.session.pop(REDIRECT_SESSION_KEY, None)
return (
next
if is_safe_url(url=next, allowed_hosts=[request.get_host()])
else None
)
return next if is_safe_url(url=next, allowed_hosts=[request.get_host()]) else None


@never_cache
def admin_oauth(request):
client = GoogleOAuth2Client(request)

if request.GET.get('next'):
request.session[REDIRECT_SESSION_KEY] = request.GET['next']
if request.GET.get("next"):
request.session[REDIRECT_SESSION_KEY] = request.GET["next"]

if all(key not in request.GET for key in ('code', 'oauth_token')):
if all(key not in request.GET for key in ("code", "oauth_token")):
return redirect(client.get_authentication_url())

user_data = client.get_user_data()
email = user_data.get('email', '')
email = user_data.get("email", "")

if email:
for pattern, user_mail in ADMIN_OAUTH_PATTERNS:
Expand All @@ -54,12 +50,11 @@ def admin_oauth(request):
user = auth.authenticate(email=user_mail)
if user and user.is_staff:
auth.login(request, user)
return redirect(retrieve_next(request) or 'admin:index')
return redirect(retrieve_next(request) or "admin:index")

messages.error(
request,
_('No matching staff users for email address \'%s\'') % email,
request, _("No matching staff users for email address '%s'") % email
)
else:
messages.error(request, _('Could not determine your email address.'))
return redirect('admin:login')
messages.error(request, _("Could not determine your email address."))
return redirect("admin:login")
3 changes: 3 additions & 0 deletions authlib/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ def get_user(self, user_id):
return None

if VERSION < (1, 11):

def authenticate(self, email):
return _by_email(email)

else:

def authenticate(self, request, email):
return _by_email(email)
26 changes: 10 additions & 16 deletions authlib/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ def get_user_data(self):
class BaseUserManager(auth_models.BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Email missing')
user = self.model(
email=self.normalize_email(email),
)
raise ValueError("Email missing")
user = self.model(email=self.normalize_email(email))
if password:
user.set_password(password)
user.save(using=self._db)
Expand All @@ -36,25 +34,21 @@ def create_superuser(self, email, password=None):


class BaseUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
EMAIL_FIELD = "email"
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []

email = models.EmailField(
_('email'),
max_length=254,
unique=True,
)
is_active = models.BooleanField(_('is active'), default=True)
is_staff = models.BooleanField(_('is staff'), default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
email = models.EmailField(_("email"), max_length=254, unique=True)
is_active = models.BooleanField(_("is active"), default=True)
is_staff = models.BooleanField(_("is staff"), default=False)
date_joined = models.DateTimeField(_("date joined"), default=timezone.now)

objects = BaseUserManager()

class Meta:
abstract = True
verbose_name = _('user')
verbose_name_plural = _('users')
verbose_name = _("user")
verbose_name_plural = _("users")

def __str__(self):
return self.email
Expand Down
88 changes: 46 additions & 42 deletions authlib/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,29 @@ def render_to_mail(template, context, **kwargs):
message = render_to_mail('myproject/hello_mail', {}, to=[email])
message.send()
"""
lines = iter(render_to_string('%s.txt' % template, context).splitlines())
lines = iter(render_to_string("%s.txt" % template, context).splitlines())

subject = ''
subject = ""
while True:
line = next(lines)
if line:
subject = line
break

body = '\n'.join(lines).strip('\n')
body = "\n".join(lines).strip("\n")
message = EmailMultiAlternatives(subject=subject, body=body, **kwargs)

try:
message.attach_alternative(
render_to_string('%s.html' % template, context),
'text/html')
render_to_string("%s.html" % template, context), "text/html"
)
except TemplateDoesNotExist:
pass

return message


def get_signer(salt='email_registration'):
def get_signer(salt="email_registration"):
"""
Returns the signer instance used to sign and unsign the registration
link tokens
Expand All @@ -68,36 +68,32 @@ def get_last_login_timestamp(user):
"""
Django 1.7 allows the `last_login` timestamp to be `None` for new users.
"""
return int(user.last_login.strftime('%s')) if user.last_login else 0
return int(user.last_login.strftime("%s")) if user.last_login else 0


def get_confirmation_code(email, request, *, user=None):
"""
Returns the code for the confirmation URL
"""
code = [email, '', '']
code = [email, "", ""]
if user:
code[1] = str(user.id)
code[2] = int_to_base36(get_last_login_timestamp(user))
return get_signer().sign(':'.join(code))
return get_signer().sign(":".join(code))


def get_confirmation_url(email, request, user=None,
name='email_registration_confirm'):
def get_confirmation_url(email, request, user=None, name="email_registration_confirm"):
"""
Returns the confirmation URL
"""
code = [email, '', '']
code = [email, "", ""]
if user:
code[1] = str(user.id)
code[2] = int_to_base36(get_last_login_timestamp(user))

return request.build_absolute_uri(reverse(
name,
kwargs={
'code': get_confirmation_code(email, request, user=user),
},
))
return request.build_absolute_uri(
reverse(name, kwargs={"code": get_confirmation_code(email, request, user=user)})
)


def send_registration_mail(email, *, request, user=None):
Expand All @@ -122,10 +118,8 @@ def send_registration_mail(email, *, request, user=None):
"""

render_to_mail(
'registration/email_registration_email',
{
'url': get_confirmation_url(email, request, user=user),
},
"registration/email_registration_email",
{"url": get_confirmation_url(email, request, user=user)},
to=[email],
).send()

Expand All @@ -144,37 +138,47 @@ def decode(code, *, max_age):
try:
data = get_signer().unsign(code, max_age=max_age)
except signing.SignatureExpired:
raise ValidationError(_(
'The link is expired. Please request another registration link.'
), code='email_registration_expired')
raise ValidationError(
_("The link is expired. Please request another registration link."),
code="email_registration_expired",
)

except signing.BadSignature:
raise ValidationError(_(
'Unable to verify the signature. Please request a new'
' registration link.'
), code='email_registration_signature')

parts = data.split(':')
raise ValidationError(
_(
"Unable to verify the signature. Please request a new"
" registration link."
),
code="email_registration_signature",
)

parts = data.split(":")
if len(parts) != 3:
raise ValidationError(_(
'Something went wrong while decoding the'
' registration request. Please try again.'
), code='email_registration_broken')
raise ValidationError(
_(
"Something went wrong while decoding the"
" registration request. Please try again."
),
code="email_registration_broken",
)

email, uid, timestamp = parts
if uid and timestamp:
try:
user = User.objects.get(pk=uid)
except (User.DoesNotExist, TypeError, ValueError):
raise ValidationError(_(
'Something went wrong while decoding the'
' registration request. Please try again.'
), code='email_registration_invalid_uid')
raise ValidationError(
_(
"Something went wrong while decoding the"
" registration request. Please try again."
),
code="email_registration_invalid_uid",
)

if timestamp != int_to_base36(get_last_login_timestamp(user)):
raise ValidationError(_(
'The link has already been used.'
), code='email_registration_used')
raise ValidationError(
_("The link has already been used."), code="email_registration_used"
)

else:
user = None
Expand Down
21 changes: 9 additions & 12 deletions authlib/facebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@


class FacebookOAuth2Client(OAuthClient):
authorization_base_url = 'https://www.facebook.com/dialog/oauth'
token_url = 'https://graph.facebook.com/oauth/access_token'
scope = ['email']
authorization_base_url = "https://www.facebook.com/dialog/oauth"
token_url = "https://graph.facebook.com/oauth/access_token"
scope = ["email"]
client_id = settings.FACEBOOK_CLIENT_ID
client_secret = settings.FACEBOOK_CLIENT_SECRET

Expand All @@ -17,13 +17,13 @@ def __init__(self, request):
self._session = OAuth2Session(
self.client_id,
scope=self.scope,
redirect_uri=request.build_absolute_uri('.'),
redirect_uri=request.build_absolute_uri("."),
)

def get_authentication_url(self):
authorization_url, self._state = self._session.authorization_url(
self.authorization_base_url,
access_type='online', # Only right now.
access_type="online", # Only right now.
# approval_prompt='force', # Maybe not, later.
)

Expand All @@ -34,14 +34,11 @@ def get_user_data(self):
self.token_url,
client_secret=self.client_secret,
authorization_response=self._request.build_absolute_uri(
self._request.get_full_path()),
self._request.get_full_path()
),
)
data = self._session.get(
'https://graph.facebook.com/v2.8/me',
params={'fields': 'email,name'},
"https://graph.facebook.com/v2.8/me", params={"fields": "email,name"}
).json()

return {
'email': data.get('email'),
'full_name': data.get('name'),
}
return {"email": data.get("email"), "full_name": data.get("name")}

0 comments on commit e6d03ec

Please sign in to comment.