- Authentication
- Restrictions on registration
- Integration with OpenID, Facebook, etc.
- CAPTCHA and reCAPTCHA
- Customizing
Auth
- Renaming
Auth
tables - Other login methods and login forms
- Record versioning
Mail
andAuth
- Two-step verification
Authentication
In order to use RBAC, users need to be identified. This means that they need to register (or be registered) and log in.
Auth provides multiple login methods. The default one consists of identifying users based on the local auth_user
table. Alternatively, it can log in users against third-party authentication systems and single sign on providers such as Google, PAM, LDAP, Facebook, LinkedIn, Dropbox, OpenID, OAuth, etc..
To start using Auth
, you need at least this code in a model file, which is also provided with the web2py “welcome” application and assumes a db
connection object:
from gluon.tools import Auth
auth = Auth(db)
auth.define_tables(username=False, signature=False)
By default, web2py uses email for login. If instead you want to log in using username set auth.define_tables(username=True)
Setting signature=True
adds user and date stamping to auth tables, to track modifications.
Auth has an optional secure=True
argument, which will force authenticated pages to go over HTTPS.
By default, Auth protects logins against cross-site request forgeries (CSRF). This is actually provided by web2py’s standard CSRF protection whenever forms are generated in a session. However, under some circumstances, the overhead of creating a session for login,password request and reset attempts may be undesirable. DOS attacks are theoretically possible. CSRF protection can be disabled for Auth forms (as of v 2.6):
Auth = Auth(..., csrf_prevention = False)
Note that doing this purely to avoid session overload on a busy site is not recommended because of the introduced security risk. Instead, see the Deployment chapter for advice on reducing session overheads.
The
password
field of thedb.auth_user
table defaults to aCRYPT
validator, which needs anhmac_key
. On legacy web2py applications you may see an extra argument passed to the Auth constructor:hmac_key = Auth.get_or_create_key()
. The latter is a function that read the HMAC key from a file “private/auth.key” within the application folder. If the file does not exist it creates a randomhmac_key
. If multiple apps share the same auth database, make sure they also use the samehmac_key
. This is no longer necessary for new applications since passwords are salted with an individual random salt.
If multiple apps share the same auth database you may want to disable migrations: auth.define_tables(migrate=False)
.
To expose Auth, you also need the following function in a controller (for example in “default.py”):
def user(): return dict(form=auth())
The
auth
object and theuser
action are already defined in the scaffolding application.
web2py also includes a sample view “welcome/views/default/user.html” to render this function properly that looks like this:
{{extend 'layout.html'}}
<h2>{{=T( request.args(0).replace('_', ' ').capitalize() )}}</h2>
<div id="web2py_user_form">
{{=form}}
{{if request.args(0)=='login':}}
{{if not 'register' in auth.settings.actions_disabled:}}
<br/><a href="{{=URL(args='register')}}">register</a>
{{pass}}
{{if not 'request_reset_password' in auth.settings.actions_disabled:}}
<br/>
<a href="{{=URL(args='request_reset_password')}}">lost password</a>
{{pass}}
{{pass}}
</div>
Notice that this function simply displays a form
and therefore it can be customized using normal custom form syntax. The only caveat is that the form displayed by form=auth()
depends on request.args(0)
; therefore, if you replace the default auth()
login form with a custom login form, you may need an if
statement like this in the view:
{{if request.args(0)=='login':}}...custom login form...{{pass}}
The controller above exposes multiple actions:
http://.../[app]/default/user/register
http://.../[app]/default/user/login
http://.../[app]/default/user/logout
http://.../[app]/default/user/profile
http://.../[app]/default/user/change_password
http://.../[app]/default/user/verify_email
http://.../[app]/default/user/retrieve_username
http://.../[app]/default/user/request_reset_password
http://.../[app]/default/user/reset_password
http://.../[app]/default/user/impersonate
http://.../[app]/default/user/groups
http://.../[app]/default/user/not_authorized
- register allows users to register. It is integrated with CAPTCHA, although this is disabled by default. This is also integrated with a client-side entropy calculator defined in “web2py.js”. The calculator indicates the strength of the new password. You can use the
IS_STRONG
validator to prevent web2py from accepting weak passwords. - login allows users who are registered to log in (if the registration is verified or does not require verification, if it has been approved or does not require approval, and if it has not been blocked).
- logout does what you would expect but also, as the other methods, logs the event and can be used to trigger some event.
- profile allows users to edit their profile, i.e. the content of the
auth_user
table. Notice that this table does not have a fixed structure and can be customized. - change_password allows users to change their password in a fail-safe way.
- verify_email. If email verification is turned on, then visitors, upon registration, receive an email with a link to verify their email information. The link points to this action.
- retrieve_username. By default, Auth uses email and password for login, but it can, optionally, use username instead of email. In this latter case, if a user forgets his/her username, the
retrieve_username
method allows the user to type the email address and retrieve the username by email. - request_reset_password. Allows users who forgot their password to request a new password. They will get a confirmation email pointing to reset_password.
- impersonate allows a user to “impersonate” another user. This is important for debugging and for support purposes.
request.args[0]
is the id of the user to be impersonated. This is only allowed if the logged in userhas_permission('impersonate', db.auth_user, user_id)
. You can useauth.is_impersonating()
to check is the current user is impersonating somebody else. - groups lists the groups of which the current logged in user is a member.
- not_authorized displays an error message when the visitor tried to do something that he/she is not authorized to do
- navbar is a helper that generates a bar with login/register/etc. links.
Logout, profile, change_password, impersonate, and groups require login.
By default they are all exposed, but it is possible to restrict access to only some of these actions.
All of the methods above can be extended or replaced by subclassing Auth.
All of the methods above can be used in separate actions. For example:
def mylogin(): return dict(form=auth.login())
def myregister(): return dict(form=auth.register())
def myprofile(): return dict(form=auth.profile())
...
To restrict access to functions to only logged in visitors, decorate the function as in the following example
@auth.requires_login()
def hello():
return dict(message='hello %(first_name)s' % auth.user)
Any function can be decorated, not just exposed actions. Of course this is still only a very simple example of access control. More complex examples will be discussed later.
auth.user_groups
.
auth.user
contains a copy of thedb.auth_user
records for the current logged in user orNone
otherwise. There is also aauth.user_id
which is the same asauth.user.id
(i.e. the id of the current logger in user) orNone
. Similarly,auth.user_groups
contains a dictionary where each key is the id of a group of with the current logged in user is member of, the value is the corresponding group role.
The auth.requires_login()
decorator as well as the other auth.requires_*
decorators take an optional otherwise
argument. It can be set to a string where to redirect the user if registration files or to a callable object. It is called if registration fails.
Restrictions on registration
If you want to allow visitors to register but not to log in until registration has been approved by the administrator:
auth.settings.registration_requires_approval = True
You can approve a registration via the appadmin interface. Look into the table auth_user
. Pending registrations have a registration_key
field set to “pending”. A registration is approved when this field is set to blank.
Via the appadmin interface, you can also block a user from logging in. Locate the user in the table auth_user
and set the registration_key
to “blocked”. “blocked” users are not allowed to log in. Notice that this will prevent a visitor from logging in but it will not force a visitor who is already logged in to log out. The word “disabled” may be used instead of “blocked” if preferred, with exactly the same behavior.
You can also block access to the “register” page completely with this statement:
auth.settings.actions_disabled.append('register')
If you want to allow people to register and automatically log them in after registration but still want to send an email for verification so that they cannot login again after logout, unless they completed the instructions in the email, you can accomplish it as follows:
auth.settings.registration_requires_verification = True
auth.settings.login_after_registration = True
Other methods of Auth can be restricted in the same way.
Integration with OpenID, Facebook, etc.
You can use the web2py Role Base Access Control and authenticate with other services like OpenID, Facebook, LinkedIn, Google, Dropbox, MySpace, Flickr, etc. The easiest way is to use Janrain Engage (formerly RPX) (Janrain.com).
Dropbox is discussed as a special case in Chapter 14 since it allows more than just login, it also provides storage services for the logged in users.
Janrain Engage is a service that provides middleware authentication. You can register with Janrain.com, register a domain (the name of your app) and set of URLs you will be using, and they will provide you with an API key.
Now edit the model of your web2py application and place the following lines somewhere after the definition of the auth
object :
from gluon.contrib.login_methods.rpx_account import RPXAccount
auth.settings.actions_disabled=['register', 'change_password', 'request_reset_password']
auth.settings.login_form = RPXAccount(request,
api_key='...',
domain='...',
url = "http://your-external-address/%s/default/user/login" % request.application)
The first line imports the new login method, the second line disables local registration, and the third line asks web2py to use the RPX login method. You must insert your own api_key
provided by Janrain.com, the domain you choose upon registration and the external url
of your login page. To obtain then login at janrain.com, then go to [Deployment][Application Settings]. On the right side there is the “Application Info”, The api_key is called “API Key (Secret)”.
The domain is the “Application Domain” without leading “https://“ and without the trailing “.rpxnow.com/“ For example: if you have registered a website as “secure.mywebsite.org”, Janrain turns it to the Application Domain “https://secure-mywebsite.rpxnow.com“.
When a new user logins for the first time, web2py creates a new db.auth_user
record associated to the user. It will use the registration_id
field to store a unique id for the user. Most authentication methods will also provide a username, email, first_name and last_name but that is not guaranteed. Which fields are provided depends on the login method selected by the user. If the same user logs in twice using different authentication mechanisms (for example once with OpenID and once with Facebook), Janrain may not recognize his/her as the same user and issue different registration_id
.
You can customize the mapping between the data provided by Janrain and the data stored in db.auth_user
. Here is an example for Facebook:
auth.settings.login_form.mappings.Facebook = lambda profile: dict(registration_id = profile["identifier"],
username = profile["preferredUsername"],
email = profile["email"],
first_name = profile["name"]["givenName"],
last_name = profile["name"]["familyName"])
The keys in the dictionary are fields in db.auth_user
and the values are data entries in the profile object provided by Janrain. Look at the online Janrain documentation for details on the latter.
Janrain will also keep statistics about your users’ login.
This login form is fully integrated with web2py Role Based Access Control and you can still create groups, make users members of groups, assign permissions, block users, etc.
Janrain’s free Basic service allows up to 2500 unique registered users to sign in annually. Accommodating more users requires an upgrade to one of their paid service tiers.
If you prefer not to use Janrain and want to use a different login method (LDAP, PAM, Google, OpenID, OAuth/Facebook, LinkedIn, etc.) you can do so. The API to do so is described later in the chapter.
CAPTCHA and reCAPTCHA
To prevent spammers and bots registering on your site, you may require a registration CAPTCHA. web2py supports reCAPTCHA[recaptcha] out of the box. This is because reCAPTCHA is very well designed, free, accessible (it can read the words to the visitors), easy to set up, and does not require installing any third-party libraries.
This is what you need to do to use reCAPTCHA:
- Register with reCAPTCHA[recaptcha] V2 and obtain a (PUBLIC_KEY, PRIVATE_KEY) couple for your account. These are just two strings.
- Append the following code to your model after the
auth
object is defined:
from gluon.tools import Recaptcha2
auth.settings.captcha = Recaptcha2(request,
'PUBLIC_KEY', 'PRIVATE_KEY')
reCAPTCHA may not work if you access the web site as ‘localhost’ or ‘127.0.0.1’, because it is registered to work with publicly visible web sites only, unless you add them to the domains in the reCAPTCHA admin panel.
The Recaptcha2
constructor takes some optional arguments:
Recaptcha2(..., error_message='invalid', label='Verify:', options={})
There is an experimental argument, ajax=True
, which uses the ajax API to recaptcha. It can be used with any recaptcha, but it was specifically added to allow recpatcha fields to work in LOAD forms (see Chapter 12 for more about LOAD, which allows web2py to ‘plugin’ components of a page with ajax ). It’s experimental because it may be replaced with automatic detection of when ajax is required.
options
may be a configuration dictionary, e.g. options={theme: 'white', size: 'normal'}
More details: reCAPTCHA[recaptchagoogle] and configuration.
If you do not want to use reCAPTCHA, look into the definition of the Recaptcha2
class in “gluon/tools.py”, since it is easy to use other CAPTCHA systems.
Notice that Recaptcha2
is just a helper that extends DIV
. It generates a dummy field that validates using the reCaptcha
service and, therefore, it can be used in any form, including used defined FORMs:
form = FORM(INPUT(...), Recaptcha2(...), INPUT(_type='submit'))
You can use it in all types of SQLFORM by injection:
form = SQLFORM(...) or SQLFORM.factory(...)
form.insert(-1, TR('', Recaptcha2(...), ''))
Customizing Auth
The call to
auth.define_tables()
defines all Auth tables that have not been defined already. This means that if you wish to do so, you can define your own auth_user
table.
There are a number of ways to customize auth. The simplest way is to add extra fields:
## after auth = Auth(db)
auth.settings.extra_fields['auth_user']= [
Field('address'),
Field('city'),
Field('zip'),
Field('phone')]
## before auth.define_tables(username=True)
You can declare extra fields not just for table “auth_user” but also for other “auth_“ tables. Using extra_fields
is the recommended way as it will not break any internal mechanism.
Another way to do this, although not really recommended, consists of defining your auth tables yourself. If a table is declared before auth.define_tables()
it is used instead of the default one. Here is how to do it:
## after auth = Auth(db)
db.define_table(
auth.settings.table_user_name,
Field('first_name', length=128, default=''),
Field('last_name', length=128, default=''),
Field('email', length=128, default='', unique=True), # required
Field('password', 'password', length=512, # required
readable=False, label='Password'),
Field('address'),
Field('city'),
Field('zip'),
Field('phone'),
Field('registration_key', length=512, # required
writable=False, readable=False, default=''),
Field('reset_password_key', length=512, # required
writable=False, readable=False, default=''),
Field('registration_id', length=512, # required
writable=False, readable=False, default=''))
## do not forget validators
custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table
custom_auth_table.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
custom_auth_table.password.requires = [IS_STRONG(), CRYPT()]
custom_auth_table.email.requires = [
IS_EMAIL(error_message=auth.messages.invalid_email),
IS_NOT_IN_DB(db, custom_auth_table.email)]
auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table
## before auth.define_tables()
You can add any field you wish, and you can change validators but you cannot remove the fields marked as “required” in this example.
It is important to make “password”, “registration_key”, “reset_password_key” and “registration_id” fields readable=False
and writable=False
, since a visitor must not be allowed to tamper with them.
If you add a field called “username”, it will be used in place of “email” for login. If you do, you will need to add a validator as well:
auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)
Note that Auth caches the logged in user in the session and that’s what you get in auth.user
, so you need to clear the sessions for the extra fields changes to be reflected in it.
Renaming Auth
tables
[renaming_auth_tables]
The actual names of the Auth
tables are stored in
auth.settings.table_user_name = 'auth_user'
auth.settings.table_group_name = 'auth_group'
auth.settings.table_membership_name = 'auth_membership'
auth.settings.table_permission_name = 'auth_permission'
auth.settings.table_event_name = 'auth_event'
The names of the table can be changed by reassigning the above variables after the auth
object is defined and before the Auth tables are defined. For example:
auth = Auth(db)
auth.settings.table_user_name = 'person'
#...
auth.define_tables()
The actual tables can also be referenced, independently of their actual names, by
auth.settings.table_user
auth.settings.table_group
auth.settings.table_membership
auth.settings.table_permission
auth.settings.table_event
Note: auth.signature gets defined when Auth is initialized, which is before you have set the custom table names. To avoid this do:
auth = Auth(db, signature=False)
In that case, auth.signature will instead be defined when you call auth.define_tables(), by which point the custom tables names will already be set.
Other login methods and login forms
Auth provides multiple login methods and hooks to create new login methods. Each supported login method corresponds to a file in the folder
gluon/contrib/login_methods/
Refer to the documentation in the files themselves for each login method, but here are some examples.
First of all, we need to make a distinction between two types of alternate login methods:
- login methods that use a web2py login form (although the credentials are verified outside web2py). An example is LDAP.
- login methods that require an external single-sign-on form (an example is Google and Facebook).
In the latter case, web2py never gets the login credentials, only a login token issued by the service provider. The token is stored in db.auth_user.registration_id
.
Let’s consider examples of the first case:
Basic
Let’s say you have an authentication service, for example at the url
https://basic.example.com
that accepts basic access authentication. That means the server accepts HTTP requests with a header of the form:
GET /index.html HTTP/1.0
Host: basic.example.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
where the latter string is the base64 encoding of the string username:password. The service responds 200 OK if the user is authorized and 400, 401, 402, 403 or 404 otherwise.
You want to enter username and password using the standard Auth
login form and verify the credentials against such a service. All you need to do is add the following code to your application
from gluon.contrib.login_methods.basic_auth import basic_auth
auth.settings.login_methods.append(
basic_auth('https://basic.example.com'))
Notice that auth.settings.login_methods
is a list of authentication methods that are executed sequentially. By default it is set to
auth.settings.login_methods = [auth]
When an alternate method is appended, for example basic_auth
, Auth first tries to log in the visitor based on the content of auth_user
, and when this fails, it tries the next method in the list. If a method succeeds in logging in the visitor, and if auth.settings.login_methods[0]==auth
, Auth
takes the following actions:
- if the user does not exist in
auth_user
, a new user is created and the username/email and passwords are stored. - if the user does exist in
auth_user
but the new accepted password does not match the old stored password, the old password is replaced with the new one (notice that passwords are always stored hashed unless specified otherwise).
If you do not wish to store the new password in auth_user
, then it is sufficient to change the order of login methods, or remove auth
from the list. For example:
from gluon.contrib.login_methods.basic_auth import basic_auth
auth.settings.login_methods = [basic_auth('https://basic.example.com')]
The same applies for any other login method described here.
SMTP and Gmail
You can verify login credentials using a remote SMTP server, for example Gmail; i.e., you log the user in if the email and password they provide are valid credentials to access the Gmail SMTP server (smtp.gmail.com:587
). All that is needed is the following code:
from gluon.contrib.login_methods.email_auth import email_auth
auth.settings.login_methods.append(
email_auth("smtp.gmail.com:587", "@gmail.com"))
The first argument of email_auth
is the address:port of the SMTP server. The second argument is the email domain.
This works with any SMTP server that requires TLS authentication.
PAM
Authentication using Pluggable Authentication Modules (PAM) works as in the previous cases. It allows web2py to authenticate users using the operating system accounts:
from gluon.contrib.login_methods.pam_auth import pam_auth
auth.settings.login_methods.append(pam_auth())
LDAP
Authentication using LDAP works very much as in the previous cases.
To use LDAP login with MS Active Directory:
from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods.append(ldap_auth(mode='ad',
server='my.domain.controller',
base_dn='ou=Users,dc=domain,dc=com'))
To use LDAP login with Lotus Notes and Domino:
auth.settings.login_methods.append(ldap_auth(mode='domino',
server='my.domino.server'))
To use LDAP login with OpenLDAP (with UID):
auth.settings.login_methods.append(ldap_auth(server='my.ldap.server',
base_dn='ou=Users,dc=domain,dc=com'))
To use LDAP login with OpenLDAP (with CN):
auth.settings.login_methods.append(ldap_auth(mode='cn',
server='my.ldap.server', base_dn='ou=Users,dc=domain,dc=com'))
There are additional parameters to let web2py
- read additional data like the username from LDAP
- implement group control
- restrict login access.
See the documentation of ldap_auth
in web2py/gluon/contrib/login_methods/ldap_auth.py
.
Google App Engine
Authentication using Google when running on Google App Engine requires skipping the web2py login form, being redirected to the Google login page, and back upon success. Because the behavior is different than in the previous examples, the API is a little different.
from gluon.contrib.login_methods.gae_google_login import GaeGoogleAccount
auth.settings.login_form = GaeGoogleAccount()
OpenID
We have previously discussed integration with Janrain (which has OpenID support) and that is the easiest way to use OpenID. Yet sometimes you do not want to rely on a third party service and you want to access the OpenID provider directly from the consumer (your app).
Here is an example:
from gluon.contrib.login_methods.openid_auth import OpenIDAuth
auth.settings.login_form = OpenIDAuth(auth)
OpenIDAuth
requires the python-openid module to be installed separately. Under the hood, this login method defines the following table:
db.define_table('alt_logins',
Field('username', length=512, default=''),
Field('type', length =128, default='openid', readable=False),
Field('user', self.table_user, readable=False))
which stores the openid usernames for each user. If you want to display the openids for the current logged in user:
{{=auth.settings.login_form.list_user_openids()}}
OAuth2.0
We have previously discussed integration with Janrain, yet sometimes you do not want to rely on a third party service and you want to access a OAuth2.0 provider directly; for example, Facebook, Linkedin, Twitter, Google all of them provide an OAuth2.0 authentication service. web2py handles the OAuth2.0 flow transparently so that a user can be verified against any configured OAuth2.0 provider during login. Other than authentication an OAuth2.0 provider can grant to any web2py application access to user resources with restricted access thought a proprietary API. Google, Twitter, Facebook and so on, all have APIs that can be easily accessed by a web2py application.
It must be underlined that OAuth2.0 is limited only to authentication and authorization (for instance CAS has more functionalities), this means that each OAuth2.0 provider has a different way to receive a unique id from their user database through one of their APIs. Specific methods are well explained on respective provider documentation, they usually consist in a very simple REST call. This is why for each OAuth2.0 provider there is the need to write a few lines of code.
Before writing any instructions in the application model a first step is needed for any provider: registering a new application; this is usually done on provider’s site and is explained in provider’s documentation.
There are a few things that needs to be known once there is the need to add a new OAuth2.0 provider to your application: 1. the Authorization URI; 2. the Token request URI; 3. the application identification token and secret received upon registration of the new application; 4. the permissions that the provider must grant to the web2py application, i.e. the “scope” (see the provider’s documentation); 5. the API call to receive a UID of the authenticating user, as explained on providers documentation.
Point 1 to 4 are used to initialize the authorization endpoint used by web2py to communicate with the OAuth2.0 provider. The unique id is retrieved by web2py with a call to the get_user() method when needed during the login flow; this is where the API call of point 5 is needed.
These are the essential modification that need to be done in your model: a. import OAuthAccount class; b. define a derived OAuthClass implementation; c. override __init__() method of that class; d. override get_user() method of that class. e. instantiate the class with the data of points 1-4 of the above list;
Once the class is instantiated, and the user is authenticated, the web2py application can access the API of the provider any time by using the OAuth2.0 access token by calling the accessToken() method of that class.
What follows is an example of what can be used with Facebook. This is a basic example using Facebook Graph API, remind that, by writing a proper get_user() method, many different things can be done. The example shows how the OAuth2.0 access token can be used when calling the remote API of the provider.
First of all you must install the Facebook Python SDK.
Second, you need the following code in your model:
## Define oauth application id and secret.
FB_CLIENT_ID='xxx'
FB_CLIENT_SECRET="yyyy"
## import required modules
try:
import json
except ImportError:
from gluon.contrib import simplejson as json
from facebook import GraphAPI, GraphAPIError
from gluon.contrib.login_methods.oauth20_account import OAuthAccount
## extend the OAUthAccount class
class FaceBookAccount(OAuthAccount):
"""OAuth impl for FaceBook"""
AUTH_URL="https://graph.facebook.com/oauth/authorize"
TOKEN_URL="https://graph.facebook.com/oauth/access_token"
def __init__(self):
OAuthAccount.__init__(self, None, FB_CLIENT_ID, FB_CLIENT_SECRET,
self.AUTH_URL, self.TOKEN_URL,
scope='email,user_about_me,user_activities, user_birthday, user_education_history, user_groups, user_hometown, user_interests, user_likes, user_location, user_relationships, user_relationship_details, user_religion_politics, user_subscriptions, user_work_history, user_photos, user_status, user_videos, publish_actions, friends_hometown, friends_location,friends_photos',
state="auth_provider=facebook",
display='popup')
self.graph = None
def get_user(self):
'''Returns the user using the Graph API.
'''
if not self.accessToken():
return None
if not self.graph:
self.graph = GraphAPI((self.accessToken()))
user = None
try:
user = self.graph.get_object("me")
except GraphAPIError, e:
session.token = None
self.graph = None
if user:
if not user.has_key('username'):
username = user['id']
else:
username = user['username']
if not user.has_key('email'):
email = '%s.fakemail' %(user['id'])
else:
email = user['email']
return dict(first_name = user['first_name'],
last_name = user['last_name'],
username = username,
email = '%s' %(email) )
## use the above class to build a new login form
auth.settings.login_form=FaceBookAccount()
We have previously discussed integration with Janrain (which has LinkedIn support) and that is the easiest way to use OAuth. Yet sometime you do not want to rely on a third party service or you may want to access LinkedIn directly to get more information than Janrain provides.
Here is an example:
from gluon.contrib.login_methods.linkedin_account import LinkedInAccount
auth.settings.login_form=LinkedInAccount(request,KEY,SECRET,RETURN_URL)
LinkedInAccount
requires the “python-linkedin” module installed separately.
X509
You can also login by passing to the page an x509 certificate and your credential will be extracted from the certificate. This requires M2Crypto
installed from
http://chandlerproject.org/bin/view/Projects/MeTooCrypto
Once you have M2Cryption installed you can do:
from gluon.contrib.login_methods.x509_auth import X509Account
auth.settings.actions_disabled=['register', 'change_password', 'request_reset_password']
auth.settings.login_form = X509Account()
You can now authenticate into web2py passing your x509 certificate. How to do this is browser-dependent, but probably you are more likely to use certificates for web services. In this case you can use for example cURL
to try out your authentication:
curl -d "firstName=John&lastName=Smith" -G -v --key private.key --cert server.crt https://example/app/default/user/profile
This works out of the box with Rocket (the web2py built-in web server) but you may need some extra configuration work on the web server side if you are using a different web server. In particular you need to tell your web server where the certificates are located on local host and that it needs to verify certificates coming from the clients. How to do it is web server dependent and therefore omitted here.
Multiple login forms
Some login methods modify the login_form, some do not. When they do that, they may not be able to coexist. Yet some coexist by providing multiple login forms in the same page. web2py provides a way to do it. Here is an example mixing normal login (auth) and RPX login (janrain.com):
from gluon.contrib.login_methods.extended_login_form import ExtendedLoginForm
other_form = RPXAccount(request, api_key='...', domain='...', url='...')
auth.settings.login_form = ExtendedLoginForm(auth, other_form, signals=['token'])
If signals are set and a parameter in request matches any signals, it will return the call of other_form.login_form
instead. other_form
can handle some particular situations, for example, multiple steps of OpenID login inside other_form.login_form
.
Otherwise it will render the normal login form together with the other_form
.
Record versioning
You can use Auth to enable full record versioning:
auth.enable_record_versioning(db,
archive_db=None,
archive_names='%(tablename)s_archive',
current_record='current_record'):
This tells web2py to create an archive table for each of the tables in db
and store a copy of each record when modified. The old copy is stored. The new copy is not.
The last three parameters are optional:
archive_db
allows to specify another database where the archive tables are to be stored. Setting it toNone
is the same as setting it todb
.archive_names
provides a pattern for naming each archive table.current_record
specified the name of the reference field to be used in the archive table to refer to the original, unmodified, record. Notice thatarchive_db!=db
then the reference field is just an integer field since cross database references are not possible.
Only tables with modified_by
and modified_on
fields (as created for example by auth.signature) will be archived.
When you enable_record_versioning
, if records have an is_active
field (also created by auth.signature), records will never be deleted but they will be marked with is_active=False
. In fact, enable_record_versioning
adds a common_filter
to every versioned table that filters out records with is_active=False
so they essentially become invisible.
If you enable_record_versioning
, you should not use auth.archive
or crud.archive
else you will end up with duplicate records. Those functions do explicitly what enable_record_versioning
does automatically and they will be deprecated.
Mail
and Auth
You can read more about web2py API for emails and email configuration in Chapter 8. Here we limit the discussion to the interaction between Mail
and Auth
.
Define a mailer with
from gluon.tools import Mail
mail = Mail()
mail.settings.server = 'smtp.example.com:25'
mail.settings.sender = 'you@example.com'
mail.settings.login = 'username:password'
or simply use the mailer provided by auth
:
mail = auth.settings.mailer
mail.settings.server = 'smtp.example.com:25'
mail.settings.sender = 'you@example.com'
mail.settings.login = 'username:password'
You need to replace the mail.settings with the proper parameters for your SMTP server. Set mail.settings.login = None
if the SMTP server does not require authentication. If you don’t want to use TLS, set mail.settings.tls = False
In Auth
, by default, email verification is disabled. To enable email, append the following lines in the model where auth
is defined:
auth.settings.registration_requires_verification = True
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
auth.messages.verify_email = 'Click on the link %(link)s to verify your email'
auth.messages.reset_password = 'Click on the link %(link)s to reset your password'
In the two auth.messages
above, you may need to replace the URL portion of the string with the proper complete URL of the action. This is necessary because web2py may be installed behind a proxy, and it cannot determine its own public URLs with absolute certainty. The above examples (which are the default values) should, however, work in most cases.
Two-step verification
Two-step verification (or Two-factor authentication) is a way of improving authentication security. The setting adds an extra step in the login process. In the first step, users are shown the standard username/password form. If they successfully pass this challenge by submitting the correct username and password, and two-factor authentication is enabled for the user, the server will present a second form before logging them in.
This functionality can be enabled on a per-user basis:
This case is a good example for apps where users can enable/disable two-factor authentication by them self.
This form will ask users for a six-digit code that has been emailed to their accounts (the server emails the code if the username and password was correct). By default the user will 3 attempts to introduce the code. If the code is incorrect after 3 attempts, the second verification step is treated as having failed and the user must complete the first challenge (username/password) again.
- Create a group (also known as a role) for the two-step verification. In this example it will be called
auth2step
and the description may beTwo-step verification
. - Give a user membership of this role.
- Add the following setting in the model where you created and configured your auth object (probably in the model db.py):
auth.settings.two_factor_authentication_group = "auth2step"
- Don’t forget to configure the email server in db.py
This functionality can be enabled for the entire app:
This form will ask users for a six-digit code that has been emailed to their accounts (the server emails the code if the username and password was correct). By default the user will 3 attempts to introduce the code. If the code is incorrect after 3 attempts, the second verification step is treated as having failed and the user must complete the first challenge (username/password) again.
auth.settings.auth_two_factor_enabled = True
This case will effect over all the user in the application. For example, if your office IP is 93.56.854.54 and you don’t want two-factor authentication from your office IP. In your models:
if request.env.remote_addr != '93.56.854.54':
auth.settings.auth_two_factor_enabled = True
Other options that can be applied over the examples before:
Example 1: If you want to send the code by SMS instead of email. In your models write:
def _sendsms(user, auth_two_factor):
#write the process to send the auth_two_factor code by SMS
return auth_two_factor
auth.settings.auth_two_factor_enabled = True
auth.messages.two_factor_comment = "Your code have been sent by SMS"
auth.settings.two_factor_methods = [lambda user, auth_two_factor: _sendsms(user, auth_two_factor)]
For def _sendsms(...)
receive two values: user and auth_two_factor:
- user: it is a row with all his parameters. You can access them: user.email, user.first_name, etc.
- auth_two_factor: string that contains the authentication code.
Note that in case you want to send an SMS, you will need to add extra field, for example phone
in your user table. In this case you can access to the phone field as user.phone
. More info how to send an SMS with web2py Emails-and-SMS
Example 2: If you want to send the code by SMS and create or own code:
def _sendsms(user, auth_two_factor):
auth_two_factor = #write your own algorithm to generate the code.
#write the process to send the auth_two_factor code by SMS
return auth_two_factor
auth.settings.two_factor_methods = [lambda user, auth_two_factor: _sendsms(user, auth_two_factor)]
Example 3: The code is generated by a external client. For example Mobile OTP Client:
MOTP (Mobile one time password) allows you to login with a one time password (OTP) generated on a motp client, motp clients are available for practically all platforms. To know more about OTP visit wiki-One-time-password to know more visit MOTP
For the next example we will use DroidOTP. It is a free app and it can be found in Play Store for Android. Once you have installed:
- Create a new profile, for example
test
- Initialize a secret key shaking your phone.
In your models copy and paste:
#Before define tables, we add some extra field to auth_user
auth.settings.extra_fields['auth_user'] = [
Field('motp_secret', 'password', length=512, default='', label='MOTP Secret'),
Field('motp_pin', 'string', length=128, default='', label='MOTP PIN')]
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.
# This will avoid to use the default setting and send a code by email.
def _set_two_factor(user, auth_two_factor):
return None
def verify_otp(user, otp):
import time
from hashlib import md5
epoch_time = int(time.time())
time_start = int(str(epoch_time - OFFSET)[:-1])
time_end = int(str(epoch_time + OFFSET)[:-1])
for t in range(time_start - 1, time_end + 1):
to_hash = str(t) + user.motp_secret + user.motp_pin
hash = md5(to_hash).hexdigest()[:6]
if otp == hash:
return hash
auth.settings.auth_two_factor_enabled = True
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_onvalidation = [lambda user, otp: verify_otp(user, otp)]
The secret key generated before with your phone need to be introduced into motp_secret
field. The secret should be not reused, for security reasons. Choose one PIN. It can be numbers, letters or a mix. Go to your phone, choose your profile and type the PIN you have introduced before in the form. You got the authenticator code to use in your app!!
Note that for this way of two-factor authentication phone and server (where web2py app is hosted) need to be synchronized (on time). They can be in a different time zone. This is because the OTP use Unix time stamp. It tracks the time as a running total of seconds.
Some extra parameters for configuration:
Set your custom attempts to login:
auth.setting.auth_two_factor_tries_left = 3
Message to return in case the code is incorrect:
auth.messages.invalid_two_factor_code = 'Incorrect code. {0} more attempt(s) remaining.'
To customize the email template:
auth.messages.retrieve_two_factor_code='Your temporary login code is {0}'
auth.messages.retrieve_two_factor_code_subject='Your temporary login code is {0}'
To customize two-factor form:
auth.messages.label_two_factor = 'Authentication code'
auth.messages.two_factor_comment = 'The code was emailed to you and is required for login.'