예제 #1
0
def tokenGenerator(agent, type):
    #Generate the token
    chars = 'abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    token = ''
    i = 0
    while i < 40:
        token += random.choice(chars)
        i += 1

    #Verify special agents
    if '+http://www.google.com/bot.html' in agent:
        agent = 'google';
    elif agent == 'OpenAuth':
        agent = 'google';

    #Save the token
    ts = int(time.time()*1000)
    data = readToken()
    legalTypes = ['access_token', 'authorization_code', 'refresh_token']

    if type in legalTypes:
        data[agent][type]['value'] = token
        data[agent][type]['timestamp'] = ts
        writeToken(data)
        return token
    else:
        return 'Something goes wrong'
예제 #2
0
def auth():
    token = readToken();                #Tokens from the DDBB
    clientId = request.args.get('client_id')    #ClientId from the client
    responseURI = request.args.get('redirect_uri')
    state = request.args.get('state')
    print('auth')
    if clientId == token['google']['client_id']:
        print('id_correcto')
        #Create a new authorization_code
        code = tokenGenerator('google', 'authorization_code')
        #Compose the response URL
        global responseURL
        responseURL = responseURI + '?code=' + str(code) + '&state=' +  state
        print(responseURL)
        #Return the page
        #return '<center><h1 style=\"font-size: 6em;\">Homeware LAN</h1><br><a style=\"font-size: 4em;\" class=\"btn btn-primary\" href=\"' + responseURL + '\">Pulsa aquí para enlazar</a></center>'
        return render_template('panel/googleSync.html')
    else:
        return 'Algo ha ido mal en la autorización'
예제 #3
0
def smarthome():
    #Get all data
    body = request.json
    print(body)
    #Get the agent
    agent = request.headers['User-Agent']
    #Verify special agents
    if '+http://www.google.com/bot.html' in agent:
        agent = 'google';
    elif agent == 'OpenAuth':
        agent = 'google';
    #Get the access_token
    tokenClient = request.headers['authorization'].split(' ')[1]
    data = readJSON()
    token = readToken()
    if tokenClient == token[agent]['access_token']['value']:
        #Anlalyze the inputs
        inputs = body['inputs']
        requestId = body['requestId']
        for input in inputs:
            if input['intent'] == 'action.devices.SYNC':
                print('Intent SYNC')
                obj = {}
                obj['requestId'] = requestId
                obj['payload'] = {}
                obj['payload']['agentUserId'] = '123'
                obj['payload']['devices'] = data['devices']
                response = app.response_class(
                    response=json.dumps(obj),
                    status=200,
                    mimetype='application/json'
                )
                return response
            elif input['intent'] == 'action.devices.QUERY':
                updatestates()
                data = readJSON()
                obj = {}
                obj['requestId'] = requestId
                obj['payload'] = {}
                obj['payload']['devices'] = data['status']
                response = app.response_class(
                    response=json.dumps(obj),
                    status=200,
                    mimetype='application/json'
                )
                return response
            elif input['intent'] == 'action.devices.EXECUTE':
                #Response
                obj = {}
                obj['requestId'] = requestId
                obj['payload'] = {}
                obj['payload']['commands'] = []
                obj['payload']['commands'].append({})
                obj['payload']['commands'][0]['ids'] = []
                obj['payload']['commands'][0]['status'] = 'SUCCESS'
                obj['payload']['commands'][0]['states'] = {}
                #Get ans analyze data
                data = readJSON()
                #Only the first input and the first command
                n = 0
                for command in input['payload']['commands']:
                    devices = command['devices']
                    executions = command['execution']
                    for device in devices:
                        deviceId = device['id']
                        obj['payload']['commands'][n]['ids'].append(deviceId)
                        deviceParams = executions[0]['params']

                        deviceParamsKeys = deviceParams.keys()
                        for key in deviceParamsKeys:
                            data['status'][deviceId][key] = deviceParams[key]
                        publish.single("device/"+deviceId, json.dumps(data['status'][deviceId]), hostname="192.168.19.92")

                    obj['payload']['commands'][n]['states'] = data['status']
                    n += 1
                writeJSON(data)

                response = app.response_class(
                    response=json.dumps(obj),
                    status=200,
                    mimetype='application/json'
                )
                return response
            elif input['intent'] == 'action.devices.DISCONNECT':

                return 'Ok'

            else:
                print('Intent desconocido')
    else:
        print('Token incorrecto')
        return "A"
예제 #4
0
def token():

    agent = request.headers['User-Agent']
    #Verify special agents
    if '+http://www.google.com/bot.html' in agent:
        agent = 'google';
    elif agent == 'OpenAuth':
        agent = 'google';

    grantType = request.form.get('grant_type')
    client_id = request.form.get('client_id')
    client_secret = request.form.get('client_secret')
    code = ''
    if grantType == 'authorization_code':
        code = request.form.get('code')
    else:
        code = request.form.get('refresh_token')


    #Get the tokens and ids from DDBB
    data = readJSON()
    token = readToken()
    obj = {}
    #Verify the code
    if code == token[agent][grantType]['value']:
        #Tokens lifetime
        secondsInDay = 86400;
        #Create a new token
        access_token = tokenGenerator(agent, 'access_token')
        #Compose the response JSON
        obj['token_type'] = 'bearer'
        obj['expires_in'] = secondsInDay
        if grantType == 'authorization_code':
            #Create a new token
            refresh_token = tokenGenerator(agent, 'refresh_token')
            obj['access_token'] = access_token
            obj['refresh_token'] = refresh_token
        elif grantType == 'refresh_token':
            obj['access_token'] = access_token
            obj['refresh_token'] = code


        #Clear authorization_code if autoAuthentication is not permited
        if agent == 'google':
            data = readJSON()
            token[agent]['authorization_code']['value'] = random.randrange(1000000000)
            writeJSON(data)


        ## TODO:
        #Create an alert on the status register

        #Response back
        response = app.response_class(
            response=json.dumps(obj),
            status=200,
            mimetype='application/json'
        )
        return response
    else:
        #Response back
        obj['error'] = 'invalid_grant'
        response = app.response_class(
            response=json.dumps(obj),
            status=200,
            mimetype='application/json'
        )
        return response
예제 #5
0
def front(operation, segment = "", value = ''):
    #Log in doesn't require token
    if operation == 'login':
        if segment == 'user':
            config = readConfig()
            user = request.headers['user']
            password = request.headers['pass']

            cipher_suite = Fernet(str.encode(config['key'][2:len(config['key'])]))
            plain_text = cipher_suite.decrypt(str.encode(config['pass'][2:len(config['pass'])]))
            responseData = {}
            if user == config['user'] and plain_text == str.encode(password):
                #Generate the token
                chars = 'abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
                token = ''
                i = 0
                while i < 40:
                    token += random.choice(chars)
                    i += 1
                #Saved the new token
                config = readConfig();
                config['token'] = {
                    'front': token
                }
                writeConfig(config)
                #Prepare the response
                responseData = {
                    'status': 'in',
                    'user': user,
                    'token': token
                }
            else:
                #Prepare the response
                responseData = {
                    'status': 'fail'
                }

        elif segment == 'token':
            config = readConfig()
            user = request.headers['user']
            token = request.headers['token']

            if user == config['user'] and token == config['token']['front']:
                responseData = {
                    'status': 'in'
                }
            else:
                responseData = {
                    'status': 'fail'
                }
        elif segment == 'googleSync':
            print(responseURL)
            config = readConfig()
            user = request.headers['user']
            password = request.headers['pass']

            cipher_suite = Fernet(str.encode(config['key'][2:len(config['key'])]))
            plain_text = cipher_suite.decrypt(str.encode(config['pass'][2:len(config['pass'])]))
            responseData = {}
            if user == config['user'] and plain_text == str.encode(password):
                return responseURL
            else:
                return "fail"
        response = app.response_class(
            response=json.dumps(responseData),
            status=200,
            mimetype='application/json'
        )
        return response

    #Operations not related with login
    else:
        #Verify the user token
        token = request.headers['authorization'].split(' ')[1]
        savedToken = readConfig()['token']['front'];
        if token == savedToken:
            #Read data
            data = {}
            if operation == 'read':
                if 'token' in segment:
                    dataTmp = readToken()
                    data = {
                        "client_id": dataTmp["google"]["client_id"],
                        "client_secret": dataTmp["google"]["client_secret"],
                    }
                else:
                    data = readJSON()
                    #Get the requested data
                    if segment != '':
                        for p in segment.split('>'):
                            data = data[p]

                response = app.response_class(
                    response=json.dumps(data),
                    status=200,
                    mimetype='application/json'
                )
                return response
            #Save simple data
            #Write data
            elif operation == 'write':
                data = {}
                if 'token' in segment:
                    data = readToken()
                    data["google"]["client_id"] = json.loads(value)['client_id']
                    data["google"]["client_secret"] = json.loads(value)['client_secret']
                    writeToken(data)
                else:
                    data = readJSON()
                    segments = segment.split('>')
                    #Esto es una ñapa, pero ahora mismo no se cómo solucionarlo
                    if len(segments) == 1:
                        data[segment] = json.loads(value)
                    elif len(segments) == 2:
                        data[segments[0]][segments[1]] = json.loads(value)
                    elif len(segments) == 3:
                        data[segments[0]][segments[1]][segments[2]] = json.loads(value)
                    writeJSON(data)

                response = app.response_class(
                    response=json.dumps(data),
                    status=200,
                    mimetype='application/json'
                )

                return response
            #Special operations
            elif operation == 'device':
                data = readJSON()

                if segment == 'update' or segment == 'create':
                    incommingData = json.loads(value)
                    deviceID = incommingData['devices']['id']

                    #Updating device or create device
                    if segment == 'update':
                        temp_devices = [];
                        for device in data['devices']:
                            if device['id'] == incommingData['devices']['id']:
                                temp_devices.append(incommingData['devices'])
                            else:
                                temp_devices.append(device)
                        data['devices'] = temp_devices
                    else:
                        data['devices'].append(incommingData['devices'])

                    #Update alive
                    data['alive'][deviceID] = incommingData['alive']
                    #Update status
                    if not deviceID in data['status'].keys():
                        data['status'][deviceID] = {}
                    #Create dummy status using selected traits
                    with open('paramByTrait.json', 'r') as f:
                        paramByTrait = json.load(f)
                        for trait in incommingData['devices']['traits']:
                            for paramKey in paramByTrait[trait].keys():
                                data['status'][deviceID][paramKey] = paramByTrait[trait][paramKey]

                    data['status'][deviceID]['online'] = True

                elif segment == 'delete':
                    temp_devices = [];
                    for device in data['devices']:
                        if device['id'] != value:
                            temp_devices.append(device)
                    data['devices'] = temp_devices
                    # Delete status
                    status = data['status']
                    del status[value]
                    data['status'] = status
                    # Delete alive
                    alive = data['alive']
                    del alive[value]
                    data['alive'] = alive

                writeJSON(data)

                response = app.response_class(
                    response=json.dumps(data),
                    status=200,
                    mimetype='application/json'
                )
                return response
            #Special operations
            elif operation == 'rule':
                data = readJSON()
                if segment == 'update':
                    incommingData = json.loads(value)
                    data['rules'][int(incommingData['n'])] = incommingData['rule']
                if segment == 'create':
                    incommingData = json.loads(value)
                    data['rules'].append(incommingData['rule'])

                elif segment == 'delete':
                    temp_rules = data['rules']
                    del temp_rules[int(value)]
                    data['rules'] = temp_rules

                writeJSON(data)

                response = app.response_class(
                    response=json.dumps(data),
                    status=200,
                    mimetype='application/json'
                )
                return response

        else:
            return 'Bad token'