def test_given_valid_auth_header_when_calling_login_then_token_is_returned():
    # given
    mock_user_collection = Mock()
    mock_whitelisted_collection = Mock()
    mock_user_collection.find_one.return_value = {
        # hashed version of 'test' with salt
        'password':
        "******",
        'name': 'dummy_name',
        '_id': 'some_id'
    }

    auth_service = AuthService(mock_user_collection,
                               mock_whitelisted_collection, mock_private_key,
                               jwt)

    # when
    token = auth_service.login({"username": '******', 'password': '******'})

    # then
    data = jwt.decode(token, mock_public_key, algorithm='RS256')
    assert 'some_id' == data['public_id']
    assert data['exp'] is not None

    # hashed version, no salt for 'test'
    print data['key'] == "xzwXZ2CoOI8Z/2QH"
    mock_user_collection.find_one.assert_called_once_with({'name': 'test'})
Ejemplo n.º 2
0
    def __init__(self, config, api_url, user_agent, auth_url, client_id, client_secret, grant_type, scope):
        self.config = config
        self.config.load()

        self.api_url = api_url
        self.user_agent = user_agent

        AuthService.__init__(self, auth_url, client_id, client_secret, grant_type, scope)
Ejemplo n.º 3
0
    def __init__(self, config, api_url, user_agent, auth_url, client_id,
                 client_secret, grant_type, scope):
        self.config = config
        self.config.load()

        self.api_url = api_url
        self.user_agent = user_agent

        AuthService.__init__(self, auth_url, client_id, client_secret,
                             grant_type, scope)
def test_given_not_registered_user__when_calling_login_then_UnrecognisedUserException_is_returned(
):
    # given
    mock_user_collection = Mock()
    mock_whitelisted_collection = Mock()
    mock_user_collection.find_one.return_value = False
    auth_service = AuthService(mock_user_collection,
                               mock_whitelisted_collection, mock_private_key,
                               jwt)

    # then
    with raises(UnrecognisedUserException):
        auth_service.login({'username': '******', "password": '******'})
Ejemplo n.º 5
0
def game_likes(request, game_id=None):
  if (request.method == 'GET'):
    game_likes = GameLike.objects.filter(game_id=game_id)
    return HttpResponse(serializers.serialize('json', game_likes), content_type='application/json')

  if (request.method == 'POST'):
    if (AuthService.authenticate(request)):
      payload      = AuthService.getPayload(request.META['HTTP_AUTHORIZATION'])
      current_user = User.objects.get(id=payload.get('id'))
      json_data    = json.loads(request.body.decode(encoding='UTF-8'))
      game_id      = json_data.get('game_id', None)

      with transaction.atomic():
        if (not GameLike.objects.filter(game_id=game_id, user_id=current_user.id).exists() or not current_user is None or not game_id is None):
          GameLike.objects.create(game_id=game_id, user_id=current_user.id)

          game                = Game.objects.get(id=game_id)
          current_like_count  = game.game_likes_count
          current_like_count += 1
          Game.objects.filter(id=game_id).update(game_likes_count=current_like_count)

          return HttpResponse(json.dumps({'result': True}), content_type='application/json')
        else:
          return HttpResponse('Unauthorized', status=401)
    else:
      return HttpResponse('Unauthorized', status=401)

  if (request.method == 'DELETE'):
    if (AuthService.authenticate(request)):
      payload      = AuthService.getPayload(request.META['HTTP_AUTHORIZATION'])
      current_user = User.objects.get(id=payload.get('id'))
      json_data    = json.loads(request.body.decode(encoding='UTF-8'))
      game_id      = json_data.get('game_id', None)

      with transaction.atomic():
        if (GameLike.objects.filter(game_id=game_id, user_id=current_user.id).exists() or not current_user is None or not game_id is None):
          GameLike.objects.filter(game_id=game_id, user_id=current_user.id).delete()

          game               = Game.objects.get(id=game_id)
          current_like_count = game.game_likes_count
          if (current_like_count > 0):
            current_like_count -= 1
            Game.objects.filter(id=game_id).update(game_likes_count=current_like_count)

          return HttpResponse(json.dumps({'result': True}), content_type='application/json')
        else:
          return HttpResponse('Unauthorized', status=401)
    else:
      return HttpResponse('Unauthorized', status=401)
def test_given_whitelisted_and_not_registerd_before_user_when_calling_register_then_user_is_registerd(
):
    # given
    mock_user_collection = Mock()
    mock_user_collection.find_one.return_value = False

    mock_whitelisted_collection = Mock()
    mock_whitelisted_collection.find_one.return_value = True

    auth_service = AuthService(mock_user_collection,
                               mock_whitelisted_collection, mock_private_key,
                               jwt)

    # when
    status = auth_service.register("test", "password")

    # then
    assert status is True
def test_given_invalid_password_when_calling_login_then_WrongPasswordException_is_returned(
):
    # given
    mock_user_collection = Mock()
    mock_whitelisted_collection = Mock()
    mock_user_collection.find_one.return_value = {
        # hashed version of 'test' with salt
        'password':
        "******",
        '_id': 'some_id'
    }
    auth_service = AuthService(mock_user_collection,
                               mock_whitelisted_collection, mock_private_key,
                               jwt)

    # then
    with raises(WrongPasswordException):
        auth_service.login({'username': '******', "password": '******'})
def test_given_invalid_header_when_calling_login_then_MissingAuthHeaderException_is_returned(
):
    # given
    mock_user_collection = Mock()
    mock_whitelisted_collection = Mock()
    auth_service = AuthService(mock_user_collection,
                               mock_whitelisted_collection, mock_private_key,
                               jwt)

    # then
    with raises(MissingAuthHeaderException):
        auth_service.login({"password": '******'})

    with raises(MissingAuthHeaderException):
        auth_service.login({"username": '******'})

    with raises(MissingAuthHeaderException):
        auth_service.login(None)
Ejemplo n.º 9
0
def users(request):
  if (request.method == 'POST'):
    cipher    = AesService(AesService.secret_key)
    json_data = json.loads(request.body.decode(encoding='UTF-8'))
    username  = json_data.get('username', None)
    password  = cipher.encrypt(json_data.get('password', None))

    if (username is None or password is None):
      return HttpResponse('Unauthorized', status=401)
    else:
      if (not User.objects.filter(username=username, password=password).exists()):
        user  = User.objects.create(username=username, password=password)
        token = AuthService.getToken(user)

        return HttpResponse(json.dumps({'token': token}), content_type='application/json')
      else:
        return HttpResponse('Unauthorized', status=401)
Ejemplo n.º 10
0
def login(request):
  if (request.method == 'GET'):
    cipher   = AesService(AesService.secret_key)
    username = request.GET.get('username', None)
    password = request.GET.get('password', None)

    if (not username is None and not password is None):
      try:
        user  = User.objects.get(username=username)

        if (password == cipher.decrypt(user.password).decode(encoding='UTF-8')):
          token = AuthService.getToken(user)
          return HttpResponse(json.dumps({'token': token}), content_type='application/json')
        else:
          return HttpResponse('Unauthorized', status=401)
      except ObjectDoesNotExist:
        return HttpResponse('Unauthorized', status=401)
    else:
      return HttpResponse('Unauthorized', status=401)
Ejemplo n.º 11
0
import cherrypy
from auth_service import AuthService
from user_service import UserService
from subaccount_service import SubaccountService
from category_service import CategoryService
from currency_service import CurrencyService
from transaction_service import TransactionService
from csv_service import CSVService
from config import WITH_AUTHENTICATION, WITHOUT_AUTHENTICATION, CHERRYPY_CONFIG_DEFAULT


if __name__ == '__main__':
    cherrypy.config.update(CHERRYPY_CONFIG_DEFAULT)

    cherrypy.tree.mount(AuthService(), '/api/auth', WITHOUT_AUTHENTICATION)
    cherrypy.tree.mount(UserService(), '/api/user', WITH_AUTHENTICATION)
    cherrypy.tree.mount(SubaccountService(), '/api/subaccounts', WITH_AUTHENTICATION)
    cherrypy.tree.mount(CategoryService(), '/api/categories', WITH_AUTHENTICATION)
    cherrypy.tree.mount(TransactionService(), '/api/transactions', WITH_AUTHENTICATION)
    cherrypy.tree.mount(CurrencyService(), '/api/currency', WITH_AUTHENTICATION)
    cherrypy.tree.mount(CSVService(), '/api/csv', WITH_AUTHENTICATION)

    cherrypy.engine.start()
    cherrypy.engine.block()