Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored services #2

Merged
merged 1 commit into from
May 16, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
78 changes: 42 additions & 36 deletions happycube/auth/services.py
Original file line number Diff line number Diff line change
@@ -1,54 +1,60 @@
from happycube.service import BaseService
from happycube.users.services import user_service
from happycube.errors import HTTPError
from happycube.users.models import User
from flask import g, request
import jwt


class AuthService(object):
def get_authenticated_user(login, password):
user = User.first(name=login)
if user and user.check_password(password):
return user
else:
return None

def get_authenticated_user(self, login, password):
user = user_service.first(name=login)
if user and user.check_password(password):
return user
else:
return None

def name_available(login):
user = User.first(name=login)
if user is None:
return True
else:
return False

def verify_jwt(self):
"""Does the actual work of verifying the JWT data in the current request.
"""
auth = request.headers.get('Authorization', None)

if auth is None:
raise HTTPError(401, 'Authorization header was missing')
def register_new_user(login, password):
return User.create(name=login, password=password)

segments = auth.split()

if segments[0].lower() != 'bearer':
raise HTTPError(401, 'Authorization header format is \'Bearer TOKEN\'')
elif len(segments) == 1:
raise HTTPError(401, 'Token missing')
elif len(segments) > 2:
raise HTTPError(401, 'Token invalid')
def verify_jwt():
"""Does the actual work of verifying the JWT data in the current request.
"""
auth = request.headers.get('Authorization', None)

try:
payload = jwt.decode(segments[1], 'secret') # TODO: make secret key secret
except jwt.ExpiredSignatureError:
raise HTTPError(401, 'Token expired')
except jwt.DecodeError:
raise HTTPError(401, 'Token invalid')
if auth is None:
raise HTTPError(401, 'Authorization header was missing')

try:
g.user = user_service.get(payload.get('user_id'))
except:
raise HTTPError(401, 'User does not exist')
segments = auth.split()

return None
if segments[0].lower() != 'bearer':
raise HTTPError(401, 'Authorization header format is \'Bearer TOKEN\'')
elif len(segments) == 1:
raise HTTPError(401, 'Token missing')
elif len(segments) > 2:
raise HTTPError(401, 'Token invalid')

try:
payload = jwt.decode(segments[1], 'secret') # TODO: make secret key secret
except jwt.ExpiredSignatureError:
raise HTTPError(401, 'Token expired')
except jwt.DecodeError:
raise HTTPError(401, 'Token invalid')

try:
g.user = User.get(payload.get('user_id'))
except:
raise HTTPError(401, 'User does not exist')

def issue_jwt(self, user):
return jwt.encode({'user_id': user.id}, 'secret')
return None


auth_service = AuthService()
def issue_jwt(user):
return jwt.encode({'user_id': user.id}, 'secret')
34 changes: 31 additions & 3 deletions happycube/auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,49 @@
from happycube.decorators.validation import validate
from happycube.decorators.rate_limit import limit

from happycube.auth.services import auth_service
from happycube.auth.services import (
get_authenticated_user,
issue_jwt,
name_available,
register_new_user
)

blueprint = Blueprint('auth', __name__, url_prefix='/api/v0/auth')

@blueprint.route('/login/', methods = ['POST'])
def login():
payload = request.get_json()
user = auth_service.get_authenticated_user(payload['login'], payload['password'])
user = get_authenticated_user(payload['login'], payload['password'])

if user:
token = auth_service.issue_jwt(user)
token = issue_jwt(user)
ret = {
'token': token.decode('utf-8')
}

return jsonify(ret)
else:
raise HTTPError(401, 'Login failed')


@blueprint.route('/sign-up/', methods = ['POST'])
def sign_up():
payload = request.get_json()
if name_available(payload['login']):
register_new_user(payload['login'], payload['password'])

ret = {}

return jsonify(ret)
else:
raise HTTPError(403, 'Username already exists')


@blueprint.route('/logout/', methods = ['POST'])
def logout():

ret = {
'message': 'Logout successful'
}

return jsonify(ret)
4 changes: 2 additions & 2 deletions happycube/decorators/auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from functools import wraps
from happycube.auth.services import auth_service
from happycube.auth.services import verify_jwt

def jwt_required():
"""View decorator that requires a valid JWT token to be present in the request
Expand All @@ -8,7 +8,7 @@ def jwt_required():
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
auth_service.verify_jwt()
verify_jwt()
return fn(*args, **kwargs)
return decorator
return wrapper
Expand Down
9 changes: 4 additions & 5 deletions happycube/solves/services.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from happycube.service import BaseService
from happycube.solves.models import Solve

def get_all_solves():
return Solve.all()

class SolveService(BaseService):
__model__ = Solve

solve_service = SolveService()
def create_solve(payload):
Solve.create(**payload)
6 changes: 3 additions & 3 deletions happycube/solves/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from happycube.decorators.rate_limit import limit
from happycube.decorators.auth import jwt_required

from happycube.solves.services import solve_service
from happycube.solves.services import get_all_solves, create_solve
from happycube.solves.serializer import serialize

import json
Expand All @@ -22,7 +22,7 @@
@jwt_required()
def index():

solves = solve_service.all()
solves = get_all_solves()

ret = [serialize(x) for x in solves]

Expand All @@ -37,7 +37,7 @@ def create():
payload = request.get_json()
payload['user_id'] = g.user.id

new_solve = solve_service.create(**payload)
new_solve = create_solve(**payload)

return json.dumps(serialize(new_solve))

8 changes: 0 additions & 8 deletions happycube/users/services.py

This file was deleted.