Background Image
Table of Contents Table of Contents
Previous Page  274 / 478 Next Page
Information
Show Menu
Previous Page 274 / 478 Next Page
Page Background

accounts/authentication.py.

import

requests

import

sys

from

accounts.models

import

ListUser

class

PersonaAuthenticationBackend

(

object

):

def

authenticate

(

self

,

assertion

):

# Send the assertion to Mozilla's verifier service.

data

=

{

'assertion'

:

assertion

,

'audience'

:

'localhost'

}

print

(

'sending to mozilla'

,

data

,

file

=

sys

.

stderr

)

resp

=

requests

.

post

(

'https://verifier.login.persona.org/verify

'

,

data

=

data

)

print

(

'got'

,

resp

.

content

,

file

=

sys

.

stderr

)

# Did the verifier respond?

if

resp

.

ok

:

# Parse the response

verification_data

=

resp

.

json

()

# Check if the assertion was valid

if

verification_data

[

'status'

]

==

'okay'

:

email

=

verification_data

[

'email'

]

try

:

return

self

.

get_user

(

email

)

except

ListUser

.

DoesNotExist

:

return

ListUser

.

objects

.

create

(

email

=

email

)

def

get_user

(

self

,

email

):

return

ListUser

.

objects

.

get

(

email

=

email

)

This code is copy-pasted directly from the Mozilla site, as you can see from the ex‐

planatory comments.

You’ll need to

pip install requests

into your virtualenv. If you’ve never used it before,

Requests

is a great alternative to the Python standard library tools for HTTP requests.

To finish off the job of customising authentication in Django, we just need a custom

user model:

accounts/models.py.

from

django.contrib.auth.models

import

AbstractBaseUser

,

PermissionsMixin

from

django.db

import

models

class

ListUser

(

AbstractBaseUser

,

PermissionsMixin

):

email

=

models

.

EmailField

(

primary_key

=

True

)

USERNAME_FIELD

=

'email'

#REQUIRED_FIELDS = ['email', 'height']

objects

=

ListUserManager

()

@property

def

is_staff

(

self

):

return

self

.

email

==

'harry.percival@example.com

'

@property

246

|

Chapter 15: User Authentication, Integrating Third-Party Plugins, and Mocking with JavaScript