示例#1
0
def register():
    # need to sanatize input
    DB.initdb()

    resp = json.loads(flask.request.data)
    username = resp['username']
    salt, hashedpass = hashpass(resp['password'])
    print("\tfrom client: \n\tregister request:\n\tu: " + username + ", p: " +
          resp['password'])

    #is username already registered
    if (userexists(username)):
        return {'message': 'Username already taken', 'code': 'failed'}
    #is username already requested
    if (len(
            DB.query(
                "accountrequests",
                args="WHERE username = \'{u}\'".format(u=username))) == 1):
        return {'message': 'Username already taken', 'code': 'failed'}

    #submit account for approval
    try:
        DB.insert("accountrequests",
                  ("\'" + username + "\'", "\'" + hashedpass + "\'",
                   "\'" + salt + "\'", "(SELECT datetime())"))
        return {
            'message': 'registered ' + username +
            ', pending admin approval. Try logging on later.',
            'code': 'success'
        }
    except sqlite3.IntegrityError as E:
        return {'message': 'error, ' + E.__str__(), 'code': 'failed'}
示例#2
0
def createtoken(username):
    spice = os.urandom(10).hex()
    token = jwt.encode({
        'username': username,
        'spice': spice
    },
                       'secret',
                       algorithm='HS256')

    #limit of 5 tokens
    preExisting = DB.query('logintokens',
                           args='WHERE username = \'{u}\''.format(u=username))
    if len(preExisting) >= 5:
        oldest = datetime.strptime(preExisting[0][2], '%Y-%m-%d %H:%M:%S.%f')
        for row in preExisting:
            if datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S.%f') < oldest:
                oldest = datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S.%f')

        DB.delete(
            'logintokens',
            'username = \'{u}\' AND time = \'{t}\''.format(u=username,
                                                           t=str(oldest)))

    #store the payload in db
    DB.insert("logintokens", ("\'" + username + "\'", "\'" + spice + "\'",
                              "\'" + str(datetime.now()) + "\'"))
    return token.hex()
示例#3
0
def createroom():
    data = json.loads(request.data)
    if AM.checktoken(json.loads(request.data)['token'])[1] != 'admin':
        return {
            'code': 'failed',
            'message': 'Privilege level not high enough.'
        }
    print(str(data))
    if len(
            DB.query(
                'rooms',
                args='WHERE floornumber = {fn} AND roomnumber = {rn}'.format(
                    fn=data['update']['floornumber'],
                    rn=data['update']['roomnumber']))) > 0:
        return {'code': 'failed', 'message': 'Room already exists.'}

    DB.insert('rooms',
              (data['update']['floornumber'], data['update']['roomnumber'],
               "\'" + data['update']['isVaccant'] + "\'",
               "\'" + data['update']['isReady'] + "\'",
               "\'" + data['update']['description'] + "\'",
               "\'" + data['update']['price'] + "\'"))

    DB.insert(
        'room_info',
        (data['update']['floornumber'], data['update']['roomnumber'], "\'" +
         data['update']['bed'] + "\'", "\'" + data['update']['microwave'] +
         "\'", "\'" + data['update']['balcony'] + "\'",
         "\'" + data['update']['ethernet'] + "\'",
         "\'" + data['update']['TV'] + "\'", data['update']['bedamount']))

    return {'code': 'success', 'message': 'Room added to DB.'}
示例#4
0
def bookroom():
    #room id, token, date
    data = json.loads(request.data)
    floornumber = data['roomid'][:2]
    roomnumber = data['roomid'][2:]
    print(str(data))
    rows = DB.query(
        'bookings',
        args='WHERE floornumber = {fn} AND roomnumber = {rn} AND date = \"{d}\"'
        .format(fn=floornumber, rn=roomnumber, d=data['date']))

    if len(rows) > 0:
        return {
            'code': 'failed',
            'message': 'Room already booked for that date.'
        }

    userdata = AM.checktoken(data['token'])
    if userdata[0] == False:
        return {'code': 'failed', 'message': 'Invalid user token.'}
    try:
        price = DB.query(
            'rooms',
            columns='price',
            args='WHERE floornumber = {fn} AND roomnumber = {rn}'.format(
                fn=floornumber, rn=roomnumber))[0][0]
    except IndexError as E:
        return {'code': 'failed', 'message': 'No such room exists.'}
    transID = random.randint(100000, 999999)
    bookingID = random.randint(100000, 999999)

    while True:
        try:
            DB.insert('bookings',
                      (str(bookingID), "\'" + str(floornumber) + "\'",
                       "\'" + str(roomnumber) + "\'",
                       "\'" + userdata[2] + "\'", "\'" + data['date'] + "\'",
                       "\'" + data['customer_name'] + "\'"))
            break
        except sqlite3.InterfaceError as E:
            bookingID = random.randint(100000, 999999)

    while True:
        try:
            DB.insert(
                'transactions',
                (str(transID), "\'" + userdata[2] + "\'", "\'" + price + "\'",
                 str(bookingID), "\'" + data['customer_name'] + "\'"))
            break
        except sqlite3.IntegrityError as E:
            transID = random.randint(100000, 999999)

    return {
        'code': 'success',
        'message': 'Room booked.',
        'bookingID': bookingID,
        'transactionID': transID
    }
示例#5
0
def approveuser():
    data = json.loads(request.data)
    username = data['username']
    if (AM.checktoken(data['token'])[1] == 'admin'):
        row = DB.query('accountrequests',
                       args='WHERE username = \'{u}\''.format(u=username))
        DB.delete('accountrequests',
                  args='username = \'{u}\''.format(u=username))
        DB.insert(
            'users',
            ('\'' + row[0][0] + '\'', '\'' + row[0][1] + '\'', '\'' +
             row[0][2] + '\'', '\'user\'', '\'false\'', '(SELECT datetime())'))
        return {'code': 'success'}
    return {'code': 'failed'}
示例#6
0
def addClient():
    # returns code

    data = json.loads(request.data)
    account = AM.checktoken(data['token'])

    if account[1] != 'agent':
        return {'code': 'failed', 'message': 'This is not an agent account.'}

    try:
        DB.insert('agent_clients',
                  ('\'' + account[2] + '\'', '\'' + data['client_name'] + '\'',
                   '\'' + data['client_email'] + '\''))
        return {'code': 'success', 'message': 'Client added.'}
    except sqlite3.IntegrityError as E:
        return {'code': 'failed', 'message': 'Client already exists.'}