Browse Source

converted groups to the new exception format

master
Julio Biason 11 years ago
parent
commit
cae4728100
  1. 57
      luncho/blueprints/groups.py
  2. 23
      luncho/blueprints/token.py
  3. 18
      luncho/blueprints/users.py
  4. 8
      luncho/exceptions.py
  5. 23
      luncho/helpers.py

57
luncho/blueprints/groups.py

@ -12,13 +12,40 @@ from flask import jsonify
from sqlalchemy.exc import IntegrityError
from luncho.helpers import ForceJSON
from luncho.helpers import JSONError
from luncho.helpers import user_or_error
from luncho.helpers import user_from_token
from luncho.server import User
from luncho.server import Group
from luncho.server import db
from luncho.exceptions import LunchoException
from luncho.exceptions import ElementNotFoundException
class AccountNotVerifiedException(LunchoException):
"""The account isn't verified."""
def __init__(self):
super(AccountNotVerifiedException, self).__init__()
self.status = 412
self.message = 'Account not verified'
class NewMaintainerDoesNotExistException(LunchoException):
"""The account for the new maintainer does not exist."""
def __init__(self):
super(NewMaintainerDoesNotExistException, self).__init__()
self.status = 401
self.message = 'New maintainer not found'
class UserIsNotAdminException(LunchoException):
"""The user is not the admin of the group."""
def __init__(self):
super(UserIsNotAdminException, self).__init__()
self.status = 401
self.message = 'User is not admin'
groups = Blueprint('groups', __name__)
LOG = logging.getLogger('luncho.blueprints.groups')
@ -45,14 +72,11 @@ def user_groups(token):
@ForceJSON(required=['name'])
def create_group(token):
"""Create a new group belonging to the user."""
(user, error) = user_or_error(token)
if error:
return error
user = user_from_token(token)
LOG.debug('User status: {verified}'.format(verified=user.verified))
if not user.verified:
return JSONError(412, 'Account not verified')
raise AccountNotVerifiedException()
json = request.get_json(force=True)
new_group = Group(name=json['name'],
@ -72,13 +96,10 @@ def create_group(token):
@ForceJSON()
def update_group(token, groupId):
"""Update group information."""
(user, error) = user_or_error(token)
if error:
return error
user = user_from_token(token)
group = Group.query.get(groupId)
if not group:
return JSONError(404, 'Group not found')
raise ElementNotFoundException('Group')
LOG.debug('Group = {group}'.format(group=group))
@ -89,7 +110,8 @@ def update_group(token, groupId):
if 'maintainer' in json:
new_maintainer = User.query.get(json['maintainer'])
if not new_maintainer:
return JSONError(401, 'New maintainer not found')
raise NewMaintainerDoesNotExistException()
group.owner = new_maintainer.username
db.session.commit()
@ -99,16 +121,13 @@ def update_group(token, groupId):
@groups.route('<token>/<groupId>/', methods=['DELETE'])
def delete_group(token, groupId):
"""Delete a group."""
(user, error) = user_or_error(token)
if error:
return error
user = user_from_token(token)
group = Group.query.get(groupId)
if not group:
return JSONError(404, 'Group not found')
raise ElementNotFoundException('Group')
if not group.owner == user.username:
return JSONError(401, 'User is not admin')
raise UserIsNotAdminException()
db.session.delete(group)
db.session.commit()

23
luncho/blueprints/token.py

@ -8,11 +8,28 @@ from flask import jsonify
from flask import request
from luncho.helpers import ForceJSON
from luncho.helpers import JSONError
from luncho.server import User
from luncho.server import db
from luncho.exceptions import LunchoException
class UserDoesNotExistException(LunchoException):
"""There is no such user in the database."""
def __init__(self):
super(UserDoesNotExistException, self).__init__()
self.status = 404
self.message = 'User does not exist'
class InvalidPasswordException(LunchoException):
"""Invalid password."""
def __init__(self):
super(InvalidPasswordException, self).__init__()
self.status = 401
self.message = 'Invalid password'
token = Blueprint('token', __name__)
@token.route('', methods=['POST'])
@ -24,10 +41,10 @@ def get_token():
user = User.query.filter_by(username=json['username']).first()
if user is None:
return JSONError(404, 'User does not exist')
raise UserDoesNotExistException()
if not user.passhash == json['password']:
return JSONError(401, 'Invalid password')
raise InvalidPasswordException()
return jsonify(status='OK',
token=user.get_token())

18
luncho/blueprints/users.py

@ -12,7 +12,7 @@ from flask import jsonify
from sqlalchemy.exc import IntegrityError
from luncho.helpers import ForceJSON
from luncho.helpers import JSONError
from luncho.helpers import user_from_token
from luncho.server import User
from luncho.server import db
@ -61,13 +61,7 @@ def update_user(token):
Any other field will be ignored; only fields that need to be changed
must be send."""
json = request.get_json(force=True)
user = User.query.filter_by(token=token).first()
if not user:
return JSONError(404, 'User not found (via token)')
if not user.valid_token(token):
return JSONError(400, 'Invalid token')
user = user_from_token(token)
if 'full_name' in json:
LOG.debug('Fullname = {fullname}'.format(fullname=json['full_name']))
@ -84,13 +78,7 @@ def update_user(token):
@users.route('<token>/', methods=['DELETE'])
def delete_user(token):
"""Delete a user. No confirmation is send."""
user = User.query.filter_by(token=token).first()
if not user:
return JSONError(404, 'User not found (via token)')
if not user.valid_token(token):
return JSONError(400, 'Invalid token')
user = user_from_token(token)
db.session.delete(user)
db.session.commit()
return jsonify(status='OK')

8
luncho/exceptions.py

@ -53,3 +53,11 @@ class UserNotFoundException(LunchoException):
super(UserNotFoundException, self).__init__()
self.status = 404
self.message = 'User not found (via token)'
class ElementNotFoundException(LunchoException):
"""The requested element does not exist."""
def __init__(self, element_name):
super(ElementNotFoundException, self).__init__()
self.status = 404
self.message = '{element} not found'.format(element=element_name)

23
luncho/helpers.py

@ -40,26 +40,7 @@ class ForceJSON(object):
return check_json
def JSONError(status, message, **kwargs):
"""Generate a JSON error message with the error and extra fields.
:param status: the HTTP status code for the error
:type status: int
:param message: The message in the error
:type message: str
:param kwargs: Extra fields to be added in the response. *Note*: `status`
and `message` should **NOT** be used.
:type kwargs: kwargs
:return: A response with the JSON and the status code."""
resp = jsonify(status='ERROR',
message=message,
**kwargs)
resp.status_code = status
return resp
def user_or_error(token):
def user_from_token(token):
"""Returns a tuple with the user that owns the token and the error. If the
token is valid, user will have the user object and error will be None; if
there is something wrong with the token, the user will be None and the
@ -76,4 +57,4 @@ def user_or_error(token):
if not user.valid_token(token):
raise InvalidTokenException()
return (user, None)
return user

Loading…
Cancel
Save