The module allows you to:
It also includes default pages to login, generate a password-reset token, email the token and set a new password after the token is validated.
Create the following tables:
CREATE TABLE user (
user_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_login varchar(64) NOT NULL,
user_password varchar(255) NOT NULL,
user_email varchar(64), # Optional, see settings
user_status varchar(16) NOT NULL DEFAULT 'active',
user_last_login datetime NOT NULL
)
CREATE TABLE permission (
permission_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
permission_codename varchar(50), # Example: 'can_vote'
permission_desc varchar(50) # Example: 'Can vote in elections'
)
CREATE TABLE user_permission (
up_user_id int REFERENCES user (user_id),
up_permission_id int REFERENCES permission (permission_id),
PRIMARY KEY (up_user_id, up_permission_id)
)
Use in your code:
import web
from web.contrib.auth import DBAuth
urls = (
'/', 'index',
)
app = web.application(urls, locals())
db = web.database(dbn='mysql', db='webpy', user='scott', pw='tiger')
settings = {}
auth = DBAuth(app, db, **settings)
The system will create and use a DiskStore session. If you want to use an existing one or another type of session, you pass it as an argument.
mysession = web.session.Session(app, web.session.DiskStore('sessions'))
auth = DBAuth(app, db, mysession, **settings)
Once you have an DBAuth instance a number of methods are available on that object:
Examples:
Limiting access to authenticated users
class somePage:
@auth.protected()
def GET(self):
...
Limiting access to users with a specific permission
class somePage:
@auth.protected(perm='can_edit')
def GET(self):
...
Limiting access to users who pass a test
def over18(user):
return user.age > 18
class somePage:
@auth.protected(test=over18)
def GET(self):
...
If the user isn't authorized it'll be redirected to settings.url_login ('/login' by default).
user = auth.authenticate(login='john', password='secret')
if not user:
return 'That's correct'
else:
return 'Wrong!'
This function does not log in the user. Use auth.login() for that.By default the system will map a login, logout and password-reset pages. This can be disabled in the settings.
render = web.template.render('/templates')
settings = dict(
template_login = render.mylogin,
)
auth = DBAuth(app, db, **settings)
If None, the default template will be used. See web/contrib/auth/templates/login.html