コード例 #1
0
def optionsUser():
    i = -1
    while i != 0:
        i = menus.menuUser()
        if i == 1:
            user.sudoers()
        elif i == 2:
            user.hashes()
        elif i == 3:
            user.createUser()
        elif i == 4:
            user.root()
コード例 #2
0
def createUser():
    data = request.json
    newUser = user.createUser(data['User_ID'], data['Email'],
                              data['First_Name'], data['Last_Name'],
                              data['Avatar'])
    LIST.addUser(newUser)
    return jsonify({'msg': "User successfully created"})
コード例 #3
0
def handle_dialog(res, req):
    # текст команды, которую ввел пользователь
    command = req['request']['original_utterance'].lower()

    # обработчик пинга
    if command == 'ping':
        res.addText('pong')
        return

    # получаем ID пользователя
    user_id = req['session']['user_id']

    # если пользователь новый, то просим представиться
    if req['session']['new']:
        res.addText('Привет! Назови свое имя!')
        # создаем класс для хранения информации о пользователе
        user = createUser(user_id)
        # сохраняем пользователя в базе данных
        commit()
        return

    # находим пользователя
    user = findUser(user_id)

    # если пользователь еще не представился
    if user.name is None:
        first_name = get_first_name(req)

        if first_name is None:
            res.addText('Не расслышала имя. Повтори, пожалуйста!')
            return

        user.name = first_name
        res.addText('Приятно познакомиться, ' + first_name.title() + '.')
        res.addText('Давай поиграем.')
        command = None

    # обработчик 1 комнаты
    if user.room == 1:
        Room1(res, req, user, command)

    # обработчик 2 комнаты
    elif user.room == 2:
        Room2(res, req, user, command)

    # обработчик 3 комнаты
    elif user.room == 3:
        Room3(res, req, user, command)

    # обработчик 4 комнаты
    elif user.room == 4:
        Room4(res, req, user, command)

    # обработчик Москвы
    else:
        Moscow(res, req, user, command)

    # сохраняем пользователя в базе данных
    commit()
コード例 #4
0
def updateUser():
    data = request.json
    tmpUser = user.createUser(data['User_ID'], data['Email'],
                              data['First_Name'], data['Last_Name'],
                              data['Avatar'])
    print("avatar", data['User_ID'])
    LIST.updateUser(int(data['page']), int(data['user']), tmpUser)
    return jsonify({'msg': "User successfully updated"})
コード例 #5
0
def fbconnect():
    """Authenticate user using Facebook"""

    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
    access_token = access_token.decode("utf-8")
    # Exchange client token for long-lived server-side token with GET 
    # /oauth/access_toke?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]
    result_string = result.decode("utf-8")
    # Use token to get user info from API
    userinfo_url = "https://graph.facebook.com/v3.2/me"
    # Strip expire tag from access token
    token = result_string.split(',')[0].split(':')[1].replace('"', '')
    url = "https://graph.facebook.com/v3.2/"+\
            "me?access_token=%s&fields=name,id,email" % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    result_string = result.decode("utf-8")
    data = json.loads(result_string)
    login_session['provider'] = 'facebook'
    login_session['username'] = data["name"]
    login_session['email'] = data["email"]
    login_session['facebook_id'] = data["id"]
    # Get user picture
    url = "https://graph.facebook.com/v3.3/"+\
            "me?access_token=%s&fields=picture" % token
    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)
    login_session['picture'] = data["picture"]["data"]["url"]
    # See if user exists
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    output = ''
    output += '<div class="container text-center">'+\
                '<div class="row justify-content-md-center">'+\
                    '<div class="col-md-8 border p-1 m-1">'+\
                        '<pclass="m-1">Welcome, '
    output += login_session['username']
    output += '!</p>'
    output += '<div class="d-flex justify-content-center m-1">'+\
                '<img class="rounded mx-auto d-block" width="30%" src="'
    output += login_session['picture']
    output += '"></div></div></div></div>'
    return output
コード例 #6
0
def routeUser(username):
    if request.headers['Content-Type'] == 'application/json':
        if request.method == 'GET':
            return user.getUser(username)
        elif request.method == 'POST':
            return user.createUser(username, request.json)
        elif request.method == 'DELETE':
            return user.deleteUser(username)
    else:
        abort(415)
コード例 #7
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

    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

    token = result.split('"')[3]
    # token = token.replace('"', '')
    url = 'https://graph.facebook.com/v2.8/me?' \
          'access_token=%s&fields=name,id,email' % 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

    login_session['access_token'] = token

    # Get user picture
    url = 'https://graph.facebook.com/v2.8/me/picture?access_token=%s&' \
          'redirect=0&height=200&width=200' % token

    h = httplib2.Http()
    result = h.request(url, 'GET')[1]
    data = json.loads(result)

    login_session['picture'] = data["data"]["url"]

    # see if user exists
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    return afterlogin(login_session)
コード例 #8
0
ファイル: server.py プロジェクト: Overrideveloper/bcmis-api
def signup():
    username = request.form.get('username')
    password = request.form.get('hash')
    group = request.form.get('group')

    process = user.createUser(username, password, group)

    if process != None:
        response = jsonify(message=True, code=200, data=process)
        response.status_code = 200
    else:
        response = jsonify(message=False,
                           code=500,
                           data="Error occured. Please try again")
        response.status_code = 500
    return response
コード例 #9
0
def gconnect():
    """Authenticate user using Google"""

    # Validate state token
    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
    # Obtain authorization code
    code = request.data
    try:
        # Upgrade the authorization code into a credentials 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 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)
    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'
        return response
    # 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
    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token 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['provider'] = 'google'
    login_session['access_token'] = credentials.access_token
    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 = answer.json()
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    output = ''
    output += '<div class="container text-center">'+\
                '<div class="row justify-content-md-center">'+\
                    '<div class="col-md-8 border p-1 m-1"><pclass="m-1">Welcome, '
    output += login_session['username']
    output += '!</p>'
    output += '<div class="d-flex justify-content-center m-1">'+\
                '<img class="rounded mx-auto d-block" '+\
                    'width="30%" src="'
    output += login_session['picture']
    output += '"></div></div></div></div>'
    return output
コード例 #10
0
ファイル: google.py プロジェクト: mozuk/udacity
def gconnect():
    # Validate state token
    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
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials 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 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)
    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

    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.to_json()
    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 = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    # ADD PROVIDER TO LOGIN SESSION
    login_session['provider'] = 'google'

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(data["email"])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: ' \
              '150px;-webkit-border-radius: ' \
              '150px;-moz-border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    print "done!"
    return output
コード例 #11
0
import user
import numpy

USERS = [
    user.createUser(
        "1", "*****@*****.**", "George", "Bluth",
        "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"),
    user.createUser(
        "2", "*****@*****.**", "Janet", "Weaver",
        "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"),
    user.createUser(
        "3", "*****@*****.**", "Emma", "Wong",
        "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"),
    user.createUser(
        "4", "*****@*****.**", "Eve", "Holt",
        "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"),
    user.createUser(
        "5", "*****@*****.**", "Charles", "Morris",
        "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"),
    user.createUser(
        "6", "*****@*****.**", "Tracey", "Ramos",
        "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg")
]

PAGES = []


class createUsersList:
    def __init__(self):
        global USERS
        global PAGES
コード例 #12
0
ファイル: gd-pyapi.py プロジェクト: jiri-simon/GD-PyAPI-lib
    

###############################################################################################


##Login
LogIn = logIn(settings.GDHostname,settings.GDAdmin_username , settings.GDAdmin_password)

GDCAuthSST = LogIn['GDCAuthSST']  #Get SST
adminid = LogIn['Profile']        #Get Profile of loged user
GDCAuthTT= getTT(settings.GDHostname,GDCAuthSST)      #set Variable GDCAuthTT
GetDomainUsers=getUsers(settings.GDHostname,GDCAuthTT,settings.GDDomain) 
json_acceptable_string = GetDomainUsers['read'].replace("'", "\"")
d = json.loads(json_acceptable_string)
iterace = d['accountSettings']['items']

user=createUser(settings.GDHostname,GDCAuthTT,settings.GDDomain,"*****@*****.**","*****@*****.**","Heslo123","TestJmeno","TestPrijmeni","")
print user['code']
print user['read']

deletedUser=deleteUser(settings.GDHostname,GDCAuthTT,"/gdc/account/profile/589124c2f127f09fe803a22ceb66cf2e")
print deletedUser['code']
print deletedUser['read']


#for item in iterace:
#     ChangePasswdUser(settings.GDHostname,GDCAuthTT,item['accountSetting']['links']['self'],item['accountSetting']['firstName'],item['accountSetting']['lastName'],adminid,"SecretPassword")

#logOut(settings.GDHostname,GDCAuthTT,adminid)
コード例 #13
0
def signUpBase64():
    params = ['name', 'starting_balance', 'username', 'password', 'image']

    data = request.form

    for p in params:
        if p not in data:
            return json.dumps({
                'error': 'Required params missing',
                'success': False
            }), 200

    try:
        float(data['starting_balance'])
    except ValueError:
        return json.dumps({'error': 'Invalid balance', 'success': False}), 400

    image_string = data['image']
    tmp_file = str(random.randint(1, 1000)) + '_' + str(random.randint(
        1, 1000)) + '.jpg'
    fh = open(tmp_file, "wb")
    fh.write(str(image_string.split(",")[1].decode('base64')))
    fh.close()

    images = []

    img = cv2.imread(tmp_file)
    os.remove(tmp_file)

    if img is None:
        return json.dumps({
            'error': 'Invalid file uploaded',
            'success': False
        }), 200

    faces = face_detector(img, 1)

    if len(faces) < 1:
        return json.dumps({
            'error':
            'Please upload different images; we cannot detect a face in at least one image',
            'success': False
        }), 200

    if len(faces) > 1:
        return json.dumps({
            'error': 'Please upload images that only has your face in it',
            'success': False
        }), 200

    images.append(img)

    ret, success = getUserFromImage(images[0])

    if success:
        return json.dumps({'error': 'Sorry, user already exists.'})

    ret, success = user.createUser(data['name'], data['starting_balance'],
                                   data['username'], data['password'], images)

    if not success:
        return json.dumps({'error': ret, 'success': False})
    else:
        return json.dumps({'success': True})
コード例 #14
0
def signUp():
    params = ['name', 'starting_balance', 'username', 'password']

    data = request.form

    for p in params:
        if p not in data:
            return json.dumps({
                'error': 'Required params missing',
                'success': False
            }), 200

    try:
        float(data['starting_balance'])
    except ValueError:
        return json.dumps({'error': 'Invalid balance', 'success': False}), 400

    files = request.files.getlist('file')

    if len(files) < 1:
        return json.dumps({
            'error': 'You need an image',
            'success': False
        }), 200

    images = []
    for file in files:
        if not allowed_file(file.filename):
            return json.dumps({'error': 'You uploaded an invalid image type'})
        filename = secure_filename(file.filename)
        tmp_file = str(random.randint(1, 1000)) + '_' + str(
            random.randint(1, 1000)) + '.' + filename.rsplit('.',
                                                             1)[1].lower()

        file.save(tmp_file)
        img = cv2.imread(tmp_file)
        os.remove(tmp_file)

        if img is None:
            return json.dumps({
                'error': 'Invalid file uploaded',
                'success': False
            }), 200

        faces = face_detector(img, 1)

        if len(faces) < 1:
            return json.dumps({
                'error':
                'Please upload different images; we cannot detect a face in at least one image',
                'success': False
            }), 200

        if len(faces) > 1:
            return json.dumps({
                'error': 'Please upload images that only has your face in it',
                'success': False
            }), 200

        images.append(img)

    ret, success = getUserFromImage(images[0])

    if success:
        return json.dumps({'error': 'Sorry, user already exists.'})

    ret, success = user.createUser(data['name'], data['starting_balance'],
                                   data['username'], data['password'], images)

    if not success:
        return json.dumps({'error': ret, 'success': False})
    else:
        return json.dumps({'success': True})
コード例 #15
0
def receive_message():
    try:
        print('Received Message')
        # get whatever message a user sent the bot
        output = request.get_json()
        for event in output['entry']:
            if ("messaging" not in event):
                print('No messages in event')
                return "Message Processed"
            messaging = event['messaging']
            for message in messaging:
            # Check if user exists in state management, if not create user
                if message.get('message'):
                    recipient_id = message['sender']['id']
                    print(recipient_id)
                    print(message)
                    print("Processing Message")
                    if (middleWare(message, recipient_id, bot) == True):
                        return "Message Processed"
                    if (recipient_id not in globalVar.userState):
                        createUser(recipient_id)
                        sendInitialMessage(recipient_id)
                        print('Created user with id ', recipient_id)
                        return "Messaged Processed"
                    else: 
                        currState = globalVar.userState[recipient_id].currState
                        if currState == 'initial':
                            startWebsite(recipient_id, message['message'].get('text'), 'text')
                            if(message['message'].get('text') == 'yes'):
                                return "test"
                        elif currState == 'insertName':
                            send_message(recipient_id, "Sorry, that's not a valid option! Please try again!", bot)
                            buttons.send_carousel(recipient_id, ACCESS_TOKEN)
                        elif currState == 'insertName2':
                            # You can validate name here
                            businessName = message['message'].get('text')
                            globalVar.userState[recipient_id].websiteName = businessName
                            responseTemp = "Your business name is " + businessName
                            send_message(recipient_id, responseTemp, bot)
                            send_message(recipient_id, globalVar.localdata["business_address"][globalVar.locale], bot)
                            globalVar.userState[recipient_id].currState = 'insertAddress'
                        elif currState == 'insertAddress':
                            addressName = message['message'].get('text')
                            globalVar.userState[recipient_id].address = addressName
                            responseTemp = "Your business address is " + addressName
                            send_message(recipient_id, responseTemp, bot)
                            send_message(recipient_id, globalVar.localdata["business_email"][globalVar.locale], bot)
                            globalVar.userState[recipient_id].currState = 'insertEmail'
                        elif currState == 'insertEmail':
                            emailName = message['message'].get('text')
                            globalVar.userState[recipient_id].email = emailName
                            responseTemp = "Your email address is " + emailName
                            send_message(recipient_id, responseTemp, bot)
                            send_message(recipient_id, globalVar.localdata["business_phoneNumber"][globalVar.locale], bot)
                            globalVar.userState[recipient_id].currState = 'insertNumber'
                        elif currState == 'insertNumber':
                            numberName = message['message'].get('text')
                            globalVar.userState[recipient_id].phoneNumber = numberName
                            responseTemp = "Your phone number is " + numberName
                            send_message(recipient_id, responseTemp, bot)
                            generateJson(recipient_id)
                            send_message(recipient_id, "Done! We have generated your site!", bot)
                            test = 'https://dynamic-website-builder.herokuapp.com'
                            send_message(recipient_id, test, bot)
                            globalVar.userState[recipient_id].currState = 'free'
                        elif currState == 'free':
                            nlp = message["message"].get("nlp")
                            entities = nlp.get("entities")
                            intent = entities.get("Intent")[0].get("value")
                            website_feat = entities.get("website_feature")[0].get("value")
                            if website_feat == "phone number":
                                web_feat_val = entities.get("phone_number")[0].get("value")
                                globalVar.userState[recipient_id].phoneNumber = web_feat_val
                                responseNLP = "Sure thing! Changing your phoneNumber"
                                send_message(recipient_id, responseNLP, bot)
                            elif website_feat == "address":
                                web_feat_val =entities.get("location")[0].get("value")
                                globalVar.userState[recipient_id].address = web_feat_val
                                responseNLP = "Sure thing! Changing your address!"
                                send_message(recipient_id, responseNLP, bot)
                            elif website_feat == "email":
                                web_feat_val =entities.get("email")[0].get("value")
                                globalVar.userState[recipient_id].email = web_feat_val
                                responseNLP = "Sure thing! Changing your email!"
                                send_message(recipient_id, responseNLP, bot)
                            elif website_feat == "title":
                                web_feat_val =entities.get("title")[0].get("value")
                                globalVar.userState[recipient_id].websiteName = web_feat_val
                                responseNLP = "Sure thing! Changing your business name!"
                                send_message(recipient_id, responseNLP, bot)
                            elif website_feat == "description":
                                web_feat_val =entities.get("slogan")[0].get("value")
                                globalVar.userState[recipient_id].slogan = web_feat_val
                                responseNLP = "Sure thing! Changing your slogan!"
                                send_message(recipient_id, responseNLP, bot)
                            finalJson = generateJson(recipient_id)
                            return "banana"
                            # Do analysis here for NLP
                if message.get('postback'):
                    recipient_id = message['sender']['id']
                    currState = globalVar.userState[recipient_id].currState
                    print(currState)
                    if currState == 'initial':
                        startWebsite(recipient_id, message, 'payload')
                    elif currState == 'selectingType':
                        startBusiness(recipient_id, message, 'payload')
                    elif currState == 'insertName':
                        print('test')
                        send_message(recipient_id, globalVar.localdata["business_name"][globalVar.locale], bot)
                        globalVar.userState[recipient_id].currState = 'insertName2'

        return "Message Processed"
    except Exception as e:
        print("There was an error bug I'm ignoring it")
        print(e)
        return "Errored out!"
コード例 #16
0
def gconnect():
    # Validate state token
    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
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('google_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 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)
    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'
        return response

    # 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

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token 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['access_token'] = credentials.access_token

    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 = answer.json()
    login_session['provider'] = 'google'
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

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

    login_session['user_id'] = user_id

    return afterlogin(login_session)