Пример #1
0
    'update users set fail_login_counter=0,fail_login_timestamp=0 where id=' +
    str(auth.user_id))
mydb.execute('select id,`default` from devices where uid=' +
             str(auth.user_id) + ' and name="' + jsonpost['device'] +
             '" and state>0')
dev = mydb.fetchone()
if dev is None:  # Need to add new device to user
    mydb.execute('insert into devices set `default`=0, uid=' +
                 str(auth.user_id) + ', name="' + jsonpost['device'] +
                 '", state=1, created=' + timestamp_string + ', lastconnect=' +
                 timestamp_string)
    auth.user_some_state = mydb_connection.insert_id()
    _mobile.log('New device added id:' + str(auth.user_some_state))
else:
    if int(dev['default']) > 0:
        headers.errorResponse('You can not use this device name')
    auth.user_some_state = int(dev['id'])

if auth.user_some_state < 1:
    wrongCred(4)

auth.credentials = auth.buildCredentials(int(auth.user_id), jsonpost['login'],
                                         jsonpost['password'], 1,
                                         auth.user_some_state)
headers.jsonAPI(False)
_mobile.log('Token was sent to device id:' + str(auth.user_some_state))
headers.goodResponse({
    'accepted': True,
    'token': auth.credentials
}, translation.getValue('registration_success'))
Пример #2
0
import inspect
import os
import sys

currentdir = os.path.dirname(os.path.abspath(
        inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.dirname(os.path.dirname(currentdir)))
from _common.api import auth
from _common.api import headers
from _common.api import db

headers.jsonAPI()
ext_links = db.getUserLinkedDevices(auth.user_id)
ext_link_names = ext_links['names']
ext_link_ids = ext_links['all']
linked_devices = []
for key in ext_link_ids:
    obj = {'id': ext_link_ids[key],
           'name': ext_link_names[ext_link_ids[key]]['device'].title(),
           'user': (ext_link_names[ext_link_ids[key]]['user'] or '').title()
           }
    linked_devices.append(obj)
own_devices = db.getUserOwnDevices(auth.user_id)
headers.goodResponse({'login': auth.user_login,
                      'some_state': auth.user_some_state,
                      'all_devices': [{'id': 0, 'name': '@str.all_devices'}],
                      'own_devices': own_devices['all'],
                      'linked_devices': linked_devices
                      })
Пример #3
0
src = safeGETint('src')
if src < 0:
    headers.errorResponse('@str.permission_denied')
dst = safeGETint('dst')
db.sql_request('select id from devices where id=' + str(src) + ' and uid=' +
               str(auth.user_id) + ' and state>0 and `default`=0')
row = db.mydb.fetchone()
if (row is None) or ('id' not in row) or (row['id'] is None) or (int(
        row['id']) < 1) or (int(row['id']) != src):
    headers.errorResponse('@str.permission_denied')

if dst > 0:
    db.sql_request('select id from devices where id=' + str(dst) +
                   ' and uid!=' + str(auth.user_id) + ' and state>0')
    row = db.mydb.fetchone()
    if (row is None) or ('id' not in row) or (row['id'] is None) or (int(
            row['id']) < 1) or (int(row['id']) != dst):
        headers.errorResponse('@str.permission_denied')
else:
    db.sql_request('update devices set sync0=' + str(sync0) + ',sync1=' +
                   str(sync1) + ',sync2=' + str(sync2) + ',sync3=' +
                   str(sync3) + ' where id=' + str(src))
    headers.goodResponse({'saved': True})

db.sql_request('update sync_devices set sync0=' + str(sync0) + ',sync1=' +
               str(sync1) + ',sync2=' + str(sync2) + ',sync3=' + str(sync3) +
               ' where src=' + str(src) + ' and dst=' + str(dst) +
               ' and state>0')
headers.goodResponse({'saved': True})
Пример #4
0
import inspect
import os
import sys

currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.dirname(os.path.dirname(currentdir)))
from _common.api import auth
from _common.api import headers
from mobile_service.apiv1 import _mobile

headers.jsonAPI()
devid = auth.user_some_state
if (auth._POST is None):  # only POST accepted
    _mobile.elog('No posted info uid:' + auth.user_id)
    headers.errorResponse('Wrong information')
json = auth._POST
if 'need_tasks' not in json:
    _mobile.elog('Incorrect tasks uid:' + auth.user_id)
    headers.errorResponse('Nothing was sent')
tasks = json['need_tasks']
if len(tasks) < 1:
    headers.errorResponse('No requested information was sent')
obj = _mobile.getTotalIdsString(user_id=auth.user_id,
                                devid=auth.user_some_state,
                                cross=tasks,
                                extendType=1)
if obj is None:
    headers.errorResponse('SQL error')
headers.goodResponse(obj)
Пример #5
0
    auth.user_id) + ')'
try:
    mydb.execute(sql)
except Exception as ex:
    utils.log(utils.clearUserLogin(str(ex)), 'error', 'mobile')
    headers.errorResponse('Can not remove dest sync devices')

sql = 'delete from sync_tasks where dst in (select id from devices where uid=' + str(
    auth.user_id) + ')'
try:
    mydb.execute(sql)
except Exception as ex:
    utils.log(utils.clearUserLogin(str(ex)), 'error', 'mobile')
    headers.errorResponse('Can not remove tasks sync links')

sql = 'delete from devices where uid=' + str(auth.user_id) + ''
try:
    mydb.execute(sql)
except Exception as ex:
    utils.log(utils.clearUserLogin(str(ex)), 'error', 'mobile')
    headers.errorResponse('Can not remove devices')

sql = 'delete from users where id=' + str(auth.user_id) + ''
try:
    mydb.execute(sql)
except Exception as ex:
    utils.log(utils.clearUserLogin(str(ex)), 'error', 'mobile')
    headers.errorResponse('Can not remove user account')
headers.goodResponse({'status': True},
                     translation.getValue('remove_account_message'))
Пример #6
0
                           devid=auth.user_some_state,
                           myself=False,
                           cache=False)  # except myself
result = {'own': [], 'in': [], 'out': []}
def_id = db.getDefaultDevice(auth.user_id)
for dev in own['all']:
    if (dev['id'] == def_id) or (dev['id'] == auth.user_id):
        continue
    result['own'].append({'id': dev['id'], 'device': dev['name']})

for key in links['in']['all']:
    dev = links['in']['all'][key]
    result['in'].append({
        'id': dev,
        'device': links['names'][dev]['device'],
        'user': links['names'][dev]['user']
    })

for key in links['out']['all']:
    dev = links['out']['all'][key]
    result['out'].append({
        'id': dev,
        'device': links['names'][dev]['device'],
        'user': links['names'][dev]['user']
    })

if len(result['out']) < 1 and len(result['in']) < 1 and len(result['own']) < 1:
    headers.errorResponse(
        'No devices available.\nInvite new devices on settings page')
headers.goodResponse(result)
Пример #7
0
                                                        month=row['month'], day=row['day'], hour=row['hour'],
                                                        minute=row['minute'])
            event['start'] = str(task_time_obj['year']) + '-' +\
                             str(task_time_obj['month']).rjust(2, '0') + '-' +\
                             str(task_time_obj['day']).rjust(2, '0') + 'T' +\
                             str(task_time_obj['hour']).rjust(2, '0') + ':' +\
                             str(task_time_obj['minute']).rjust(2, '0') +\
                             ':00'
            if (row['duration_time'] > 0):
                task_time_obj = date_utils.getHumanTime(timezone_offset=row['timezone'],
                                                        timestamp=task_time_obj['timestamp'] +\
                                                                  (row['duration_time'] * 60 * 1000))
                event['end'] = str(task_time_obj['year']) + '-' +\
                               str(task_time_obj['month']).rjust(2, '0') + '-' +\
                               str(task_time_obj['day']).rjust(2, '0') + 'T' +\
                               str(task_time_obj['hour']).rjust(2, '0') + ':' +\
                               str(task_time_obj['minute']).rjust(2, '0') +\
                               ':00'
    else:
        task_time_obj = date_utils.getHumanTime(timezone_offset=row['timezone'],
                                                timestamp=row['done_time'])
        event['start'] = str(task_time_obj['year']) + '-' +\
                         str(task_time_obj['month']).rjust(2, '0') + '-' +\
                         str(task_time_obj['day']).rjust(2, '0') + 'T' +\
                         str(task_time_obj['hour']).rjust(2, '0') + ':' +\
                         str(task_time_obj['minute']).rjust(2, '0') +\
                         ':00'
        event['color'] = '#d7d7d7'
    json_result.append(event)
headers.goodResponse({'events': json_result}, toastMessage)
Пример #8
0
# check permissions
for device in all_devices:
    if not (device in check_list):
        to_remove_from.append(device)

for remover in to_remove_from:
    all_devices.remove(remover)  # TODO

# tids_str = "'" + "','".join(tasks_arr) + "'"
# sql_request("delete from sync_tasks where tid in ("+tids_str+") and dst in ("++")")

if duplicate:
    sql_request_ignore_error('START TRANSACTION')
    for device in all_devices:
        for task in tasks_arr:
            db.duplicateTask(task, device)
    sql_request_ignore_error('COMMIT')
    headers.goodResponse({'status': True},
                         translation.getValue('duplicate_complete'))
else:
    sql_request_ignore_error('START TRANSACTION')
    for device in all_devices:
        for task in tasks_arr:
            sql = 'insert ignore into sync_tasks (dst,tid,sender) values (' + str(
                device) + ',' + str(task) + ',' + str(auth.user_id) + ')'
            sql_request_ignore_error(sql)

    sql_request_ignore_error('COMMIT')
    headers.goodResponse({'status': True},
                         translation.getValue('sharing_complete'))
Пример #9
0
if usr['fail_login_counter'] is None:
    usr['fail_login_counter'] = 0

timestamp_int = int(time.time() * 1000)
if (abs(timestamp_int - int(usr['fail_login_timestamp'])) < 60 * 1000) and (int(usr['fail_login_counter']) > 5):
    auth.credentials = auth.buildCredentials(0, '', '', 0, 0)
    headers.jsonAPI(False)
    time.sleep(1)
    headers.errorResponse('@str.wait_1_min', '@str.attention', 403)

timestamp_string = str(timestamp_int)
if usr['password'] != jsonpost['password'] or int(usr['state']) < 1:
    mydb.execute(
            'update users set fail_login_counter=(fail_login_counter+1),fail_login_timestamp=' + timestamp_string + ' where id=' + str(
                    usr['id']))
    wrongCred()  # auth fail

auth.user_id = int(usr['id'])  # before! buildCredentials call
if auth.isMobile:
    badExit()  # using this form from mobile app APIs is not permitted
else:
    mydb.execute('update users set fail_login_counter=0,fail_login_timestamp=0,lastlogin='******' where id=' + str(auth.user_id))

auth.credentials = auth.buildCredentials(
        auth.user_id, usr['login'], usr['password'], jsonpost['remember'], auth.user_some_state)
headers.jsonAPI(False)  # New cookie always there
utils.log(usr['login'] + ' Logged in', 'auth')
headers.goodResponse({'accepted': True})

Пример #10
0
            minute=row['minute'])
        timestamp = task_time_obj['timestamp']
        for i in range(7):
            if (timestamp < days_time[i]):
                timers[i]['data'].insert(0, row)
                break
    elif (row['type'] == 0):
        if (row['utc_flag'] != 0):
            timestamp = row['start_time']
        else:
            if (row['day'] == 0):
                bug_obj = date_utils.getHumanTime(row['timezone'],
                                                  row['start_time'])
                row['day'] = bug_obj['day']
                row['month'] = bug_obj['month']
            task_time_obj = date_utils.getTimestamp(
                timezone_offset=row['timezone'],
                year=row['year'],
                month=row['month'],
                day=row['day'],
                hour=row['hour'],
                minute=row['minute'])
            timestamp = task_time_obj['timestamp']
        for i in range(7):
            if (timestamp < days_time[i]):
                timers[i]['data'].append(row)
                break
    # row['hour']=str(row['hour']).rjust(2, '0')
    row['minute'] = str(row['minute']).rjust(2, '0')
headers.goodResponse({'timers': timers}, toastMessage)
Пример #11
0
    for row in linksOut:
        if row['src'] == selected:
            obj = {
                'color': 0,
                'id': row['src'],
                'dst': row['dst'],
                'device': linked['names'][row['dst']]['device'],
                'user': linked['names'][row['dst']]['user'],
                'sync0': row['sync0'],
                'sync1': row['sync1'],
                'sync2': row['sync2'],
                'sync3': row['sync3']
            }
            selLinks.append(obj)
    headers.goodResponse({'nodes': nodes, 'edges': edges, 'links': selLinks})

if (selected > 0) and not our_device_selected:
    selLinks = []
    for row in linksIn:
        if row['dst'] == selected:
            if row['src'] in own['names']:
                obj = {
                    'id': row['src'],
                    'color': 2,
                    'dst': row['dst'],
                    'device': own['names'][row['src']],
                    'sync0': row['sync0'],
                    'sync1': row['sync1'],
                    'sync2': row['sync2'],
                    'sync3': row['sync3']
Пример #12
0
    headers.errorResponse('You already have full access to your own devices')

sql_request('select id, state, invite from sync_devices where src=' +
            str(my_device) + ' and dst=' + str(another_device))
link_id = 0
link_state = 0
link_invite = ''
rows = mydb.fetchall()
for row in rows:
    link_id = int(row['id'])
    link_state = int(row['state'])
    link_invite = row['invite']
if link_state > 0:
    headers.errorResponse('You already can send information to this device')

if link_id > 0:
    if len(link_invite) > 3:
        headers.goodResponse({'invite': link_invite.upper()})
    link_invite = utils.rand_string(5)
    sql_request('update sync_devices set state=0,invite="' + link_invite +
                '" where id=' + str(link_id))

else:
    link_invite = utils.rand_string(5)
    sql_request(
        'insert into sync_devices (src,dst,state,invite,created) values (' +
        str(my_device) + ',' + str(another_device) + ',0,"' + link_invite +
        '",' + str(int(time.time() * 1000)) + ')')
headers.goodResponse({'invite': link_invite.upper()},
                     '\n' + link_invite.upper() + '\n')
Пример #13
0
    {
        'state': 40,
        "id": "canceled",
        'pname': '@str.canceled',
        'items': []
    }

]
items_20 = panels[0]['items']
items_30 = panels[1]['items']
items_40 = panels[2]['items']

sql_filter = db.buildSqlPermissionfilter(auth.user_id, devid, True)
sql = 'select * from tasks t where t.type=2 and ' + sql_filter + ' order by t.state, t.priority desc,t.created desc limit 600'
db.sql_request(sql)
rows = mydb.fetchall()
json_result = []
toastMessage=None
if (rows is None) or len(rows) < 1:
    toastMessage='@str.no_notes'
for row in rows:
    obj = {'id': row['id'], 'title': row['title'], 'desc': row['desc'], 'priority': row['priority']}
    if row['state'] == 20:
        items_20.append(obj)
    elif row['state'] == 30:
        items_30.append(obj)
    elif row['state'] == 40:
        items_40.append(obj)

headers.goodResponse({'panels': panels},toastMessage)
if len(your_arr) < 1 and len(out_arr) < 1 and len(in_arr) < 1:
    headers.errorResponse(
            "You can not remove current and default devices.\nBut you can erase your account from server")

if len(out_arr) > 0:
    req_filter = ",".join(list(out_arr))
    sql_request(
            "delete from sync_devices where src=" + str(auth.user_some_state) + " and dst in (" + req_filter + ")")
    sql_request("""delete sync_tasks from sync_tasks 
             inner join tasks as t on t.id=sync_tasks.tid and t.devid=""" + str(auth.user_some_state) + """
             where sync_tasks.dst in (""" + req_filter + ")")

if len(in_arr) > 0:
    req_filter = ",".join(list(in_arr))
    sql_request(
            "delete from sync_devices where dst=" + str(auth.user_some_state) + " and src in (" + req_filter + ")")
    sql_request("""delete sync_tasks from sync_tasks 
             inner join tasks as t on t.id=sync_tasks.tid and t.devid in (""" + req_filter + """) 
             where sync_tasks.dst in (""" + str(auth.user_some_state) + ")")

if len(your_arr) > 0:
    req_filter = ",".join(list(your_arr))
    sql_request(
            "update tasks set devid=" + str(
                auth.user_some_state) + " where devid in (" + req_filter + ") and devid in (select id from devices where uid=" + str(
                auth.user_id) + ")")
    sql_request(
            "delete from devices where id in (" + req_filter + ") and uid=" + str(auth.user_id))

headers.goodResponse({'status': True}, translation.getValue('device_link_removed'))
Пример #15
0
# After updating we check db values and CRC32,
# if they are different - need to check
obj = _mobile.getTotalIdsString(user_id=auth.user_id,
                                devid=auth.user_some_state,
                                extendType=2)
if obj is None:
    headers.errorResponse('SQL error')
if (mobile_time != obj['time'] or (mobile_serial != obj['serial'])
        or (mobile_count != obj['count'])
        or (mobile_crc32 != utils.crc32(obj['info']['ids']))):
    headers.goodResponse({
        'saved': {
            'state': True,
            'ids': ','.join(saved_ids),
            'broken': ','.join(broken_ids),
            'remove': ','.join(remove_ids),
        },
        'diff': {
            'state': True,
            'info': obj['info']
        }
    })
else:
    headers.goodResponse(
        {
            'saved': {
                'state': True,
                'ids': ','.join(saved_ids),
                'broken': ','.join(broken_ids),
                'remove': ','.join(remove_ids),
            },
            'diff': {
Пример #16
0
currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.dirname(os.path.dirname(currentdir)))
from _common.api._settings import mydb
from _common.api import auth
from _common.api import headers
from _common.api import utils
from _common.api import translation
from mobile_service.apiv1._mobile import sql_request

headers.jsonAPI()

jsonpost = auth._POST
if (jsonpost is None) or ('invite' not in jsonpost):
    headers.errorResponse('Bad request')
invite = utils.clearStringHard(str(jsonpost['invite']))[:7].lower()
if len(invite) < 3:
    headers.errorResponse('Too short invite')
sql_request('select id from sync_devices where (dst=' +
            str(auth.user_some_state) + ') and invite="' + invite + '"')
row = mydb.fetchone()
id = 0
if row is None:
    headers.errorResponse('Not found')
id = int(row['id'])
if id < 1:
    headers.errorResponse('Not found')

sql_request('update sync_devices set invite="", state=1 where id=' + str(id))
headers.goodResponse({'state': True}, translation.getValue('confirm_invite'))