def test_create_user_should_return_token(self):
     resp = self.simulate_post('/user')
     self.assertIn('token', resp.json)
     token = resp.json.get('token')
     hash = UserModel.generate_token_hash(token)
     user = UserModel.get(UserModel.token_hash == hash)
     self.assertEqual(user.token_hash, hash)
def tasks_taskLists(event, context):
  """
  userが属するtasksおよびtaskListsを返す
  """
  try:
    logger.info(event)
    if not event['pathParameters']:
      raise errors.BadRequest('Bad request')
    user_id = event['pathParameters']['id']
    
    # userを取得
    try:
      user = UserModel.get(user_id)
    except UserModel.DoesNotExist:
      raise errors.NotFound('The user does not exist')
    
    # userの参加するtasksを取得
    try:
      tasks = user.get_tasks()
    except ScanError as e:
      logger.exception(e)
      raise errors.InternalError('Internal server error')

    # taskListIdでグループ化
    tasks_group = {}
    for task in tasks:
      if task.taskListId in tasks_group:
        tasks_group[task.taskListId].append(task)
      else:
        tasks_group[task.taskListId] = [task]
    
    # taskListsを取得
    task_lists = []
    for task_list_id in tasks_group.keys():
      try:
        task_list = TaskListModel.get(task_list_id)
      except TaskListModel.DoesNotExist as e:
        logger.exception(e)
        continue
      except GetError as e:
        logger.exception(e)
      task_lists.append(task_list)

    # 結果の整形
    task_lists = [dict(task_list) for task_list in task_lists]
    for task_list in task_lists:
      task_list['tasks'] = [dict(task) for task in tasks_group[task_list['id']]]

    return {
        'statusCode': 200,
        'headers': {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json'
        },
        'body': json.dumps(
          {
            'statusCode': 200,
            'userId': user_id,
            'taskLists': task_lists
          }
        )
      }

  except errors.BadRequest as e:
    logger.exception(e)
    return build_response(e, 400)

  except errors.NotFound as e:
    logger.exception(e)
    return build_response(e, 404)

  except errors.InternalError as e:
    logger.exception(e)
    return build_response(e, 500)
Beispiel #3
0
def delete(event, context):
    """
  userを削除
  また参加しているtaskのuserIdsから自身を取り除く
  """
    try:
        logger.info(event)
        if not event['pathParameters']:
            raise errors.BadRequest('Bad request')
        user_id = event['pathParameters']['id']

        # user_idがauthorized_userのものか検証
        if user_id != event['requestContext']['authorizer']['authorizedUserId']:
            raise errors.ForbiddenError('Access denied')

        # userの取得
        try:
            user = UserModel.get(user_id)
        except UserModel.DoesNotExist:
            raise errors.NotFound('The user does not exist')

        # userが参加するtaskの取得
        try:
            tasks = user.get_tasks()
        except ScanError as e:
            logger.exception(e)
            raise errors.InternalError('Internal server error')

        # userが参加するtaskのuserIdsからuser_idを削除
        for task in tasks:
            try:
                task.update([TaskModel.userIds.delete([user_id])])
            except UpdateError as e:
                logger.exception(e)
                raise errors.InternalError('Internal server error')

        # userを削除
        try:
            user.logic_delete()
        except UpdateError as e:
            logger.exception(e)
            raise errors.InternalError('Internal server error')

        return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            'body': json.dumps({'statusCode': 200})
        }

    except errors.BadRequest as e:
        logger.exception(e)
        return build_response(e, 400)

    except errors.NotFound as e:
        logger.exception(e)
        return build_response(e, 404)

    except errors.InternalError as e:
        logger.exception(e)
        return build_response(e, 500)
Beispiel #4
0
def update(event, context):
    """
  userの更新
  updateでの更新対象はemail, name, phoneNumberのみ
  """
    try:
        logger.info(event)
        if not (event['body'] and event['pathParameters']):
            raise errors.BadRequest('Bad request')

        data = json.loads(event['body'])
        # dataから不要なattributeを削除
        data = {
            k: v
            for k, v in data.items() if k in ['name', 'email', 'phoneNumber']
        }
        if not data:
            raise errors.BadRequest('Bad request')
        user_id = event['pathParameters']['id']

        # user_idがauthorized_userのものか検証
        if user_id != event['requestContext']['authorizer']['authorizedUserId']:
            raise errors.ForbiddenError('Access denied')

        # userが存在するか
        try:
            user = UserModel.get(user_id)
        except UserModel.DoesNotExist as e:
            raise errors.NotFound('This user does not exist')

        if 'name' in data:
            user.name = data['name']
        if 'email' in data:
            user.email = data['email']
        if 'phoneNumber' in data:
            user.phoneNumber = data['phoneNumber']

        # userの更新
        try:
            user.save()
        except InvalidNameError as e:
            logger.exception(e)
            raise errors.BadRequest(str(e.with_traceback(sys.exc_info()[2])))
        except InvalidPhoneNumberError as e:
            logger.exception(e)
            raise errors.BadRequest(str(e.with_traceback(sys.exc_info()[2])))
        except InvalidEmailError as e:
            logger.exception(e)
            if str(e.with_traceback(
                    sys.exc_info()[2])) == 'This email has been registered':
                raise errors.UnprocessableEntity(
                    str(e.with_traceback(sys.exc_info()[2])))
            else:
                raise errors.BadRequest(
                    str(e.with_traceback(sys.exc_info()[2])))
        except PutError as e:
            logger.exception(e)
            raise errors.InternalError('Internal server error')

        return {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            'body': json.dumps({
                'statusCode': 200,
                'user': dict(user)
            })
        }

    except errors.BadRequest as e:
        logger.exception(e)
        return build_response(e, 400)

    except errors.ForbiddenError as e:
        logger.exception(e)
        return build_response(e, 403)

    except errors.NotFound as e:
        logger.exception(e)
        return build_response(e, 404)

    except errors.UnprocessableEntity as e:
        logger.exception(e)
        return build_response(e, 409)

    except errors.InternalError as e:
        logger.exception(e)
        return build_response(e, 500)