Exemple #1
0
def signup(*args, **kwargs):
    data = request.get_json()

    try:
        new_user = User(username=data['username'],
                        email=data['email'],
                        password=data['password'])
        new_user.save()
        token = create_access_token(identity=new_user.uuid,
                                    expires_delta=timedelta(30))
        response = compose_json_response(success=True,
                                         data=token,
                                         message=None,
                                         code=200)
    except OperationException:
        response = compose_json_response(success=False,
                                         data=None,
                                         message=None,
                                         code=500)
    except KeyError:
        response = compose_json_response(success=False,
                                         data=None,
                                         message=None,
                                         code=400)
    return response
Exemple #2
0
def add_user(email, name='Paul Anderson'):
    """Setup a new user for the database with a default institute."""
    connect('variantDatabase', host='localhost', port=27017)

    institute = Institute.objects.first()
    Whitelist(email=email).save()
    # create a default user
    user = User(email=email,
                name=name,
                roles=['admin'],
                institutes=[institute])
    user.save()
Exemple #3
0
def add_user(email, name='Paul Anderson'):
  """Setup a new user for the database with a default institute."""
  connect('variantDatabase', host='localhost', port=27017)

  institute = Institute.objects.first()
  Whitelist(email=email).save()
  # create a default user
  user = User(
    email=email,
    name=name,
    roles=['admin'],
    institutes=[institute]
  )
  user.save()
Exemple #4
0
def get_user(request):
    logger.info("setup a user")
    user = User(
        email='*****@*****.**',
        name="John Doe"
    )
    logger.info("Adding user to database")
    user.save()
    def teardown():
        print('\n')
        logger.info('Removing user')
        user.delete()
        logger.info('user removed')
    request.addfinalizer(teardown)
    
    return user
Exemple #5
0
def build_user(user_info):
    """Build a user object

    Args:
        user_info(dict): A dictionary with user information

    Returns:
        user_obj(scout.models.User)
    """
    try:
        email = user_info["email"]
    except KeyError as err:
        raise KeyError("A user has to have a email")

    try:
        name = user_info["name"]
    except KeyError as err:
        raise KeyError("A user has to have a name")

    user_obj = User(email=email, name=name, id=user_info.get("id"))

    ##TODO check that these are on the correct format
    if "roles" in user_info:
        user_obj["roles"] = user_info["roles"]

    if "location" in user_info:
        user_obj["location"] = user_info["location"]

    if "institutes" in user_info:
        user_obj["institutes"] = user_info["institutes"]

    return user_obj
Exemple #6
0
def build_user(user_info):
    """Build a user object
    
    Args:
        user_info(dict): A dictionary with user information
    
    Returns:
        user_obj(scout.models.User)
    """
    try:
        email = user_info['email']
    except KeyError as err:
        raise KeyError("A user has to have a email")

    try:
        name = user_info['name']
    except KeyError as err:
        raise KeyError("A user has to have a name")

    user_obj = User(email=email, name=name)

    ##TODO check that these are on the correct format
    if 'roles' in user_info:
        user_obj['roles'] = user_info['roles']

    if 'location' in user_info:
        user_obj['location'] = user_info['location']

    if 'institutes' in user_info:
        user_obj['institutes'] = user_info['institutes']

    return user_obj
Exemple #7
0
    def cases(self, collaborator=None, query=None, skip_assigned=False):
        """Fetches all cases from the backend.

        Args:
            collaborator(str): If collaborator should be considered
            query(dict): If a specific query is used

        Yields:
            Cases ordered by date
        """
        logger.info("Fetch all cases")
        if collaborator:
            logger.info("Use collaborator {0}".format(collaborator))
            case_query = Case.objects(collaborators=collaborator)
        else:
            case_query = Case.objects

        if query:
            # filter if any user names match query
            matching_users = User.objects(name__icontains=query)

            # filter cases by matching display name of case or individuals
            case_query = case_query.filter(
                Q(display_name__icontains=query) |
                Q(individuals__display_name__icontains=query) |
                Q(assignee__in=matching_users)
            )

        if skip_assigned:
            case_query = case_query.filter(assignee__exists=False)

        return case_query.order_by('-updated_at')
Exemple #8
0
def login(*args, **kwargs):
    data = request.get_json()

    try:
        username_or_email = data['username_or_email']
        password = data['password']

        if username_or_email and password:
            auth_dict = User.validate_credentials(username_or_email, password)
            if auth_dict['valid']:
                token = create_access_token(
                    identity=auth_dict['user'].to_json()['uuid'],
                    expires_delta=timedelta(90))
                response = compose_json_response(success=True,
                                                 data=token,
                                                 message=None,
                                                 code=200)
            else:
                response = compose_json_response(success=False,
                                                 data=None,
                                                 message='Unauthorized',
                                                 code=401)
        else:
            response = compose_json_response(
                success=False,
                data=None,
                message='Invalid auth credentials',
                code=400)
    except KeyError:
        response = compose_json_response(success=False,
                                         data=None,
                                         message=None,
                                         code=400)

    return response
Exemple #9
0
def DataRequiredIf2fa(form, field):
    from scout.models import User
    user = User.GetSessionsUser()
    if user.multifactor_login_enabled and not field.data:
        field.errors.append('Two Factor Code Required')
        return False
    return True
Exemple #10
0
def get_recommendations(*args, **kwargs):
    current_user = User.get_current()

    try:
        recommendations = [YelpFusion.get_with_id(id=recommendation.yelp_id, desired_props = ["id", "name", "image_url", "is_closed", "location", "url", "price"])
                           for recommendation in Recommendation.get_latest_5_with_user_id(current_user.id)]


        response = compose_json_response(success=True, data=recommendations, message=None, code=200)
    except:
        response = compose_json_response(success=False, data=None, message=None, code=500)
    return response
Exemple #11
0
def init():
    """Initialize Scout database with an admin user account."""
    admin_email = request.form['email']
    admin_name = request.form.get('name', admin_email)
    admin_institutes = request.form.getlist('institutes')

    try:
        logger.debug('whitelist the email account')
        whitelist_obj = Whitelist(email=admin_email)
        whitelist_obj.save()
    except NotUniqueError:
        logger.debug('email already whitelisted')

    try:
        logger.debug('setup the Scout admin account')
        user_obj = User(email=admin_email, name=admin_name,
                        institutes=admin_institutes, roles=['admin'])
        user_obj.save()
    except NotUniqueError:
        logger.debug('user account already created')
        return jsonify(success=False)
    return jsonify(**prepare_json(user_obj.to_mongo()))
    def init(self, admin_mail=None, admin_name=None, admin_institutes=None):
        """Initialize Scout database with an admin user account."""
        admin_config = self.config["scout"]["admin"]
        admin_mail = admin_mail or admin_config["email"]
        admin_name = admin_name or admin_config.get("name")
        admin_institutes = admin_institutes or admin_config.get("institutes")

        try:
            logger.debug("whitelist the email account")
            whitelist_obj = Whitelist(email=admin_mail)
            whitelist_obj.save()
        except NotUniqueError:
            logger.debug("email already whitelisted")

        try:
            logger.debug("setup the Scout admin account")
            user_obj = User(email=admin_mail, name=admin_name, institutes=(admin_institutes or []), roles=["admin"])
            user_obj.save()
        except NotUniqueError:
            logger.debug("user account already created")
            return None

        return prepare_json(user_obj.to_mongo())
Exemple #13
0
def create_visit(*args, **kwargs):
    data = request.get_json()

    try:
        user_id = User.get_current().id
        yelp_id = data['yelp_id']
        attend_date = data['attend_date']
        satisfaction = data['satisfaction']

        new_visit = Visit(user_id=user_id,
                          yelp_id=yelp_id,
                          attend_date=attend_date,
                          satisfaction=satisfaction)
        new_visit.save()
        response = compose_json_response(success=True, data=None, message=None, code=200)
    except OperationException:
        response = compose_json_response(success=False, data=None, message=None, code=500)
    except KeyError:
        response = compose_json_response(success=False, data=None, message=None, code=400)
    return response
Exemple #14
0
def get_me(*args, **kwargs):
    current_user = User.get_current()
    return compose_json_response(success=True, data=current_user.to_json(), message=None, code=200)