예제 #1
0
def add_allergen(request):
    """
    Adds an allergen to a user's allergen list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        euid = request.COOKIES.get('euid')
        user = User.get_by_id(crypto.decrypt(euid))
        allergen_name = request.POST.get('allergen', '')
        allergen = Label.query(Label.user_id == user.key.id(),
                               Label.name == allergen_name).get(keys_only=True)

        if session_id and not allergen:
            profile = user.get_profile()

            for a in profile['allergens']:
                if a['name'] == allergen_name: a['value'] = 'true'

            response = label_api.set_profile(session_id, profile)

            if response.get('result') == 'success':
                Label(user_id=user.key.id(), name=allergen_name).put_async()
                return HttpResponse('{"result": "success"}',
                                    content_type='application/json')
    except:
        pass

    return HttpResponse('{"result": "failure"}',
                        content_type='application/json')
예제 #2
0
def add_ingredient(request):
    """
    Adds an ingredient to a user's ingredient list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        user_id = crypto.decrypt(request.COOKIES.get('euid', ''))
        ingredient_id = request.POST.get('ingredient_id', '')
        ingredient_name = request.POST.get('ingredient_name', '')
        ingredient = Label.query(
            Label.user_id == user_id, Label.name == ingredient_name,
            Label.sub_id == ingredient_id).get(keys_only=True)

        if session_id and not ingredient:
            response = label_api.add_ingredient(session_id, ingredient_id)

            if response.get('result') == 'success':
                Label(user_id=user_id,
                      name=ingredient_name,
                      sub_id=ingredient_id).put_async()
                return HttpResponse('{"result": "success"}',
                                    content_type='application/json')

    except:
        pass

    return HttpResponse('{"result": "failure"}',
                        content_type='application/json')
예제 #3
0
def add_ingredient(request):
    """
    Adds an ingredient to a user's ingredient list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        user_id = crypto.decrypt(request.COOKIES.get('euid', ''))
        ingredient_id = request.POST.get('ingredient_id', '')
        ingredient_name = request.POST.get('ingredient_name', '')
        ingredient = Label.query(
            Label.user_id == user_id,
            Label.name == ingredient_name,
            Label.sub_id == ingredient_id).get(keys_only=True)

        if session_id and not ingredient:
            response = label_api.add_ingredient(session_id, ingredient_id)

            if response.get('result')  == 'success':
                Label(user_id=user_id, name=ingredient_name, sub_id=ingredient_id).put_async()
                return HttpResponse('{"result": "success"}', content_type='application/json')

    except:
        pass

    return HttpResponse('{"result": "failure"}', content_type='application/json')
예제 #4
0
def remove_nutrient(request):
    """
    Removes a nutrient from a user's nutrient list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        euid = request.COOKIES.get('euid')
        user = User.get_by_id(crypto.decrypt(euid))
        nutrient_name = request.POST.get('nutrient', '')
        nutrient = Label.query(Label.user_id == user.key.id(),
                               Label.name == nutrient_name).get(keys_only=True)

        if session_id and nutrient:
            profile = user.get_profile()

            for n in profile['nutrients']:
                if n['name'] == nutrient_name: n['value'] = 'false'

            response = label_api.set_profile(session_id, profile)

            if response.get('result') == 'success':
                nutrient.delete_async()
                return HttpResponse('{"result": "success"}',
                                    content_type='application/json')
    except:
        pass

    return HttpResponse('{"result": "failure"}',
                        content_type='application/json')
예제 #5
0
def add_allergen(request):
    """
    Adds an allergen to a user's allergen list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        euid = request.COOKIES.get('euid')
        user = User.get_by_id(crypto.decrypt(euid))
        allergen_name = request.POST.get('allergen', '')
        allergen = Label.query(
            Label.user_id == user.key.id(),
            Label.name == allergen_name).get(keys_only=True)

        if session_id and not allergen:
            profile = user.get_profile()

            for a in profile['allergens']:
                if a['name'] == allergen_name: a['value'] = 'true'

            response = label_api.set_profile(session_id, profile)

            if response.get('result')  == 'success':
                Label(user_id = user.key.id(), name = allergen_name).put_async()
                return HttpResponse('{"result": "success"}', content_type='application/json')
    except:
        pass

    return HttpResponse('{"result": "failure"}', content_type='application/json')
예제 #6
0
def remove_nutrient(request):
    """
    Removes a nutrient from a user's nutrient list
    """
    try:
        session_id = request.get_signed_cookie('session_id', default=None)
        euid = request.COOKIES.get('euid')
        user = User.get_by_id(crypto.decrypt(euid))
        nutrient_name = request.POST.get('nutrient', '')
        nutrient = Label.query(
            Label.user_id == user.key.id(),
            Label.name == nutrient_name).get(keys_only=True)

        if session_id and nutrient:
            profile = user.get_profile()

            for n in profile['nutrients']:
                if n['name'] == nutrient_name: n['value'] = 'false'

            response = label_api.set_profile(session_id, profile)

            if response.get('result')  == 'success':
                nutrient.delete_async()
                return HttpResponse('{"result": "success"}', content_type='application/json')
    except:
        pass

    return HttpResponse('{"result": "failure"}', content_type='application/json')
예제 #7
0
def user_profile(request):
    """
    Returns user profile page
    """
    user_id = crypto.decrypt(request.COOKIES['euid']) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)

    if user_id and session_id:
        user = User.get_by_id(user_id)
        profile = user.get_profile()
        show_expired = False
        show_failed_upgrade = False

        if user.group_id == 2: # Upgraded user
            now = datetime.utcnow()
            if user.upgrade_exp < now:
                user.group_id = 1
                user.reset_profile(session_id)
                user.put()
                if (now - user.upgrade_exp).days < 3:
                    show_expired = True

        if request.GET.get('upgrade_status') == '0':
            show_failed_upgrade = True

        def filter_list(a_list):
            result = {}
            for x in a_list:
                if x['value'] == 'true':
                    result[x['name']] = True
            return result

        user_nutrients = filter_list(profile['nutrients'])
        user_allergens = filter_list(profile['allergens'])
        user_additives = filter_list(profile['additives'])
        user_ingredients = Label.query(
            Label.user_id == user_id,
            Label.sub_id != None).fetch()

        return render_to_response(
            'user_profile.html',
            {
                'user': user,
                'user_nutrients': user_nutrients,
                'user_allergens': user_allergens,
                'user_additives': user_additives,
                'user_ingredients': user_ingredients,
                'known_nutrients': constants.known_nutrients,
                'known_allergens': constants.known_allergens,
                'known_additives': constants.known_additives,
                'show_expired': show_expired,
                'show_failed_upgrade': show_failed_upgrade,
                'stripe_public_key': settings.STRIPE_PUBLIC_KEY
            },
            RequestContext(request))

    return redirect('/signin')    
예제 #8
0
def authenticate(request):
    """
    Get credentials from Google using code from client,
    and then check if the user already exists in ndb.
    """
    try:
        oauth_flow = OAuth2WebServerFlow(
            client_id=settings.GOOGLE_CLIENT['web']['client_id'],
            client_secret=settings.GOOGLE_CLIENT['web']['client_secret'],
            auth_uri=settings.GOOGLE_CLIENT['web']['auth_uri'],
            token_uri=settings.GOOGLE_CLIENT['web']['token_uri'],    
            redirect_uri='postmessage',
            scope='openid email',
        )
        credentials = json.loads(oauth_flow.step2_exchange(request.body).to_json())
    except FlowExchangeError:
        return HttpResponse('{"result":"failure"}', content_type='application/json')
    else:
        user = User.get_by_id(credentials['id_token']['sub'])

        if not user:
            user = User(
                id = credentials['id_token']['sub'],
                email = credentials['id_token']['email'],
                refresh_token = credentials.get('refresh_token'))
            user.put()

        try:
            uid = user.key.id()
            session = label_api.create_session(user_id=uid, app_id=uid, device_id=uid)
            session_id = session.get('session_id')

            if not session_id:
                raise Exception

            # Must set profile before adding ingredients
            response = label_api.set_profile(session_id, user.get_profile())

            if response.get('result') != 'success':
                raise Exception

            for label in Label.query(Label.user_id == uid, Label.sub_id != '').fetch():
                label_api.add_ingredient(session_id, label.sub_id)

            response = HttpResponse(json.dumps({
                "success": True,
                "euid": crypto.encrypt(uid)
            }), content_type='application/json')

            response.set_signed_cookie('session_id', session_id)

            return response
        except:
            pass

    return HttpResponse('{"success": false}', content_type='application/json')
예제 #9
0
def user_profile(request):
    """
    Returns user profile page
    """
    user_id = crypto.decrypt(
        request.COOKIES['euid']) if 'euid' in request.COOKIES else None
    session_id = request.get_signed_cookie('session_id', default=None)

    if user_id and session_id:
        user = User.get_by_id(user_id)
        profile = user.get_profile()
        show_expired = False
        show_failed_upgrade = False

        if user.group_id == 2:  # Upgraded user
            now = datetime.utcnow()
            if user.upgrade_exp < now:
                user.group_id = 1
                user.reset_profile(session_id)
                user.put()
                if (now - user.upgrade_exp).days < 3:
                    show_expired = True

        if request.GET.get('upgrade_status') == '0':
            show_failed_upgrade = True

        def filter_list(a_list):
            result = {}
            for x in a_list:
                if x['value'] == 'true':
                    result[x['name']] = True
            return result

        user_nutrients = filter_list(profile['nutrients'])
        user_allergens = filter_list(profile['allergens'])
        user_additives = filter_list(profile['additives'])
        user_ingredients = Label.query(Label.user_id == user_id,
                                       Label.sub_id != None).fetch()

        return render_to_response(
            'user_profile.html', {
                'user': user,
                'user_nutrients': user_nutrients,
                'user_allergens': user_allergens,
                'user_additives': user_additives,
                'user_ingredients': user_ingredients,
                'known_nutrients': constants.known_nutrients,
                'known_allergens': constants.known_allergens,
                'known_additives': constants.known_additives,
                'show_expired': show_expired,
                'show_failed_upgrade': show_failed_upgrade,
                'stripe_public_key': settings.STRIPE_PUBLIC_KEY
            }, RequestContext(request))

    return redirect('/signin')
예제 #10
0
def authenticate(request):
    """
    Get credentials from Google using code from client,
    and then check if the user already exists in ndb.
    """
    try:
        oauth_flow = OAuth2WebServerFlow(
            client_id=settings.GOOGLE_CLIENT['web']['client_id'],
            client_secret=settings.GOOGLE_CLIENT['web']['client_secret'],
            auth_uri=settings.GOOGLE_CLIENT['web']['auth_uri'],
            token_uri=settings.GOOGLE_CLIENT['web']['token_uri'],
            redirect_uri='postmessage',
            scope='openid email',
        )
        credentials = json.loads(
            oauth_flow.step2_exchange(request.body).to_json())
    except FlowExchangeError:
        return HttpResponse('{"result":"failure"}',
                            content_type='application/json')
    else:
        user = User.get_by_id(credentials['id_token']['sub'])

        if not user:
            user = User(id=credentials['id_token']['sub'],
                        email=credentials['id_token']['email'],
                        refresh_token=credentials.get('refresh_token'))
            user.put()

        try:
            uid = user.key.id()
            session = label_api.create_session(user_id=uid,
                                               app_id=uid,
                                               device_id=uid)
            session_id = session.get('session_id')

            if not session_id:
                raise Exception

            # Must set profile before adding ingredients
            response = label_api.set_profile(session_id, user.get_profile())

            if response.get('result') != 'success':
                raise Exception

            for label in Label.query(Label.user_id == uid,
                                     Label.sub_id != '').fetch():
                label_api.add_ingredient(session_id, label.sub_id)

            response = HttpResponse(json.dumps({
                "success": True,
                "euid": crypto.encrypt(uid)
            }),
                                    content_type='application/json')

            response.set_signed_cookie('session_id', session_id)

            return response
        except:
            pass

    return HttpResponse('{"success": false}', content_type='application/json')