Hi,
I have had a lot of problems to set up an API REST with basic auth, finally
I have used the next code, I left it here for anyone that may need it:
from gluon.serializers import json
auth.settings.allow_basic_login = True
@request.restful()
def api():
response.view = 'generic.json'
response.headers["Access-Control-Allow-Origin"] = '*'
response.headers['Access-Control-Max-Age'] = 86400
response.headers['Access-Control-Allow-Headers'] = '*'
response.headers['Access-Control-Allow-Methods'] = '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
@auth.requires_login()
def GET(id):
return json(get_post_if_user_belongs_to_blog(id, auth))
@auth.requires_login()
def PUT(id, **fields):
return get_post_if_user_belongs_to_blog(id,
auth).update_record(**fields)
@auth.requires_login()
def POST(*args, **fields):
return db.posts.validate_and_insert(blog_id=auth.user.blog_id,
user_id=auth.user.id, **fields)
@auth.requires_login()
def DELETE(id):
get_post_if_user_belongs_to_blog(id, auth).delete_record()
return dict(action="deleted", status="ok", id=id)
def OPTIONS(args, **vars):
print 'doing post options'
headers = {"Access-Control-Allow-Origin": '*',
'Access-Control-Max-Age': 86400,
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Credentials': 'true'}
raise HTTP(200, **headers)
return locals()
def get_post_if_user_belongs_to_blog(id, auth):
my_post = db.posts[id]
if my_post.blog_id != auth.user.blog_id:
return 'not authorized'
return my_post
Forget about most part of the code and pay attention to annotations.
Maybe I am not 100% right in all the approach, but this is what I have
needed:
- OPTIONS need to be without authentication, so I have removed
@auth.requires_login from main methond (def api()) and I have annotated the
GET,PUT,POST and DELETE methods.
- I have needed to set up headers on OPTIONS too, for avoiding CORS issues
I hope that this can helps to anybody. I plan to move basic auth to JWT or
another auth method.
Thanks!
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.