コード例 #1
0
ファイル: app.py プロジェクト: PolinaAlexandr/cat_fight
def registration():
    post_data = request.get_json()
    if not post_data:
        return jsonify({
            "result" : "error",
            "comment" : "Invalid format, check your input and try again"
        })
    
    if not 'user_name' in post_data or not 'password':
        return jsonify({"""
            "result" : "error",
            "comment" : "Please follow the current template {"user_name" : "John",
            "password" : "*****"}"
            """
        })

    if not db.get_user_id_by_name(post_data['user_name']):
        db.new_user(post_data['user_name'], post_data['password'])
        return jsonify({
            "result" : "ok",
            "comment": "You are successfully registered"
        })    
    else:
        return jsonify( {
            "result" : "error",
            "comment" : "This user_name already exists, please choose the new one"
        })
コード例 #2
0
ファイル: app.py プロジェクト: PolinaAlexandr/cat_fight
def login():
    post_data = request.get_json()
    if not post_data:
        return jsonify({
            "result" : "error",
            "comment" : "Invalid format, check your input and try again"
        })
    if not 'user_name' in post_data or not 'password':
        return jsonify({"""
            "result" : "error",
            "comment" : "Please follow the current template {"user_name" : "John",
            "password" : "*****"}"
            """
        })

    user_name = post_data['user_name']
    user_password = post_data['password']
    user_id = db.get_user_id_by_name(user_name)

    if user_id and db.password_is_correct(user_name, user_password):
        token = db.generate_token(user_id)
        return jsonify({
            "result" : "ok",
            "comment": "You are successfully logged in",
            "token" : token
        })  

    return  jsonify ({
        "result" : "error",
        "comment": "Please check your user_name/password or sign up by following link [sign_up]"
    })
コード例 #3
0
ファイル: app.py プロジェクト: PolinaAlexandr/cat_fight
def statistics():
    post_data = request.get_json()
    if not post_data:
        return jsonify({
            "result" : "error",
            "comment" : "Invalid format, check your input and try again"
        })
    
    if not 'user_name' in post_data or not 'token':
        return jsonify({"""
            "result" : "error",
            "comment" : "Please follow the current template {"user_name" : "John",
            "token" : "*****"}"
            """
        })

    if not db.get_user_id_by_token(post_data['token']):
        return jsonify({
            "result" : "error",
            "comment" : "Invalid token"
        })
    
    user_id = db.get_user_id_by_name(post_data['user_name'])
    if not user_id:
        return jsonify({
            "result" : "error",
            "comment" : "Cannot check statistics, user does not exists"
        })
    

    return jsonify({
        "result" : "ok",
        "statistics" : db.get_user_stats(user_id).to_dict()
    })
コード例 #4
0
ファイル: views.py プロジェクト: RudyReeves/fullstack
def add_item():
    '''Adds an item to the database'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    if request.method == 'POST':
        category_name = request.form['category_name']

        # Ensure the category exists:
        query = db.session.query(Category).filter_by(name = category_name) #NOQA
        if not db.session.query(query.exists()):
            return redirect('/')

        category = query.one()
        item_name = request.form['item_name']
        item_description = request.form['item_description']

        # Validate the item name and descriptions
        if not db.is_valid_item(item_name, item_description):
            return redirect('/')

        user_id = db.get_user_id_by_name(login_session['username'])
        db.create_item(item_name, item_description, category.id, user_id)

        return redirect("/catalog/%s/items" % category_name)
    elif request.method == 'GET':
        categories = db.get_categories()

        (state, logged_in, username) = gplus.get_login_state()
        data = {
            'categories': [category.name for category in categories],
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('add.html', data = data)
コード例 #5
0
def add_item():
    '''Adds an item to the database'''

    # Ensure there is a user logged in:
    if not gplus.is_logged_in():
        return redirect('/')

    if request.method == 'POST':
        category_name = request.form['category_name']

        # Ensure the category exists:
        query = db.session.query(Category).filter_by(name=category_name)  #NOQA
        if not db.session.query(query.exists()):
            return redirect('/')

        category = query.one()
        item_name = request.form['item_name']
        item_description = request.form['item_description']

        # Validate the item name and descriptions
        if not db.is_valid_item(item_name, item_description):
            return redirect('/')

        user_id = db.get_user_id_by_name(login_session['username'])
        db.create_item(item_name, item_description, category.id, user_id)

        return redirect("/catalog/%s/items" % category_name)
    elif request.method == 'GET':
        categories = db.get_categories()

        (state, logged_in, username) = gplus.get_login_state()
        data = {
            'categories': [category.name for category in categories],
            'state': state,
            'logged_in': logged_in,
            'username': username
        }
        return render_template('add.html', data=data)
コード例 #6
0
ファイル: gplus.py プロジェクト: RudyReeves/fullstack
def gconnect():
    if is_logged_in():
        categories = db.get_categories()
        categories = [category.name for category in categories]
        latest_items = db.get_items()
        latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in latest_items] #NOQA
        data = {
            'categories': categories,
            'latest_items': latest_items,
            'logged_in': True,
            'username': views.login_session['username']
        }
        return render_template('index.html', data = data)

    if request.args.get('state') != views.login_session['state']:
        response = make_response(views.json.dumps('Invalid state paremeter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = views.flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except views.FlowExchangeError:
        response = make_response(views.json.dumps('Failed to upgrade the authorization code.'), 401) #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid:
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) #NOQA
    http = httplib2.Http()
    result = views.json.loads(http.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(views.json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user:
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response("Token's user ID doesn't match given user ID.", 401) #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app:
    if result['issued_to'] != views.CLIENT_ID:
        response = make_response(views.json.dumps("Token's client ID does not match app's."), 401) #NOQA
        print("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check to see if user is already logged in
    stored_credentials = views.login_session.get('credentials')
    stored_gplus_id = views.login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id  == stored_gplus_id:
        response = make_response(views.json.dumps("Current user is already connected."), 200) #NOQA
        response.headers['Content-Type'] = 'application/json'

    # Get user info
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params = params)
    data = views.json.loads(answer.text)

    # Store the access token in the session for later use.
    views.login_session['credentials'] = credentials.access_token
    views.login_session['gplus_id'] = gplus_id
    views.login_session['username'] = data['name']

    # Add a new user if this user doesn't already exist
    user_id = db.get_user_id_by_name(data['name'])
    if not user_id:
        user_id = db.create_user(views.login_session)

    views.login_session['user_id'] = user_id

    return redirect('/')
コード例 #7
0
ファイル: gplus.py プロジェクト: konqlonq/catalog
def gconnect():
    if is_logged_in():
        categories = db.get_categories()
        categories = [category.name for category in categories]
        latest_items = db.get_items()
        latest_items = [[
            item.name, db.get_category_name_by_id(item.category_id)
        ] for item in latest_items]  #NOQA
        data = {
            'categories': categories,
            'latest_items': latest_items,
            'logged_in': True,
            'username': views.login_session['username']
        }
        return render_template('index.html', data=data)

    if request.args.get('state') != views.login_session['state']:
        response = make_response(views.json.dumps('Invalid state paremeter'),
                                 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = views.flow_from_clientsecrets('client_secrets.json',
                                                   scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except views.FlowExchangeError:
        response = make_response(
            views.json.dumps('Failed to upgrade the authorization code.'),
            401)  #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid:
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)  #NOQA
    http = httplib2.Http()
    result = views.json.loads(http.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(views.json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user:
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            "Token's user ID doesn't match given user ID.", 401)  #NOQA
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app:
    if result['issued_to'] != views.CLIENT_ID:
        response = make_response(
            views.json.dumps("Token's client ID does not match app's."),
            401)  #NOQA
        print("Token's client ID does not match app's.")
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check to see if user is already logged in
    stored_credentials = views.login_session.get('credentials')
    stored_gplus_id = views.login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(
            views.json.dumps("Current user is already connected."), 200)  #NOQA
        response.headers['Content-Type'] = 'application/json'

    # Get user info
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = views.json.loads(answer.text)

    # Store the access token in the session for later use.
    views.login_session['credentials'] = credentials.access_token
    views.login_session['gplus_id'] = gplus_id
    views.login_session['username'] = data['name']

    # Add a new user if this user doesn't already exist
    user_id = db.get_user_id_by_name(data['name'])
    if not user_id:
        user_id = db.create_user(views.login_session)

    views.login_session['user_id'] = user_id

    return redirect('/')