def run(self):
        # Return All the users in the User table
        self.log = Logger('DashboardEnrollmentStatusGetHandlerThread')
        # TAG = 'run'

        # ToDo : replace this with dynamic company id from cookies.
        company_id = self.company_id

        return_dict = {}
        user = UserDBHelper()
        violation = ViolationsDBHelper()
        enrollment = EnrollmentDBHelper()

        violation_count = violation.get_violation_count(company_id=company_id)
        not_enrolled_count = enrollment.get_enrollment_status_count(
            company_id=company_id, status=False)
        enrolled_count = enrollment.get_enrollment_status_count(
            company_id=company_id, status=True)

        print "\n printing enrolled count", not_enrolled_count
        user_count = user.get_users_count(company_id=company_id)

        user_info_dict = {}
        user_info_dict['Violations'] = violation_count
        user_info_dict['Not Enrolled'] = not_enrolled_count
        user_info_dict['Enrolled'] = enrolled_count
        user_info_dict['Total Users'] = user_count
        return_dict['UserInformation'] = user_info_dict

        opJson = json.dumps({'message': 'Everything seems to be working ...',
                             'data': return_dict, 'pass': True})
        #self.request.add_header('Access-Control-Allow-Origin', '*')
        self.request.set_header('Content-Type', 'application/json')
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #2
0
    def run(self):
        #Return All the users in the User table
        self.log = Logger('DashboardViolationGetHandlerThread')
        TAG = 'run'

        company_id= self.company_id

        offset = self.request.get_argument('offset', None)
        count = self.request.get_argument('count', None)
        date_handler = lambda obj: obj.isoformat() if isinstance(obj,
                                         datetime.datetime) else None

        violation = ViolationsDBHelper()
        violation_list, total_count = violation.get_violations_with_pages(
                            company_id=company_id, offset=offset, count=count)
        #print "\nprinting violations list here\n", violation_list
        if violation_list is None or len(violation_list) == 0:
            self.log.i(TAG, 'No violations found')
            pass_status = True
            violation_list = []
        else:
            pass_status = True

        opJson = json.dumps({'data':violation_list, 'count':total_count,
                    'message':'Seems like things are working ...',
                    'pass':pass_status}, default=date_handler)
        #self.request.add_header('Access-Control-Allow-Origin', '*')
        self.request.set_header('Content-Type', 'application/json')
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #3
0
    def run(self):
        # Return All the users in the User table
        self.log = Logger('DashboardViolationGetHandlerThread')
        TAG = 'run'

        company_id = self.company_id

        offset = self.request.get_argument('offset', None)
        count = self.request.get_argument('count', None)
        date_handler = lambda obj: obj.isoformat() if isinstance(
            obj, datetime.datetime) else None

        violation = ViolationsDBHelper()
        violation_list, total_count = violation.get_violations_with_pages(
            company_id=company_id, offset=offset, count=count)
        # print "\nprinting violations list here\n", violation_list
        if violation_list is None or len(violation_list) == 0:
            self.log.i(TAG, 'No violations found')
            pass_status = True
            violation_list = []
        else:
            pass_status = True

        opJson = json.dumps(
            {
                'data': violation_list,
                'count': total_count,
                'message': 'Seems like things are working ...',
                'pass': pass_status
            },
            default=date_handler)
        #self.request.add_header('Access-Control-Allow-Origin', '*')
        self.request.set_header('Content-Type', 'application/json')
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #4
0
    def run(self):
        # Return All the users in the User table
        self.log = Logger('DashboardEnrollmentStatusGetHandlerThread')
        # TAG = 'run'

        # ToDo : replace this with dynamic company id from cookies.
        company_id = self.company_id

        return_dict = {}
        user = UserDBHelper()
        violation = ViolationsDBHelper()
        enrollment = EnrollmentDBHelper()

        violation_count = violation.get_violation_count(company_id=company_id)
        not_enrolled_count = enrollment.get_enrollment_status_count(
            company_id=company_id, status=False)
        enrolled_count = enrollment.get_enrollment_status_count(
            company_id=company_id, status=True)

        print "\n printing enrolled count", not_enrolled_count
        user_count = user.get_users_count(company_id=company_id)

        user_info_dict = {}
        user_info_dict['Violations'] = violation_count
        user_info_dict['Not Enrolled'] = not_enrolled_count
        user_info_dict['Enrolled'] = enrolled_count
        user_info_dict['Total Users'] = user_count
        return_dict['UserInformation'] = user_info_dict

        opJson = json.dumps({
            'message': 'Everything seems to be working ...',
            'data': return_dict,
            'pass': True
        })
        #self.request.add_header('Access-Control-Allow-Origin', '*')
        self.request.set_header('Content-Type', 'application/json')
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #5
0
    def run(self):
        log = Logger('CheckInHandler PUT')
        TAG = 'run'
        # print ' In deviceCheckin PUT Handler\n\n\n'

        # parse the body of PUT
        # First extract the XML
        arguments = cgi.parse_qsl(self.request.request.body)
        intermediate = arguments[0]
        currentxml = intermediate[1]
        final = currentxml[25:-1]
        enrollment_id = str(self.data)
#         print final

        # Actual Parsing
        #tree = ET.ElementTree(ET.fromstring(final))
# tree = ET.parse('temp.xml')   ### For testing only
        node = etree.fromstring(final)
        device_data = []
        for text_of_child in node.itertext():
            if len(text_of_child.strip()) > 0:
                device_data.append(text_of_child.strip())
        device_data = dict(zip(device_data[::2], device_data[1::2]))

        if device_data.get('PushMagic'):
            self.push_magic = str(device_data.get('PushMagic'))

        if device_data.get('Token'):
            self.device_token = str(device_data.get('Token'))
            self.device_token = self.device_token.replace(' ', '+')
            self.device_token = self.device_token.replace('\n', '')
            self.device_token = self.device_token.replace('\t', '')
            # print len(self.device_token)
            # print self.device_token
        if device_data.get('MessageType'):
            message = device_data.get('MessageType')
            if message == 'TokenUpdate':
                self.do_entry = True
            elif message == 'Authenticate':
                self.do_initial_entry = True

        if device_data.get('UnlockToken'):
            self.unlock_token = device_data.get('UnlockToken')
            self.unlock_token = self.unlock_token.replace(' ', '+')
            self.unlock_token = self.unlock_token.replace('\n', '')
            self.unlock_token = self.unlock_token.replace('\t', '')

        if device_data.get('UDID'):
            self.udid = device_data.get('UDID')

        ### Initial Device DB Entries ###
        if self.do_entry:
            enrolled_success = False
            device_id = None
            # fetch info from enrollment table
            enrollment = EnrollmentDBHelper()

            enrollment_dict = enrollment.get_enrollment(enrollment_id)
            # print 'enrollment_dict = ' + str(enrollment_dict)
            if enrollment_dict is None:
                log.e(TAG,
                      'No user ID in Enrollment table. Enrollment ID = '
                      + str(enrollment_id))
                reply = """
                    <html>
                        <body>401</body>
                    </html>
                    """
                self.request.set_status(401)
                self.request.write(reply)
                ioloop.IOLoop.instance().add_callback(self.callback)

            else:

                reply = """
            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                         "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                        <plist version="1.0">
                        <dict>
                        </dict>
                        </plist>
                """
                print 'inner write'
                self.request.write(reply)
                ioloop.IOLoop.instance().add_callback(self.callback)

                device = DeviceDBHelper()
                violation = ViolationsDBHelper()
                user_id = str(enrollment_dict[c.ENROLLMENT_TABLE_USER])
                device_id = enrollment_dict.get(c.ENROLLMENT_TABLE_DEVICE)
                devices = device.get_device_with_udid(
                    str(self.udid), status=True)
                # print "\n print devices list if available \n\n",devices
                device_detail = DeviceDetailsDBHelper()
                device_details_dict = {
                    'token': self.device_token,
                    'push_magic': self.push_magic,
                    'unlock_token': self.unlock_token
                }

                if device_id:

                    enrolled_success = True
                    device.update_device(str(device_id),
                                         {c.DEVICE_TABLE_DELETED: False,
                                          c.DEVICE_TABLE_UDID: str(self.udid)})
                    device_detail.update_device_details(str(device_id),
                                                        device_details_dict)
                    print "Device details table updated."

                elif devices:
                    device_id = devices[0][c.DEVICE_TABLE_ID]
                    device.update_device(str(device_id),
                                         {c.DEVICE_TABLE_DELETED: False})
                    device_detail.update_device_details(str(device_id),
                                                        device_details_dict)
                    enrollment.update_enrollment(
                        enrollment_id, {
                            c.ENROLLMENT_TABLE_DEVICE: str(device_id)})
                    enrollment.set_enrolled(enrollment_id)
                    enrolled_success = True

                else:
                    # print 'user_id = ' + user_id
                    device_dict = {c.DEVICE_TABLE_USER: user_id,
                                   c.DEVICE_TABLE_OS: 'ios',
                                   c.DEVICE_TABLE_UDID: str(self.udid),
                                   c.DEVICE_TABLE_DELETED: False}
                    device_id = device.add_device(device_dict)
                    if device_id is None:
                        log.e(TAG,
                              'Not Able to insert in Device table UDID = '
                              + str(self.udid) + 'userID = ' + str(user_id))
                    else:
                        device_details_dict_new = {}
                        device_details_dict_new[
                            c.DEVICE_DETAILS_TABLE_DEVICE] = device_id
                        device_details_dict_new[
                            c.DEVICE_DETAILS_TABLE_EXTRAS] = device_details_dict
                        device_details_id = device_detail.add_device_detail(
                            device_details_dict_new)

                        # print 'device_details_id = ' + str(device_details_id)
                        if device_details_id is None:
                            log.e(TAG, 'Not Able to insert in Device Details \
                                  table UDID = ' +
                                  str(self.udid) +
                                  'userID = ' +
                                  str(user_id) +
                                  'DeviceID = ' +
                                  str(device_id))
                        else:

                            success = enrollment.update_enrollment(
                                enrollment_id,
                                {c.ENROLLMENT_TABLE_DEVICE: str(device_id)})
                            if not success:
                                log.e(TAG,
                                      'enrollment device table not linked')
                            else:
                                success1 = enrollment.set_enrolled(
                                    enrollment_id)

                                if success1:
                                    enrolled_success = True
                                else:
                                    log.e(
                                        TAG,
                                        'EnrolledOn time is not updated in \
the Enrollment Table')

                if device_id and enrolled_success:

                    violation_status = violation.update_violations(
                        str(device_id))
                    user = UserDBHelper()
                    user_info = user.get_user(user_id)
                    if violation_status:
                        log.i(TAG,
                              "Violation table updated for device_id" + str(
                                  device_id))
                    else:
                        log.e(
                            TAG,
                            "Violation table not updated for device_id" +
                            str(device_id))

                    ### Add task to Queue for celery Worker. ###
                    json_data = {'to': 'user', 'action': 'device_information',
                                 'id': user_id}
                    json_data['company_id'] = user_info.get('company_id')

                    create_command_handler_task.delay(json_data)

                    ### Now send polling Signal to device ###
                    wrapper = APNSNotificationWrapper(
                        '/opt/toppatch/assets/ios/PushCert.pem', False)
                    message = APNSNotification()
                    message.appendProperty(APNSProperty("mdm",
                                                        str(self.push_magic)))
                    message.tokenBase64(str(self.device_token))
                    wrapper.append(message)
                    wrapper.notify()

                    print 'Payload Sent'

        elif device_data.get('MessageType') == 'CheckOut':
            reply = """
                    <html>
                        <body>401</body>
                    </html>
                    """
            self.request.set_status(401)
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)

            violation = ViolationsDBHelper()
            device = DeviceDBHelper()
            enrollment = EnrollmentDBHelper()
            devices = device.get_device_with_udid(self.udid)
            if devices is None:
                log.e(TAG, 'No User ID Associated with Device UDID = '
                           + self.udid)
            else:
                device_id = devices[0][c.DEVICE_TABLE_ID]
                violation_id = violation.add_violation(str(device_id))
                if violation_id is None:
                    log.e(TAG, 'Not able to insert in Violation Table.\
                               DeviceID = ' + str(device_id))
                else:
                    device.delete_device(device_id)
                    enrollment.update_enrollment(
                        str(enrollment_id), {
                            'device_id': "null", 'is_enrolled': False})
                    log.i(TAG, 'Violation added for device id = ' +
                               str(device_id))
                    admin_mailer(device_id, violation_id)

        else:
            reply = """
            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
             "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
            """
            print 'outer write'
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #6
0
    def run(self):
        TAG = 'run'

        print ' In IOSCommandPerformer\'s PUT'
        command = IOSCommandDBHelper()
        invoke_flag = False
        arguments = cgi.parse_qsl(self.request.request.body)
        intermediate = arguments[0]
        currentxml = intermediate[1]
        final = currentxml[25:-1]  # Original Line
        # final = currentxml[20:]  ### For testing only
        # print '\n\n\n here is final xml \n\n', final
        # temp Parsing
        # tree = ET.ElementTree(ET.fromstring(final))  ##Original Line
        # tree = ET.parse('temp.xml')   ### For testing only
        initial_list = []
        initial_dict = {}

        check_out_requested = False
        send_command = False
        store_result = False
        store_error = False
        registered = True
        special_result = False
        acknowledged = False
        update_token = False

        object_root = objectify.fromstring(final)

        begin = object_root.dict

        for child in begin.iterchildren():
            initial_list.append(child.text)

        initial_dict = dict(zip(initial_list[::2], initial_list[1::2]))
        # print '\n\n print here initial dict\n', initial_dict

        if 'UDID' in initial_dict:
            udid = initial_dict.get('UDID')
            device = DeviceDBHelper()
            registered = device.is_udid_registered(str(udid))

        if 'Status' in initial_dict:
            status = initial_dict.get('Status')
            if status == 'Idle':
                send_command = True
            elif status == 'Acknowledged':
                acknowledged = True
            elif status == 'Error':
                store_error = True
                uuid = initial_dict.get('CommandUUID')

        if 'MessageType' in initial_dict:
            message = initial_dict.get('MessageType')
            if message == 'TokenUpdate':
                update_token = True
            elif message == 'CheckOut':
                check_out_requested = True
        push_magic = 'push_magic'
        token = 'Token'
        unlock_token = 'UnlockToken'

        if registered is False:
            reply = """

                    """
            self.request.set_status(401)
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            device_id = str(device.get_device_with_udid(udid)[0]['id'])
            print 'reached here '
        if acknowledged:
            if 'CommandUUID' in initial_dict:
                uuid = initial_dict.get('CommandUUID')
                # special uuid for device information
                if uuid == '55555555-5555-5555-5555-555555555555' + device_id:
                    info_list = [
                        el.text if el.text else el.tag
                        for el in object_root.iterdescendants()
                    ]
                    info_list.pop(0)
                    final = dict(zip(info_list[::2], info_list[1::2]))
                    store_result = True
                    special_result = True
                # special uuid for installed application list
                elif uuid == ('77777777-7777-7777-7777-777777777777' +
                              device_id):
                    begin = object_root.dict.array
                    apps_list = []
                    for outer_child in begin.iterchildren():
                        temp_list = []
                        for inner_child in outer_child.iterchildren():
                            temp_list.append(inner_child.text)
                        apps_list.append(
                            dict(zip(temp_list[::2], temp_list[1::2])))
                    final = apps_list
                    store_result = True
                    invoke_flag = True
                else:
                    store_result = True

        if send_command:
            if udid is None:
                self.log.e(TAG, 'No UDID is supplied from the device')
            else:

                command_list = command.get_not_executed(str(device_id))
                if command_list is None or len(command_list) == 0:
                    self.log.e(
                        TAG, 'No command to execute fot the device \
                               having ID = ' + str(device_id))
                    reply = " "
                    print 'outer write'
                    self.request.set_status(500)
                    self.request.write(reply)
                    ioloop.IOLoop.instance().add_callback(self.callback)

                else:

                    device_details = DeviceDetailsDBHelper()
                    violate_device = False
                    special_uuid = (
                        '2929292929-29292929-292929-292929-292929' +
                        str(device_id))

                    commands = command_list[0]
                    action = str(commands[c.COMMAND_TABLE_ACTION])
                    command_attributes = commands[c.COMMAND_TABLE_ATTRIBUTE]
                    command_uuid = str(commands[c.COMMAND_TABLE_COMMAND_UUID])

                    if command_uuid == special_uuid:
                        violate_device = True

                    if action is not None and not violate_device:
                        command_xml_thread = IOSCommandCreatorThread(
                            action, command_attributes, command_uuid,
                            device_id)
                        command_xml_thread.start()
                        command_xml_thread.join()
                        final_output = command_xml_thread.command_profile
                        if final_output is not None:
                            self.request.write(final_output)
                        ioloop.IOLoop.instance().add_callback(self.callback)
                        # send polling signal to device for next command
                        device_details_list = (
                            device_details.get_device_details(device_id))

                        json_extras = device_details_list.get(
                            c.DEVICE_DETAILS_TABLE_EXTRAS)

                        self.push_magic = str(json_extras.get('push_magic'))
                        self.device_token = str(json_extras.get('token'))
                        wrapper = APNSNotificationWrapper(
                            '/opt/toppatch/assets/ios/PushCert.pem', False)
                        message = APNSNotification()
                        message.appendProperty(
                            APNSProperty("mdm", self.push_magic))
                        message.tokenBase64(str(self.device_token))
                        wrapper.append(message)
                        wrapper.notify()
                        print 'Payload Sent'

                    elif violate_device:
                        ### Wiping device to Factory Reset ###
                        command_xml_thread = IOSCommandCreatorThread(
                            action, command_attributes, command_uuid,
                            device_id)
                        command_xml_thread.start()
                        command_xml_thread.join()
                        final_output = command_xml_thread.command_profile
                        if final_output is not None:
                            self.request.write(final_output)
                        ioloop.IOLoop.instance().add_callback(self.callback)

                        violation = ViolationsDBHelper()
                        enrollment = EnrollmentDBHelper()
                        violation_id = violation.add_violation(str(device_id))

                        if violation_id is None:
                            self.log.e(
                                TAG, 'Not able to insert in Violation \
Table. DeviceID = ' + str(device_id))
                        else:
                            device.delete_device(device_id)
                            enrollment_list = enrollment.get_enrollments(
                                {'device_id': device_id})
                            for enroll in enrollment_list:
                                enrollment_id = enroll.get('id')
                                enrollment.update_enrollment(
                                    str(enrollment_id), {
                                        'device_id': "null",
                                        'is_enrolled': False
                                    })
                            self.log.i(
                                TAG, 'Violation added for device id = ' +
                                str(device_id) + 'due to remote wipe command')
                    else:
                        reply = " "
                        print 'outer write'
                        self.request.set_status(500)
                        self.request.write(reply)
                        ioloop.IOLoop.instance().add_callback(self.callback)

        elif check_out_requested:
            violation = ViolationsDBHelper()
            device = DeviceDBHelper()

            devices = device.get_device_with_udid(udid)
            if devices is None:
                self.log.e(TAG,
                           'No User ID Associated with Device UDID = ' + udid)
            else:
                device_id = str(devices[0][c.DEVICE_TABLE_ID])
                violation_id = violation.add_violation(device_id)
                if violation_id is None:
                    self.log.e(
                        TAG, 'Not able to insert in Violation Table.\
                               DeviceID = ' + str(device_id))
                else:
                    self.log.i(
                        TAG,
                        'Violation added for device id = ' + str(device_id))

            reply = """

                    """
            self.request.set_status(401)
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)

        elif store_result or store_error:
            if special_result:
                is_updated = device.update_device(
                    str(device_id),
                    {c.DEVICE_TABLE_OS_VERSION: str(final.get('OSVersion'))})
                if not is_updated:
                    self.log.e(
                        TAG, 'Not able to set the version of the device\
                    udid = ' + str(udid) + " Device id = " + str(device_id))
                else:
                    self.log.i(
                        TAG, 'Version Set for the device udid = ' + str(udid) +
                        " Device id = " + str(device_id))

            if store_error:
                self.log.e(
                    TAG, 'Error in Response for uuid = ' + str(uuid) +
                    ' device_id = ' + str(device_id))
            # print '\n\nfinal dict to be stored as json is \n\n', final
            result_updated = command.update_result(str(uuid), str(device_id),
                                                   final)
            reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
            """
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)
            if not result_updated:
                self.log.e(
                    TAG, 'Result Not updated for uuid = ' + str(uuid) +
                    ' udid = ' + str(udid))
            else:
                executed = command.toggle_executed(str(uuid), str(device_id),
                                                   True)
                if executed is False:
                    self.log.e(
                        TAG, 'IOSCommand Table executed \
                            field is not updated CommandUUID = ' + str(uuid) +
                        'Device id = ' + str(device_id))

                self.log.i(
                    TAG, 'Result send in DB for uuid = ' + str(uuid) +
                    ' udid = ' + str(udid))

                if invoke_flag:
                    # Queue task to send command to user of app installation
                    user = UserDBHelper()
                    user_id = device.get_device_with_udid(
                        str(udid))[0]['user_id']
                    user_info = user.get_user(str(user_id))
                    json_data = {'to': 'user', 'id': user_id}
                    json_data['company_id'] = user_info.get('company_id')
                    create_command_handler_task.delay(json_data)

        elif update_token:
            device = DeviceDBHelper()
            device_list = device.get_device_with_udid(udid)

            device_id = 'device_id'
            if device_list is not None and len(device_list) != 0:
                for devices in device_list:
                    device_id = devices[c.DEVICE_TABLE_ID]
                    if device_id is None:
                        self.log.e(
                            TAG, 'Device id is not found corresponding \
                                   the udid = ' + str(udid))
                    else:
                        device_details = DeviceDetailsDBHelper()
                        device_details_dict = {
                            c.DEVICE_DETAILS_TABLE_DEVICE_TOKEN: token,
                            c.DEVICE_DETAILS_TABLE_PUSH_MAGIC: push_magic,
                            c.DEVICE_DETAILS_TABLE_UNLOCK_TOKEN: unlock_token
                        }
                        is_updated = device_details.update_device_details(
                            str(device_id), device_details_dict)
                        if not is_updated:
                            self.log.e(
                                TAG, 'Not able to update the device \
                                    details of device_id = ' + str(device_id))
                        else:
                            self.log.i(
                                TAG, 'Device Details successfully \
                                       updated device id = ' + str(device_id))

                        reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
                        """
                        self.request.write(reply)
                        ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
            """
            print 'outer write'
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)
def admin_mailer(device_id, violation_id, *args, **kwargs):

    TAG = 'admin mailer'
    base = DBHelper()
    cur = base.cursor
    log = Logger('AdminMailer')

    device = DeviceDBHelper()
    violation = ViolationsDBHelper()
    user = UserDBHelper()
    company = CompanyDBHelper()
    email_list = []

    device_os_mapper = {'ios': 'iOS', 'samsung': 'android'}
    ### Device information ###
    device_info = device.get_device(str(device_id), status=True)

    if device_info:
        device_os = device_info.get('os')
        device_os = device_os_mapper.get(device_os)
        device_os_version = device_info.get('os_version')
        user_info = user.get_user(str(device_info.get('user_id')))

    else:
        device_os = None
        device_os_version = None
        user_info = None

    ### User information ###
    if user_info:
        username = user_info.get('name')
        company_id = user_info.get('company_id')
        company_info = company.get_company(str(company_id))
    else:
        username = None
        company_info = None
        company_id = None

    ### Violation information ###
    violation_info = violation.get_violation(str(violation_id))

    if violation_info:
        violation_time = violation_info.get('timestamp')
        violation_time = violation_time.strftime('%d %b, %Y at %H:%M:%S')
    else:
        violation_time = None

    ### Company information ###

    if company_info:
        company_name = company_info.get('name')
        ### Query to get admin information for the particulat company ###
        try:
            cur.execute("""SELECT * FROM admin_profile
            WHERE company_id = {0}""".format(company_id))

        except Exception as err:
            log.e(TAG, 'Exception : ' + repr(err))

        if cur.rowcount > 0:
            rows = cur.fetchall()
            for row in rows:
                # ipdb.set_trace()
                email_list.append(row[1])

        else:
            log.i(
                TAG,
                """No admin user found for the violated device with company
id : {0}""".format(company_id))
            print "Query over admin went wrong"
    else:
        company_name = None

    if len(email_list) > 0 and all(
        x is not None for x in (
            username,
            company_name,
            violation_time,
            device_os)):
        message = loader.load('violation_mail.html').generate(
            username=username, company_name=company_name,
            violation_time=violation_time, device_os=device_os,
            device_os_version=device_os_version)

        try:
            ses_conn.send_email('*****@*****.**',
                                'User MDM Violations Notification',
                                message, email_list, format='html')
        except Exception as err:
            log.e(TAG, "Error in sending mail from ses side.")

    else:
        log.i(
            TAG,
            """No admin found for the violated device with company id :
{0}""".format(company_id))
Exemple #8
0
    def run(self):
        TAG = 'run'

        print ' In SamsungCommandResult\'s PUT'
        command = SamsungCommandsDBHelper()

        print "here is the response \n", self.request.request.body
        json_dict = json.loads(self.request.request.body)

        special_result = False
        checkout_result = False
        result_updated = False

        special_uuid = '1717171717-17171717-1717117-1717'
        checkout_uuid = '1919191919-19191919-191919-1919'

        command_uuid = str(json_dict.get('command_uuid'))
        gcm_id = json_dict.get('gcm_id')
        imei = json_dict.get('imei')

        if special_uuid in command_uuid:
            special_result = True

        if checkout_uuid in command_uuid:
            checkout_result = True

        device = DeviceDBHelper()
        device_list = device.get_device_with_udid(str(imei))

        print "\n device list here \n", device_list
        command_result = json_dict.get('result')

        if checkout_result:

            violation = ViolationsDBHelper()
            enrollment = EnrollmentDBHelper()
            if device_list is None:
                self.log.e(
                    TAG,
                    'No User ID Associated with Device gcm_id = ' + gcm_id)
            else:
                device_id = device_list[0][c.DEVICE_TABLE_ID]
                violation_id = violation.add_violation(str(device_id))
                if violation_id is None:
                    self.log.e(
                        TAG, 'Not able to insert in Violation Table.\
                               DeviceID = ' + str(device_id))
                else:
                    device.delete_device(device_id)
                    enrollment_list = enrollment.get_enrollments(
                        {'device_id': device_id})
                    for enroll in enrollment_list:
                        enrollment_id = enroll.get('id')
                        enrollment.update_enrollment(str(enrollment_id), {
                            'device_id': "null",
                            'is_enrolled': False
                        })
                    self.log.i(
                        TAG,
                        'Violation added for device id = ' + str(device_id))
                    admin_mailer(device_id, violation_id)

            result_updated = True

        elif special_result:
            os_version = command_result.get('device_platform')
            os_version = os_version.replace('Android', '').strip()

            if device_list is None:
                device_list = []

            for unique_device in device_list:
                device_id = unique_device.get(c.DEVICE_TABLE_ID)
                is_updated = device.update_device(
                    str(device_id),
                    {c.DEVICE_TABLE_OS_VERSION: str(os_version)})
                if not is_updated:
                    self.log.e(
                        TAG, 'Not able to set the version of the \
device gcm_id = ' + str(gcm_id) + " Device id = " + str(device_id))

                else:
                    self.log.i(
                        TAG, 'Version Set for the device gcm_id = ' +
                        str(gcm_id) + " Device id = " + str(device_id))

                result_updated = command.update_result(str(command_uuid),
                                                       str(device_id),
                                                       command_result)
        else:
            if device_list is None:
                device_list = []

            for unique_device in device_list:
                device_id = unique_device.get(c.DEVICE_TABLE_ID)
                result_updated = command.update_result(str(command_uuid),
                                                       str(device_id),
                                                       command_result)

        if not result_updated:
            self.log.e(
                TAG, 'Result Not updated for uuid = ' + str(command_uuid) +
                'gcm_id = ' + str(gcm_id))

            self.request.set_status(404)
            self.request.write("Not OK")
            ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            self.log.i(
                TAG, 'Result send in DB for uuid = ' + str(command_uuid) +
                'gcm_id = ' + str(gcm_id))
            self.request.set_status(200)
            self.request.write("OK")
            ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #9
0
    def run(self):
        #Return All the users in the User table
        log = Logger('UsersGetHandlerThreadWithPage')
        tag = 'run'

        company_id = self.company_id

        final_dict = {}

        user = UserDBHelper()
        team = TeamDBHelper()
        role = RoleDBHelper()
        violation = ViolationsDBHelper()
        device = DeviceDBHelper()

        offset = self.request.get_argument('offset', None)
        count = self.request.get_argument('count', None)
        name_query = self.request.get_argument('name', None)
        team_query = self.request.get_argument('team', None)
        role_query = self.request.get_argument('role', None)
        device_query = self.request.get_argument('device_id', None)
        sort_by = self.request.get_argument('sort_by', True)#Intentionally done
        sort_order = self.request.get_argument('sort', None)
        filter_key = self.request.get_argument('filter_key', None)
        filter_value = self.request.get_argument('filter_value', None)

        if filter_key == 'role':
            role_name = filter_value
            role_id = role.get_role_by_name(str(role_name), company_id)
        else:
            role_name = None
            role_id = None

        if filter_key == 'team':
            team_name = filter_value
            team_id = team.get_team_by_name(str(team_name), company_id)
        else:
            team_name = None
            team_id = None

        if filter_key == 'os':
            os_mapper = {'Android': 'samsung', 'iOS': 'ios'}
            os_type = os_mapper.get(str(filter_value))
        else:
            os_type = None

        if name_query:
            query  = name_query
            query_type = 'name'
        elif role_query:
            query = role_query
            query_type = 'role'
        elif device_query:
            query = device_query
            query_type = 'device'
        elif team_query:
            query = team_query
            query_type = 'team'
        else:
            query = None
            query_type = None

        if offset:
            result_list, total_count = user.get_users_for_user(
                        company_id=company_id, offset=offset, count=count,
                        role_id=role_id, team_id=team_id, query=query,
                        query_type=query_type, os_type=os_type,
                        sort_by=sort_by, sort_order=sort_order,
                        filter_key=filter_key, filter_value=filter_value)

        else:
            result_list, total_count = user.get_users(
                                    {c.USER_TABLE_COMPANY: company_id})

        if result_list:
            for user_dict in result_list:
                device_deleted = False
                device_info = device.get_device_with_udid(user_dict.get(
                                    'user_device'))
                if not device_info:
                    device_info = device.get_device_with_udid(user_dict.get(
                                    'user_device'), status=True)
                    device_deleted = True
                if device_info:
                    device_id = device_info[0].get(c.DEVICE_TABLE_ID)
                else:
                    device_id = None

                if device_deleted:
                    user_dict['user_device'] = None
                    user_dict['user_device_os'] = None

                if device_id:
                    print "printing \n device id", device_id
                    violation_count = violation.get_violation_count(
                          company_id=company_id, device_id=str(device_id))
                else:
                    violation_count = 0
                user_dict['user_violation'] = violation_count

            final_dict['data'] = result_list
            final_dict['count'] = total_count
            final_dict['pass'] = True
            final_dict['message'] = 'Seems like things are working ...'

        else:
            final_dict['pass'] = True
            log.e(tag,'No User in User Table')
            final_dict['message'] = 'Seems like things are not working ...'
            final_dict['count'] = 0

        ## add all the data into dictionary and create output json
        opJson = json.dumps(final_dict)
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #10
0
def admin_mailer(device_id, violation_id, *args, **kwargs):

    TAG = 'admin mailer'
    base = DBHelper()
    cur = base.cursor
    log = Logger('AdminMailer')

    device = DeviceDBHelper()
    violation = ViolationsDBHelper()
    user = UserDBHelper()
    company = CompanyDBHelper()
    email_list = []

    device_os_mapper = {'ios': 'iOS', 'samsung': 'android'}
    ### Device information ###
    device_info = device.get_device(str(device_id), status=True)

    if device_info:
        device_os = device_info.get('os')
        device_os = device_os_mapper.get(device_os)
        device_os_version = device_info.get('os_version')
        user_info = user.get_user(str(device_info.get('user_id')))

    else:
        device_os = None
        device_os_version = None
        user_info = None

    ### User information ###
    if user_info:
        username = user_info.get('name')
        company_id = user_info.get('company_id')
        company_info = company.get_company(str(company_id))
    else:
        username = None
        company_info = None
        company_id = None

    ### Violation information ###
    violation_info = violation.get_violation(str(violation_id))

    if violation_info:
        violation_time = violation_info.get('timestamp')
        violation_time = violation_time.strftime('%d %b, %Y at %H:%M:%S')
    else:
        violation_time = None

    ### Company information ###

    if company_info:
        company_name = company_info.get('name')
        ### Query to get admin information for the particulat company ###
        try:
            cur.execute("""SELECT * FROM admin_profile
            WHERE company_id = {0}""".format(company_id))

        except Exception as err:
            log.e(TAG, 'Exception : ' + repr(err))

        if cur.rowcount > 0:
            rows = cur.fetchall()
            for row in rows:
                # ipdb.set_trace()
                email_list.append(row[1])

        else:
            log.i(
                TAG,
                """No admin user found for the violated device with company
id : {0}""".format(company_id))
            print "Query over admin went wrong"
    else:
        company_name = None

    if len(email_list) > 0 and all(
            x is not None
            for x in (username, company_name, violation_time, device_os)):
        message = loader.load('violation_mail.html').generate(
            username=username,
            company_name=company_name,
            violation_time=violation_time,
            device_os=device_os,
            device_os_version=device_os_version)

        try:
            ses_conn.send_email('*****@*****.**',
                                'User MDM Violations Notification',
                                message,
                                email_list,
                                format='html')
        except Exception as err:
            log.e(TAG, "Error in sending mail from ses side.")

    else:
        log.i(
            TAG, """No admin found for the violated device with company id :
{0}""".format(company_id))
Exemple #11
0
def admin_mailer(device_id, violation_id, *args, **kwargs):

    TAG='admin mailer'
    base = DBHelper()
    cur = base.cursor
    log = Logger('AdminMailer')

    device = DeviceDBHelper()
    violation = ViolationsDBHelper()
    user = UserDBHelper()
    company = CompanyDBHelper()
    email_list = []

    device_os_mapper = {'ios': 'iOS', 'samsung': 'android'}
    ### Device information ###
    device_info = device.get_device(str(device_id), status=True)

    if device_info:
        device_os = device_info.get('os')
        device_os = device_os_mapper.get(device_os)
        device_os_version = device_info.get('os_version')
        user_info = user.get_user(str(device_info.get('user_id')))

    else:
        device_os = None
        device_os_version = None
        user_info = None



    ### User information ###
    if user_info:
        username = user_info.get('name')
        company_id = user_info.get('company_id')
        company_info = company.get_company(str(company_id))
    else:
        username = None
        company_info = None
        company_id = None

    ### Violation information ###
    violation_info = violation.get_violation(str(violation_id))

    if violation_info:
        violation_time = violation_info.get('timestamp')
        violation_time = violation_time.strftime('%d %b, %Y at %H:%M:%S')
    else:
        violation_time = None

    ### Company information ###

    if company_info:
        company_name = company_info.get('name')
        ### Query to get admin information for the particulat company ###
        try:
            cur.execute("""SELECT * FROM admin_profile
            WHERE company_id = {0}""".format(company_id))

        except Exception, err:
            log.e(TAG, 'Exception : ' + repr(err))

        if cur.rowcount > 0:
            rows = cur.fetchall()
            for row in rows:
                #ipdb.set_trace()
                email_list.append(row[1])

        else:
            log.i(TAG, """No admin user found for the violated device with company id : {0}""".format(company_id))
            print "Query over admin went wrong"
Exemple #12
0
    def run(self):
        log = Logger('TeamGetHandlerThread')
        TAG = 'GET'
        page = self.request.get_argument('page', None)
        count = self.request.get_argument('count', None)
        sort_by = self.request.get_argument('sort_by', None)

        if self.data is None:
            log.e(TAG, 'No Team ID in Request')
            opJson = json.dumps({
                'pass':
                False,
                'message':
                'No team found corresponding to the team \
id ' + str(self.data)
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
        else:
            team = TeamDBHelper()
            teams = team.get_team(str(self.data), company_id=self.company_id)
            outer_dict = {}
            outer_array = []
            print teams
            if teams is None:
                log.e(
                    TAG, 'No team found corresponding to the team id ' +
                    str(self.data))
                opJson = json.dumps({
                    'pass':
                    False,
                    'message':
                    'No team found corresponding to the team \
id ' + str(self.data)
                })
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

            else:
                self.team_name = teams.get(c.TEAM_TABLE_NAME)
                user = UserDBHelper()
                filter_dict = {c.USER_TABLE_TEAM: str(teams.get('id'))}
                user_list = user.get_users_with_pages(filter_dict, int(page),
                                                      int(count), str(sort_by))

                inner_array = []
                if user_list is not None:
                    for users in user_list:
                        inner_dict = {}
                        self.user_id = str(users[c.USER_TABLE_ID])
                        self.user_name = str(users[c.USER_TABLE_NAME])
                        self.user_email = str(users[c.USER_TABLE_EMAIL])
                        self.user_role_id = str(users[c.USER_TABLE_ROLE])

                        # Find out the role for user
                        role = RoleDBHelper()
                        roles = role.get_role(self.user_role_id,
                                              [c.ROLE_TABLE_NAME])
                        if roles is None:
                            self.user_role = None
                        else:
                            self.user_role = str(roles[c.ROLE_TABLE_NAME])

                        # Find out the device for user
                        device = DeviceDBHelper()
                        device_list = device.get_devices_of_user(self.user_id)
                        if device_list is None:
                            self.user_device = None
                        else:
                            devices = device_list[0]
                            self.user_device = str(
                                devices[c.DEVICE_TABLE_UDID])
                            self.user_device_os = str(
                                devices[c.DEVICE_TABLE_OS])
                            # Find out user violations
                            violation = ViolationsDBHelper()
                            violation_count = violation.get_violation_count(
                                str(devices.get('id')))

                        inner_dict = {
                            'user_id': self.user_id,
                            'user_name': self.user_name,
                            'user_role': self.user_role,
                            'user_team': self.team_name,
                            'user_device': self.user_device,
                            'user_violations': violation_count,
                            'user_device_os': self.user_device_os,
                            'user_email': self.user_email
                        }
                        inner_array.append(inner_dict)

            outer_dict['name'] = self.team_name
            outer_dict['users'] = inner_array
            outer_dict['team_id'] = self.data
            print '\nouter_dict'
            print outer_dict
            outer_array.append(outer_dict)

            self.final_dict['pass'] = True
            self.final_dict['teams'] = outer_array

            opJson = json.dumps(self.final_dict)
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
    def run(self):
        TAG = 'run'

        print ' In SamsungCommandResult\'s PUT'
        command = SamsungCommandsDBHelper()

        print "here is the response \n", self.request.request.body
        json_dict = json.loads(self.request.request.body)

        special_result = False
        checkout_result = False
        result_updated = False

        special_uuid = '1717171717-17171717-1717117-1717'
        checkout_uuid = '1919191919-19191919-191919-1919'

        command_uuid = str(json_dict.get('command_uuid'))
        gcm_id = json_dict.get('gcm_id')
        imei = json_dict.get('imei')

        if special_uuid in command_uuid:
            special_result = True

        if checkout_uuid in command_uuid:
            checkout_result = True

        device = DeviceDBHelper()
        device_list = device.get_device_with_udid(str(imei))

        print "\n device list here \n", device_list
        command_result = json_dict.get('result')

        if checkout_result:

            violation = ViolationsDBHelper()
            enrollment = EnrollmentDBHelper()
            if device_list is None:
                self.log.e(TAG, 'No User ID Associated with Device gcm_id = '
                           + gcm_id)
            else:
                device_id = device_list[0][c.DEVICE_TABLE_ID]
                violation_id = violation.add_violation(str(device_id))
                if violation_id is None:
                    self.log.e(TAG, 'Not able to insert in Violation Table.\
                               DeviceID = ' + str(device_id))
                else:
                    device.delete_device(device_id)
                    enrollment_list = enrollment.get_enrollments({
                        'device_id': device_id})
                    for enroll in enrollment_list:
                        enrollment_id = enroll.get('id')
                        enrollment.update_enrollment(
                            str(enrollment_id), {
                                'device_id': "null", 'is_enrolled': False})
                    self.log.i(TAG, 'Violation added for device id = ' +
                               str(device_id))
                    admin_mailer(device_id, violation_id)

            result_updated = True

        elif special_result:
            os_version = command_result.get('device_platform')
            os_version = os_version.replace('Android', '').strip()

            if device_list is None:
                device_list = []

            for unique_device in device_list:
                device_id = unique_device.get(c.DEVICE_TABLE_ID)
                is_updated = device.update_device(
                    str(device_id), {
                        c.DEVICE_TABLE_OS_VERSION: str(os_version)})
                if not is_updated:
                    self.log.e(TAG, 'Not able to set the version of the \
device gcm_id = ' + str(gcm_id) + " Device id = " + str(device_id))

                else:
                    self.log.i(
                        TAG,
                        'Version Set for the device gcm_id = ' +
                        str(gcm_id) +
                        " Device id = " +
                        str(device_id))

                result_updated = command.update_result(
                    str(command_uuid),
                    str(device_id),
                    command_result)
        else:
            if device_list is None:
                device_list = []

            for unique_device in device_list:
                device_id = unique_device.get(c.DEVICE_TABLE_ID)
                result_updated = command.update_result(
                    str(command_uuid),
                    str(device_id),
                    command_result)

        if not result_updated:
            self.log.e(TAG, 'Result Not updated for uuid = ' +
                       str(command_uuid) + 'gcm_id = ' + str(gcm_id))

            self.request.set_status(404)
            self.request.write("Not OK")
            ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            self.log.i(TAG, 'Result send in DB for uuid = ' +
                       str(command_uuid) + 'gcm_id = ' + str(gcm_id))
            self.request.set_status(200)
            self.request.write("OK")
            ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #14
0
    def post(self):
        print '\n\nSamsung login\n\n'
        email = self.get_argument(Constants.SAMSUNG_LOGIN_EMAIL, None)
        passcode = self.get_argument(Constants.SAMSUNG_LOGIN_PASSCODE, None)
        gcm = self.get_argument(Constants.SAMSUNG_LOGIN_GCM, None)
        imei = self.get_argument('imei', None)
        print email, passcode, gcm, imei

        if email and passcode and gcm and imei:
            # Boolena flag to track enrollment status
            enrolled_status = False
            # Check in the database helper..
            from db.helpers.authentication import AuthenticationDBHelper
            auth = AuthenticationDBHelper()
            auth_result = auth.check_authentication(email, passcode)
            print auth_result
            if auth_result is not None:
                print "\n reached here \n"
                result = dict()
                result['uuid'] = str(uuid.uuid4())
                from db.helpers import device
                # Insert a row in device table and set the enrollment
                # row[is_enrolled]=true
                device_helper = device.DeviceDBHelper()
                enrollment_helper = enrollment.EnrollmentDBHelper()
                device_details_helper = device_details.DeviceDetailsDBHelper()

                enrollment_id = str(auth_result['id'])
                devices = device_helper.get_device_with_udid(str(imei),
                                                             status=True)
                enrollment_dict = enrollment_helper.get_enrollment(
                    enrollment_id)

                device_id = enrollment_dict.get(C.ENROLLMENT_TABLE_DEVICE)

                if device_id:

                    device_helper.update_device(
                        str(device_id), {
                            C.DEVICE_TABLE_DELETED: False,
                            C.DEVICE_TABLE_UDID: str(imei)
                        })
                    device_details_helper.update_device_details(
                        str(device_id), {'gcm': gcm})
                    enrolled_status = True

                elif devices:
                    device_id = devices[0][C.DEVICE_TABLE_ID]
                    device_helper.update_device(
                        str(device_id), {
                            C.DEVICE_TABLE_DELETED: False,
                            C.DEVICE_TABLE_USER: auth_result.get('user_id')
                        })
                    device_details_helper.update_device_details(
                        str(device_id), {'gcm': gcm})
                    enrollment_helper.update_enrollment(
                        enrollment_id,
                        {C.ENROLLMENT_TABLE_DEVICE: str(device_id)})
                    enrollment_helper.set_enrolled(enrollment_id)
                    enrolled_status = True

                else:

                    print "\nIn new device conditions\n"
                    device_dict = dict()
                    device_dict[C.DEVICE_TABLE_OS] = 'samsung'
                    device_dict[C.DEVICE_TABLE_UDID] = imei
                    device_dict[C.DEVICE_TABLE_USER] = str(
                        auth_result['user_id'])
                    device_id = device_helper.add_device(device_dict)

                    # Set it as enrolled in enrollment table
                    enrollment_helper.update_enrollment(
                        enrollment_id,
                        {C.ENROLLMENT_TABLE_DEVICE: str(device_id)})
                    enrollment_helper.set_enrolled(str(auth_result['id']))
                    enrolled_status = True

                    samsung_command_helper = (
                        samsung_command.SamsungCommandsDBHelper())
                    command = dict()
                    command[C.SAMSUNG_COMMANDS_TABLE_ACTION] = (
                        C.SAMSUNG_COMMANDS_TABLE_ACTION_SETUP)
                    command[C.COMMAND_TABLE_COMMAND_UUID] = result['uuid']
                    command[C.SAMSUNG_COMMANDS_TABLE_DEVICE] = device_id
                    command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE] = ''

                    # separate implementation for getting os version using
                    # devcie_information command

                    android_engine = AndroidCommand()
                    command_dict = {}
                    command_dict['action_command'] = 'device_information'

                    # Save GCM. This is an important part.
                    device_details_helper = (
                        device_details.DeviceDetailsDBHelper())
                    device_dict = dict()
                    device_dict[C.DEVICE_DETAILS_TABLE_DEVICE] = str(device_id)
                    device_dict[C.DEVICE_DETAILS_TABLE_EXTRAS] = {'gcm': gcm}
                    if device_details_helper.add_device_detail(device_dict):
                        # Now update the os of the device as samsung. very
                        # important!!!
                        d = dict()
                        d[C.DEVICE_TABLE_OS] = 'samsung'
                        device_helper.update_device(str(device_id), d)
                        result['pass'] = True
                        result['key'] = config.SAMSUNG_LICENSE
                        result['id'] = samsung_command_helper.add_command(
                            command)
                        # self.write(json.dumps(result))

                        # now send the device information command to device
                        android_engine.execute(command_dict, device_id)
                    else:
                        result['pass'] = False
                        result['message'] = 'Could not update on the server'
                        self.write(json.dumps(result))

                if not enrolled_status:
                    result['pass'] = False
                    result['message'] = 'Could not update on the server'
                    self.write(json.dumps(result))
                else:
                    result['pass'] = True
                    result['key'] = config.SAMSUNG_LICENSE
                    self.write(json.dumps(result))
                    violation = ViolationsDBHelper()
                    violation_status = violation.update_violations(
                        str(device_id))
                    if violation_status:
                        print("Violation table updated for device_id" +
                              str(device_id))
                    else:
                        print "Violation table not updated for device_id\
                            " + str(device_id)
            else:
                result = dict()
                result['pass'] = False
                result['message'] = 'Invalid email passcode combination'
                self.write(json.dumps(result))
        elif not gcm:
            result = dict()
            result['pass'] = False
            result['message'] = 'No GCM information sent'
            self.write(json.dumps(result))
        else:
            result = dict()
            result['pass'] = False
            result['message'] = 'Email =' + \
                str(email) + ' Passcode =' + str(passcode) + ' is not valid'
            self.write(json.dumps(result))
    def run(self):
        TAG = 'run'

        print ' In IOSCommandPerformer\'s PUT'
        command = IOSCommandDBHelper()
        invoke_flag = False
        arguments = cgi.parse_qsl(self.request.request.body)
        intermediate = arguments[0]
        currentxml = intermediate[1]
        final = currentxml[25:-1]  # Original Line
# final = currentxml[20:]  ### For testing only
        # print '\n\n\n here is final xml \n\n', final
        # temp Parsing
        # tree = ET.ElementTree(ET.fromstring(final))  ##Original Line
# tree = ET.parse('temp.xml')   ### For testing only
        initial_list = []
        initial_dict = {}

        check_out_requested = False
        send_command = False
        store_result = False
        store_error = False
        registered = True
        special_result = False
        acknowledged = False
        update_token = False

        object_root = objectify.fromstring(final)

        begin = object_root.dict

        for child in begin.iterchildren():
            initial_list.append(child.text)

        initial_dict = dict(zip(initial_list[::2], initial_list[1::2]))
        # print '\n\n print here initial dict\n', initial_dict

        if 'UDID' in initial_dict:
            udid = initial_dict.get('UDID')
            device = DeviceDBHelper()
            registered = device.is_udid_registered(str(udid))

        if 'Status' in initial_dict:
            status = initial_dict.get('Status')
            if status == 'Idle':
                send_command = True
            elif status == 'Acknowledged':
                acknowledged = True
            elif status == 'Error':
                store_error = True
                uuid = initial_dict.get('CommandUUID')

        if 'MessageType' in initial_dict:
            message = initial_dict.get('MessageType')
            if message == 'TokenUpdate':
                update_token = True
            elif message == 'CheckOut':
                check_out_requested = True
        push_magic = 'push_magic'
        token = 'Token'
        unlock_token = 'UnlockToken'

        if registered is False:
            reply = """

                    """
            self.request.set_status(401)
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            device_id = str(device.get_device_with_udid(udid)[0]['id'])
            print 'reached here '
        if acknowledged:
            if 'CommandUUID' in initial_dict:
                uuid = initial_dict.get('CommandUUID')
                # special uuid for device information
                if uuid == '55555555-5555-5555-5555-555555555555' + device_id:
                    info_list = [
                        el.text if el.text else el.tag for el in object_root.iterdescendants()]
                    info_list.pop(0)
                    final = dict(zip(info_list[::2], info_list[1::2]))
                    store_result = True
                    special_result = True
                # special uuid for installed application list
                elif uuid == (
                        '77777777-7777-7777-7777-777777777777' + device_id):
                    begin = object_root.dict.array
                    apps_list = []
                    for outer_child in begin.iterchildren():
                        temp_list = []
                        for inner_child in outer_child.iterchildren():
                            temp_list.append(inner_child.text)
                        apps_list.append(dict(zip(temp_list[::2],
                                                  temp_list[1::2])))
                    final = apps_list
                    store_result = True
                    invoke_flag = True
                else:
                    store_result = True

        if send_command:
            if udid is None:
                self.log.e(TAG, 'No UDID is supplied from the device')
            else:

                command_list = command.get_not_executed(str(device_id))
                if command_list is None or len(command_list) == 0:
                    self.log.e(TAG, 'No command to execute fot the device \
                               having ID = ' + str(device_id))
                    reply = " "
                    print 'outer write'
                    self.request.set_status(500)
                    self.request.write(reply)
                    ioloop.IOLoop.instance().add_callback(self.callback)

                else:

                    device_details = DeviceDetailsDBHelper()
                    violate_device = False
                    special_uuid = (
                        '2929292929-29292929-292929-292929-292929' +
                        str(device_id))

                    commands = command_list[0]
                    action = str(commands[c.COMMAND_TABLE_ACTION])
                    command_attributes = commands[c.COMMAND_TABLE_ATTRIBUTE]
                    command_uuid = str(commands[c.COMMAND_TABLE_COMMAND_UUID])

                    if command_uuid == special_uuid:
                        violate_device = True

                    if action is not None and not violate_device:
                        command_xml_thread = IOSCommandCreatorThread(
                            action,
                            command_attributes,
                            command_uuid,
                            device_id)
                        command_xml_thread.start()
                        command_xml_thread.join()
                        final_output = command_xml_thread.command_profile
                        if final_output is not None:
                            self.request.write(final_output)
                        ioloop.IOLoop.instance().add_callback(self.callback)
                        # send polling signal to device for next command
                        device_details_list = (
                            device_details.get_device_details(device_id))

                        json_extras = device_details_list.get(
                            c.DEVICE_DETAILS_TABLE_EXTRAS)

                        self.push_magic = str(json_extras.get('push_magic'))
                        self.device_token = str(json_extras.get('token'))
                        wrapper = APNSNotificationWrapper(
                            '/opt/toppatch/assets/ios/PushCert.pem', False)
                        message = APNSNotification()
                        message.appendProperty(
                            APNSProperty(
                                "mdm",
                                self.push_magic))
                        message.tokenBase64(str(self.device_token))
                        wrapper.append(message)
                        wrapper.notify()
                        print 'Payload Sent'

                    elif violate_device:
                        ### Wiping device to Factory Reset ###
                        command_xml_thread = IOSCommandCreatorThread(
                            action,
                            command_attributes,
                            command_uuid,
                            device_id)
                        command_xml_thread.start()
                        command_xml_thread.join()
                        final_output = command_xml_thread.command_profile
                        if final_output is not None:
                            self.request.write(final_output)
                        ioloop.IOLoop.instance().add_callback(self.callback)

                        violation = ViolationsDBHelper()
                        enrollment = EnrollmentDBHelper()
                        violation_id = violation.add_violation(str(device_id))

                        if violation_id is None:
                            self.log.e(TAG, 'Not able to insert in Violation \
Table. DeviceID = ' + str(device_id))
                        else:
                            device.delete_device(device_id)
                            enrollment_list = enrollment.get_enrollments({
                                'device_id': device_id})
                            for enroll in enrollment_list:
                                enrollment_id = enroll.get('id')
                                enrollment.update_enrollment(
                                    str(enrollment_id), {
                                        'device_id': "null",
                                        'is_enrolled': False})
                            self.log.i(
                                TAG,
                                'Violation added for device id = ' +
                                str(device_id) +
                                'due to remote wipe command')
                    else:
                        reply = " "
                        print 'outer write'
                        self.request.set_status(500)
                        self.request.write(reply)
                        ioloop.IOLoop.instance().add_callback(self.callback)

        elif check_out_requested:
            violation = ViolationsDBHelper()
            device = DeviceDBHelper()

            devices = device.get_device_with_udid(udid)
            if devices is None:
                self.log.e(TAG, 'No User ID Associated with Device UDID = '
                           + udid)
            else:
                device_id = str(devices[0][c.DEVICE_TABLE_ID])
                violation_id = violation.add_violation(device_id)
                if violation_id is None:
                    self.log.e(TAG, 'Not able to insert in Violation Table.\
                               DeviceID = ' + str(device_id))
                else:
                    self.log.i(TAG, 'Violation added for device id = ' +
                               str(device_id))

            reply = """

                    """
            self.request.set_status(401)
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)

        elif store_result or store_error:
            if special_result:
                is_updated = device.update_device(
                    str(device_id), {
                        c.DEVICE_TABLE_OS_VERSION: str(
                            final.get('OSVersion'))})
                if not is_updated:
                    self.log.e(TAG, 'Not able to set the version of the device\
                    udid = ' + str(udid) + " Device id = " + str(device_id))
                else:
                    self.log.i(TAG, 'Version Set for the device udid = '
                               + str(udid) + " Device id = " + str(device_id))

            if store_error:
                self.log.e(TAG, 'Error in Response for uuid = ' +
                           str(uuid) + ' device_id = ' + str(device_id))
            # print '\n\nfinal dict to be stored as json is \n\n', final
            result_updated = command.update_result(str(uuid),
                                                   str(device_id), final)
            reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
            """
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)
            if not result_updated:
                self.log.e(TAG, 'Result Not updated for uuid = ' +
                           str(uuid) + ' udid = ' + str(udid))
            else:
                executed = command.toggle_executed(str(uuid), str(device_id),
                                                   True)
                if executed is False:
                    self.log.e(TAG, 'IOSCommand Table executed \
                            field is not updated CommandUUID = ' +
                               str(uuid) + 'Device id = ' + str(device_id))

                self.log.i(TAG, 'Result send in DB for uuid = ' +
                           str(uuid) + ' udid = ' + str(udid))

                if invoke_flag:
                    # Queue task to send command to user of app installation
                    user = UserDBHelper()
                    user_id = device.get_device_with_udid(str(
                        udid))[0]['user_id']
                    user_info = user.get_user(str(user_id))
                    json_data = {'to': 'user', 'id': user_id}
                    json_data['company_id'] = user_info.get('company_id')
                    create_command_handler_task.delay(json_data)

        elif update_token:
            device = DeviceDBHelper()
            device_list = device.get_device_with_udid(udid)

            device_id = 'device_id'
            if device_list is not None and len(device_list) != 0:
                for devices in device_list:
                    device_id = devices[c.DEVICE_TABLE_ID]
                    if device_id is None:
                        self.log.e(TAG, 'Device id is not found corresponding \
                                   the udid = ' + str(udid))
                    else:
                        device_details = DeviceDetailsDBHelper()
                        device_details_dict = {
                            c.DEVICE_DETAILS_TABLE_DEVICE_TOKEN: token,
                            c.DEVICE_DETAILS_TABLE_PUSH_MAGIC: push_magic,
                            c.DEVICE_DETAILS_TABLE_UNLOCK_TOKEN: unlock_token
                        }
                        is_updated = device_details.update_device_details(
                            str(device_id), device_details_dict)
                        if not is_updated:
                            self.log.e(TAG, 'Not able to update the device \
                                    details of device_id = ' + str(device_id))
                        else:
                            self.log.i(TAG, 'Device Details successfully \
                                       updated device id = ' + str(device_id))

                        reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
                        """
                        self.request.write(reply)
                        ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            reply = """
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
                 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
                                <plist version="1.0">
                                <dict>
                                </dict>
                                </plist>
            """
            print 'outer write'
            self.request.write(reply)
            ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #16
0
    def run(self):
        log = Logger('RoleGetHandlerThread')
        TAG = 'GET'

        page = self.request.get_argument('offset', None)
        count = self.request.get_argument('count', None)
        sort_by = self.request.get_argument('sort_by', None)
        print page
        print count
        print sort_by

        if self.data and self.company_id:
            role = RoleDBHelper()
            roles = role.get_role(str(self.data), company_id=self.company_id)
            outer_dict = {}
            outer_array = []
            if roles is None:
                log.e(TAG, 'No role found corresponding to the role id ' + \
                      str(self.data))
                opJson = json.dumps({'pass': False, 'message':'No role found \
                            corresponding to the role id ' + str(self.data)})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            else:
                self.role_name = roles[c.ROLE_TABLE_NAME]

                user = UserDBHelper()
                filter_dict = {
                               c.USER_TABLE_ROLE: str(roles.get('id'))
                               }
                user_list = user.get_users_with_pages(filter_dict, int(page), int(count), str(sort_by))

                inner_array = []
                if user_list is not None:
                    for users in user_list:
                        inner_dict = {}
                        self.user_id = str(users[c.USER_TABLE_ID])
                        self.user_name = str(users[c.USER_TABLE_NAME])
                        self.user_email = str(users[c.USER_TABLE_EMAIL])
                        self.user_team_id = str(users[c.USER_TABLE_TEAM])

                        ## Find out the team for user
                        team = TeamDBHelper()
                        teams = team.get_team(self.user_team_id,
                                [c.TEAM_TABLE_NAME])
                        if teams is None:
                            self.user_team = None
                        else:
                            self.user_team = str(teams[c.TEAM_TABLE_NAME])

                        ## Find out the device for user
                        device = DeviceDBHelper()
                        device_list = device.get_devices_of_user(self.user_id)
                        if device_list is None:
                            self.user_device = None
                        else:
                            devices = device_list[0]
                            self.user_device = str(
                                devices[c.DEVICE_TABLE_UDID])
                            self.user_device_os = str(
                                devices[c.DEVICE_TABLE_OS])

                            # Find out user violations
                            violation = ViolationsDBHelper()
                            violation_count = violation.get_violation_count(
                                     str(devices.get('id')))
                        inner_dict = {
                               'user_id': self.user_id,
                               'user_name': self.user_name,
                               'user_role': self.role_name,
                               'user_team': self.user_team,
                               'user_device': self.user_device,
                               'user_violations': violation_count,
                               'user_device_os': self.user_device_os
                        }
                        inner_array.append(inner_dict)

                outer_dict['name'] = self.role_name
                outer_dict['users'] = inner_array
                outer_dict['roleID'] = self.data
                outer_array.append(outer_dict)

            self.final_dict['pass'] = True
            self.final_dict['roles'] = outer_array

            opJson = json.dumps(self.final_dict)
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            log.e(TAG, 'UnAuthorized Access for Roles')
            self.request.set_status(401)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Exemple #17
0
    def post(self):
        print '\n\nSamsung login\n\n'
        email = self.get_argument(Constants.SAMSUNG_LOGIN_EMAIL, None)
        passcode = self.get_argument(Constants.SAMSUNG_LOGIN_PASSCODE, None)
        gcm = self.get_argument(Constants.SAMSUNG_LOGIN_GCM, None)
        imei = self.get_argument('imei', None)
        print email, passcode, gcm, imei

        if email and passcode and gcm and imei:
            # Boolena flag to track enrollment status
            enrolled_status = False
            #Check in the database helper..
            from db.helpers.authentication import AuthenticationDBHelper
            auth = AuthenticationDBHelper()
            auth_result = auth.check_authentication(email, passcode)
            print auth_result
            if auth_result is not None:
                print "\n reached here \n"
                result = dict()
                result['uuid'] = str(uuid.uuid4())
                from db.helpers import device
                #Insert a row in device table and set the enrollment row[is_enrolled]=true
                device_helper = device.DeviceDBHelper()
                enrollment_helper = enrollment.EnrollmentDBHelper()
                device_details_helper = device_details.DeviceDetailsDBHelper()

                enrollment_id = str(auth_result['id'])
                devices = device_helper.get_device_with_udid(str(imei),
                                                         status=True)
                enrollment_dict = enrollment_helper.get_enrollment(
                                        enrollment_id)

                device_id = enrollment_dict.get(C.ENROLLMENT_TABLE_DEVICE)

                if device_id:

                    device_helper.update_device(str(device_id),
                             {C.DEVICE_TABLE_DELETED: False,
                                C.DEVICE_TABLE_UDID: str(imei)})
                    device_details_helper.update_device_details(str(device_id),
                                                {'gcm':gcm})
                    enrolled_status = True

                elif devices:
                    device_id = devices[0][C.DEVICE_TABLE_ID]
                    device_helper.update_device(str(device_id),
                             {C.DEVICE_TABLE_DELETED: False,
                              C.DEVICE_TABLE_USER: auth_result.get('user_id')})
                    device_details_helper.update_device_details(str(device_id),
                                                    {'gcm':gcm})
                    enrollment_helper.update_enrollment(enrollment_id,
                                {C.ENROLLMENT_TABLE_DEVICE : str(device_id)})
                    enrollment_helper.set_enrolled(enrollment_id)
                    enrolled_status = True

                else:

                    print "\nIn new device conditions\n"
                    device_dict = dict()
                    device_dict[C.DEVICE_TABLE_OS] = 'samsung'
                    device_dict[C.DEVICE_TABLE_UDID] = imei
                    device_dict[C.DEVICE_TABLE_USER] = str(
                                auth_result['user_id'])
                    device_id = device_helper.add_device(device_dict)

                    #Set it as enrolled in enrollment table
                    enrollment_helper.update_enrollment(enrollment_id,
                            {C.ENROLLMENT_TABLE_DEVICE : str(device_id)})
                    enrollment_helper.set_enrolled(str(auth_result['id']))
                    enrolled_status = True

                    samsung_command_helper = samsung_command.SamsungCommandsDBHelper()
                    command = dict()
                    command[C.SAMSUNG_COMMANDS_TABLE_ACTION] = C.SAMSUNG_COMMANDS_TABLE_ACTION_SETUP
                    command[C.COMMAND_TABLE_COMMAND_UUID] = result['uuid']
                    command[C.SAMSUNG_COMMANDS_TABLE_DEVICE] = device_id
                    command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE] = ''

                    ## separate implementation for getting os version using
                    ## devcie_information command

                    android_engine = AndroidCommand()
                    command_dict = {}
                    command_dict['action_command'] = 'device_information'

                    #Save GCM. This is an important part.
                    device_details_helper = device_details.DeviceDetailsDBHelper()
                    device_dict = dict()
                    device_dict[C.DEVICE_DETAILS_TABLE_DEVICE] = str(device_id)
                    device_dict[C.DEVICE_DETAILS_TABLE_EXTRAS] = {'gcm':gcm}
                    if device_details_helper.add_device_detail(device_dict):
                        #Now update the os of the device as samsung. very important!!!
                        d = dict()
                        d[C.DEVICE_TABLE_OS] = 'samsung'
                        device_helper.update_device(str(device_id), d)
                        result['pass'] = True
                        result['key'] = config.SAMSUNG_LICENSE
                        result['id'] = samsung_command_helper.add_command(
                            command)
                        #self.write(json.dumps(result))

                        ## now send the device information command to device
                        android_engine.execute(command_dict, device_id)
                    else:
                        result['pass'] = False
                        result['message'] = 'Could not update on the server'
                        self.write(json.dumps(result))

                if not enrolled_status:
                    result['pass']=False
                    result['message']='Could not update on the server'
                    self.write(json.dumps(result))
                else:
                    result['pass']= True
                    result['key']= config.SAMSUNG_LICENSE
                    self.write(json.dumps(result))
                    violation = ViolationsDBHelper()
                    violation_status = violation.update_violations(
                                            str(device_id))
                    if violation_status:
                        print "Violation table updated for device_id"+ str(device_id)
                    else:
                        print "Violation table not updated for device_id"+ str(device_id)
            else:
                result = dict()
                result['pass']= False
                result['message']= 'Invalid email passcode combination'
                self.write(json.dumps(result))
        elif not gcm:
            result= dict()
            result['pass']=False
            result['message']='No GCM information sent'
            self.write(json.dumps(result))
        else:
            result = dict()
            result['pass']= False
            result['message']= 'Email ='+str(email)+ ' Passcode ='+str(passcode)+' is not valid'
            self.write(json.dumps(result))
Exemple #18
0
    def run(self):
        # Return All the users in the User table
        log = Logger('UsersGetHandlerThreadWithPage')
        tag = 'run'

        company_id = self.company_id

        final_dict = {}

        user = UserDBHelper()
        team = TeamDBHelper()
        role = RoleDBHelper()
        violation = ViolationsDBHelper()
        device = DeviceDBHelper()

        offset = self.request.get_argument('offset', None)
        count = self.request.get_argument('count', None)
        name_query = self.request.get_argument('name', None)
        team_query = self.request.get_argument('team', None)
        role_query = self.request.get_argument('role', None)
        device_query = self.request.get_argument('device_id', None)
        sort_by = self.request.get_argument('sort_by',
                                            True)  # Intentionally done
        sort_order = self.request.get_argument('sort', None)
        filter_key = self.request.get_argument('filter_key', None)
        filter_value = self.request.get_argument('filter_value', None)

        if filter_key == 'role':
            role_name = filter_value
            role_id = role.get_role_by_name(str(role_name), company_id)
        else:
            role_name = None
            role_id = None

        if filter_key == 'team':
            team_name = filter_value
            team_id = team.get_team_by_name(str(team_name), company_id)
        else:
            team_name = None
            team_id = None

        if filter_key == 'os':
            os_mapper = {'Android': 'samsung', 'iOS': 'ios'}
            os_type = os_mapper.get(str(filter_value))
        else:
            os_type = None

        if name_query:
            query = name_query
            query_type = 'name'
        elif role_query:
            query = role_query
            query_type = 'role'
        elif device_query:
            query = device_query
            query_type = 'device'
        elif team_query:
            query = team_query
            query_type = 'team'
        else:
            query = None
            query_type = None

        if offset:
            result_list, total_count = user.get_users_for_user(
                company_id=company_id,
                offset=offset,
                count=count,
                role_id=role_id,
                team_id=team_id,
                query=query,
                query_type=query_type,
                os_type=os_type,
                sort_by=sort_by,
                sort_order=sort_order,
                filter_key=filter_key,
                filter_value=filter_value)

        else:
            result_list, total_count = user.get_users(
                {c.USER_TABLE_COMPANY: company_id})

        if result_list:
            for user_dict in result_list:
                device_deleted = False
                device_info = device.get_device_with_udid(
                    user_dict.get('user_device'))
                if not device_info:
                    device_info = device.get_device_with_udid(
                        user_dict.get('user_device'), status=True)
                    device_deleted = True
                if device_info:
                    device_id = device_info[0].get(c.DEVICE_TABLE_ID)
                else:
                    device_id = None

                if device_deleted:
                    user_dict['user_device'] = None
                    user_dict['user_device_os'] = None

                if device_id:
                    print "printing \n device id", device_id
                    violation_count = violation.get_violation_count(
                        company_id=company_id, device_id=str(device_id))
                else:
                    violation_count = 0
                user_dict['user_violation'] = violation_count

            final_dict['data'] = result_list
            final_dict['count'] = total_count
            final_dict['pass'] = True
            final_dict['message'] = 'Seems like things are working ...'

        else:
            final_dict['pass'] = True
            log.e(tag, 'No User in User Table')
            final_dict['message'] = 'Seems like things are not working ...'
            final_dict['count'] = 0

        # add all the data into dictionary and create output json
        opJson = json.dumps(final_dict)
        self.request.write(opJson)
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)