def fbconnect():
    '''Oauth with Facebook account'''
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = request.data
    
    # Exchange client token for long-lived server side token with GET /oauth/
    # acces_token?grant_type=fb_exchange_token&client_id={app-id}
    # &client_secret={app-secret}&fb_exchange_token={short-lived-token}
    app_id = json.loads(open('fb_client_secrets.json', 'r').read())['web'][
        'app_id']
    app_secret = json.loads(open('fb_client_secrets.json', 'r').read())['web'][
        'app_secret']
    url = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=%s&client_secret=%s&fb_exchange_token=%s' % (
            app_id, app_secret, access_token)
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    
    # Use token to get user info from API
    userinfo_url = 'https://graph.facebook.com/v2.3/me'
    # strip expire tag from access token
    token = result.split('&')[0]
    
    url = 'https://graph.facebook.com/v2.3/me?%s' % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)
    login_session['provider'] = 'facebook'
    login_session['username'] = data['name']
    login_session['email'] = data['email']
    login_session['facebook_id'] = data['id']
    
    # The token must be stored in the login_session in order to properly logout,
    # let's strip out the information before the equals sign in our token
    stored_token = token.split("=")[1]
    login_session['access_token'] = stored_token
    
    # check if user exists in the db
    user_id = get_user_id(data['email'])
    if user_id is None:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id
    
    output = 'welcome ' + login_session['username']
    flash('you are logged in as %s' % login_session['username'])
    return output
Exemplo n.º 2
0
    def inner_func(*args, **kw):
        user_name, password = (request.authorization.username,
                               request.authorization.password
                               ) if request.authorization else (None, None)
        if not password and not user_name:
            return jsonify({"error": "missing"}), 401
        if not password:
            user = user_from_token(user_name)
            if user is not None:
                g.user_id = user[0]
                return f(*args, **kw)

        elif validate_user({'email': user_name, 'password': password}):
            g.user_id = get_user_id(user_name)
            return f(*args, **kw)

        return jsonify({'error': 'error'}), 401  ## not authenticated
Exemplo n.º 3
0
def fbconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = request.data

    # Exchanges client token for long-lived server-side token with /GET /oauth/
    # access_token?grant_type=fb_exchange_token&client_id={app-id}&client_secret={app-secret}&fb_exchange_token=
    # {short-lived-token}
    app_id = json.loads(open('fb_client_secrets.json',
                             'r').read())['web']['app_id']
    app_secret = json.loads(open('fb_client_secrets.json',
                                 'r').read())['web']['app_secret']
    url = FB_TOKEN_URL % (app_id, app_secret, access_token)
    result = request_to_url(url, value=1, to_json=False)

    # Use token to get user info from API and Strip Expire Tag from Access Token
    token = get_fb_token(result)
    userinfo_url = FB_USER_INFO_URL % token
    data = request_to_url(userinfo_url, value=1)

    login_session['provider'] = 'facebook'
    login_session['username'] = data["name"]
    login_session['email'] = data["email"]
    login_session['facebook_id'] = data["id"]

    # Get user picture
    url = FB_USER_PIC_URL % token
    data = request_to_url(url, value=1)
    login_session['picture'] = data['data']['url']

    # See if user exists
    user_id = get_user_id(login_session['email'])
    if not user_id:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id

    output = LOGIN_OUTPUT % (login_session['username'],
                             login_session['picture'])
    flash(MESSAGE_LOGIN % login_session['username'])
    return output
Exemplo n.º 4
0
def update_state(request):
    logger.info('Incoming {} request'.format(request.path))

    session = yield from get_session(request)
    user_id = get_user_id(session)

    yield from request.post()

    req_actions = request.POST.get('actions', '[]')
    req_actions = json.loads(req_actions)

    logger.debug('Wait for free redis connection from pool')
    with (yield from request.app.redis_pool) as redis:
        logger.debug('Redis connection waiting finished')
        try:
            logger.debug(
                "Requester actions is: {}".format(
                    ", ".join([req_action["type"] for req_action in req_actions])
                )
            )

            for req_action in req_actions:
                try:
                    action_cls = actions[req_action['type']]
                except KeyError:
                    msg = "Error! There is no such action type as %s" % req_action['type']
                    logger.error(msg)
                    return web.HTTPBadRequest(body=msg.encode('utf-8'))

                logger.debug('Begin "{}" action process'.format(req_action['type']))

                action = action_cls(field_db_key.format(user_id), items_db_key.format(user_id), redis)

                yield from action.make_action(**req_action['params'])

                logger.debug('End "{}" action process'.format(req_action['type']))

        except ActionException as error:
            logger.exception(error.body)
            return web.HTTPBadRequest(body=error.body.encode('utf-8'))

    return web.Response(body=b"Ok.")
Exemplo n.º 5
0
def get_state(request):
    logger.info('Incoming {} request'.format(request.path))

    session = yield from get_session(request)
    user_id = get_user_id(session)

    logger.debug('Wait for free redis connection from pool')
    with (yield from request.app.redis_pool) as redis:
        logger.debug('Redis connection waiting finished')

        logger.debug('Get field from redis')
        field = yield from redis.lrange(field_db_key.format(user_id), 0, -1, encoding='utf-8')

        if not field:
            logger.debug('User does not have a field. Creating...')
            field = create_empty_field()
            logger.debug('Write user field to Redis...')
            yield from redis.lpush(field_db_key.format(user_id), *field)

        return json_response({
            'field': field,
            'field_size': settings.FIELD_SIZE
        })
Exemplo n.º 6
0
def gconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    code = request.data
    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secret.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        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)
    result = request_to_url(url, value=1)

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 50)
        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(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

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

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

    # Store the access token in the session for later use.
    login_session['provider'] = 'google'
    login_session['credentials'] = credentials
    login_session['gplus_id'] = gplus_id
    response = make_response(json.dumps('Successfully connected user.'), 200)

    # 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 = json.loads(answer.text)

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # See if user exists, if doesn't make a new one
    user_id = get_user_id(login_session['email'])
    if not user_id:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id

    output = LOGIN_OUTPUT % (login_session['username'],
                             login_session['picture'])
    flash(MESSAGE_LOGIN % login_session['username'])
    return output
def gconnect():
    '''Oauth with Google account'''
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    code = request.data
    
    try:
        # upgrade the authorisation code into a credential object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(json.dumps('Failed to upgrade the auth code.'),
                                 401)
        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)
    h = httplib2.Http()
    result = json.loads(h.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(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(json.dumps(
            "Token's user ID doesn't match given user ID"), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    
    # verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's"), 401)
        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 = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps(
            'Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    
    # store the access token in the session for later use
    login_session['credentials'] = credentials
    login_session['gplus_id'] = gplus_id
    
    # 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 = json.loads(answer.text)
    
    login_session['username'] = data['name']
    login_session['email'] = data['email']
    login_session['picture'] = data['picture']
    login_session['provider'] = 'google'
    
    # check if user exists in the db
    user_id = get_user_id(data['email'])
    if user_id is None:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id
    
    output = 'Welcome ' + login_session['username']
    flash('you are logged in as %s' % login_session['username'])
    return output