I am pretty new to Bottle and Cork. I am working on a web app using Bottle as the framework and MongoDB as the backend. I am trying to figure out how to implement a user-login system using Cork.
I read documents and examples of Cork, and I tried to set things up. I have successfully hooked up the cork instance with Mongodb because I saw the database name, which I passed into the Cork() constructor as a parameter(backend), showed up in mongo shell. But then I have no idea how to keep going.
I read all the Cork methods' source code and they all make sense to me. But a lot of them require to have a user with enough role level to be called like "list_roles()" or "create_users()". I understand that they are designed to be called by admin. But my question is how can I get started to create some users and test things out when I initially have no users at all?
The following is what I got so far, and I just need some simple guidance or sample code to start. I would really appreciate any help!
filename: api.py
from cork import Cork
from cork.backends import MongoDBBackend
from bottle import Bottle, redirect, static_file, request, response,HTTPResponse, HTTPError, abort, debug,run, route
import bottle
from beaker.middleware import SessionMiddleware
import pymongo
session_opts = {
'session.type': 'cookie',
'session.validate_key': True,
'session.cookie_expires': True,
'session.timeout': 3600 * 24, # 1 day
'session.encrypt_key': 'lxy3344',
}
app = bottle.app()
app = SessionMiddleware(app, session_opts)
mb = MongoDBBackend(db_name='corkTry')
aaa = Cork(backend=mb, email_sender='[email protected]')
def postd():
return bottle.request.forms
def post_get(name, default=''):
return bottle.request.POST.get(name, default).strip()
# LOGIN # # LOGIN # # LOGIN # # LOGIN # # LOGIN # # LOGIN # # LOGIN #
@bottle.route('/')
@bottle.get('/login')
def login():
print aaa.current_user()
redirect('/static/login.html')
@bottle.post('/login')
def login():
print 'in post login'
"""Authenticate users"""
username = post_get('username')
password = post_get('password')
aaa.login(username, password, success_redirect='/home', fail_redirect='/login')
# REGISTER # # REGISTER # # REGISTER # # REGISTER # # REGISTER # # REGISTER #
@bottle.get('/register')
def register():
redirect('/static/register.html')
@bottle.post('/register')
def register():
# Send out register email
aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
return 'Please check your mailbox.'
@bottle.route('/validate_registration/:registration_code')
def validate_registration(registration_code):
# Validate registration, create user account
aaa.validate_registration(registration_code)
return 'Thanks. <a href="/login">Go to login</a>'
@bottle.route('/static/<filepath:path>',method='GET')
def serve_static(filepath):
return static_file(filepath, root='./static/' )
@bottle.route('/home')
def home():
return '''This is the home page'''
bottle.debug(True)
bottle.run(app=app,reloader = True)
Well I have never expected that the first answer I'm gonna post on Stackoverflow is the answer to my own question, but I just happened to figure it out and I really wanna share it!!
My very first problem was that I have no idea how to create the very first user in the Mongodb database in order to test out the functions that Cork has. The first thing I tried was to call the register() method that Cork provides. But it raised exception because I did not have any roles defined in the database. Therefore I need to first create the roles in the database.
I used the code I found at this link:
https://github.com/FedericoCeratto/bottle-cork/blob/master/examples/simple_webapp_using_mongodb.py
I just copied the method into my code:
def populate_mongodb_backend():
mb = MongoDBBackend(db_name='corkTry', initialize=True)
# mb.users._coll.insert({
# "login": "admin",
# "email_addr": "[email protected]",
# "desc": "admin test user",
# "role": "admin",
# "hash": "cLzRnzbEwehP6ZzTREh3A4MXJyNo+TV8Hs4//EEbPbiDoo+dmNg22f2RJC282aSwgyWv/O6s3h42qrA6iHx8yfw=",
# "creation_date": "2012-10-28 20:50:26.286723"
# })
mb.roles._coll.insert({'role': 'admin', 'val': 100})
mb.roles._coll.insert({'role': 'editor', 'val': 60})
mb.roles._coll.insert({'role': 'user', 'val': 50})
return mb
(I don't want to create the admin user directly using the code that I commented out above because if I did it that way, I would not be able to know the password easily, the hash was passed in directly, so I would not be able to login that user)
(However, if you would like to create the user directly using the code that I commented out above, there is a way to do it. You just need to use the same hash method as Cork used in its source code. Just pass in your password into the hash method and print out the returned hash. Then pass the hash into the following commented out code to create the user. In that way you will know the password and be able to login the user you created)
Then execute the method (just once!) to create the roles in the database:
populate_mongodb_backend()
Then execute the register method that Cork provides to register a new user:
aaa.register('yourLogin','yourPassword','[email protected]',email_template='./views/registration_email.tpl')
registration_email.tpl:
<p>Hi {{username}}! Click <a href="localhost:8080/validate_registration/{{registration_code}}">HERE</a> to finish your registration</p>
Then the user should show in the "pending_registrations" in Mongodb, you can check that by execute the following in mongo shell:
use corkTry
db.pending_registrations.find()
Then you just need to go to your email and click the link to finish the registration,then you can check in Mongodb by executing:
db.users.find()
ADDITIONAL INFO for setting up the email sending(I only tried Gmail):
You need to first make sure that IMAP is enabled for your Gmail account,and then set it up as the following:
smtp_url='starttls://yourGmailUsername:[email protected]:587'
aaa = Cork(backend=mb, email_sender='[email protected]',smtp_url=smtp_url)
You can refer to the following issue for more details, it is where I found the information about the email setting:
https://github.com/FedericoCeratto/bottle-cork/issues/57
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With