Ejemplo n.º 1
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)
Ejemplo n.º 2
0
    def check_authentication(self,email,passcode):
        TAG='check_authentication'
        if email is not None and passcode is not None:
            from db.helpers.user import UserDBHelper
            user_helper = UserDBHelper()
            users = user_helper.get_user_with_email(email)

            if type(users)==dict:
                user = users
                from db.helpers.enrollment import EnrollmentDBHelper
                enrollment_helper = EnrollmentDBHelper()
                enrollment_filter = {C.ENROLLMENT_TABLE_USER:user['id']}
                enrollments= enrollment_helper.get_enrollments(
                    enrollment_filter, status=False)
                if enrollments is not None:
                    for enrollment in enrollments:
                        if str(enrollment[C.ENROLLMENT_TABLE_PASSWORD]) == str(passcode):
                            self.log.i(TAG, 'Passcodes match')
                            return enrollment
                        else:
                            self.log.i(TAG, 'Invalid passcode email combination')
                    return None
                else:
                    self.log.e(TAG, 'No entry found in user table corresponding to email '+email)
                    return None
            else:
                self.log.e(TAG, 'No user with email address '+email+ ' found')
                return None
        else:
            return None
Ejemplo n.º 3
0
    def check_authentication(self, email, passcode):
        TAG = 'check_authentication'
        if email is not None and passcode is not None:
            from db.helpers.user import UserDBHelper
            user_helper = UserDBHelper()
            users = user_helper.get_user_with_email(email)

            if isinstance(users, dict):
                user = users
                from db.helpers.enrollment import EnrollmentDBHelper
                enrollment_helper = EnrollmentDBHelper()
                enrollment_filter = {C.ENROLLMENT_TABLE_USER: user['id']}
                enrollments = enrollment_helper.get_enrollments(
                    enrollment_filter, status=False)
                if enrollments is not None:
                    for enrollment in enrollments:
                        if str(enrollment[C.ENROLLMENT_TABLE_PASSWORD]) == str(
                                passcode):
                            self.log.i(TAG, 'Passcodes match')
                            return enrollment
                        else:
                            self.log.i(TAG,
                                       'Invalid passcode email combination')
                    return None
                else:
                    self.log.e(TAG,
                               'No entry found in user table corresponding \
                               to email ' + email)
                    return None
            else:
                self.log.e(TAG, 'No user with email address ' + email + '\
                           found')
                return None
        else:
            return None
Ejemplo n.º 4
0
    def run(self):
        # Return All the users in the User table
        log = Logger('UserDeleteHandlerThread')
        tag = 'DELETE'

        if self.data is None:
            log.e(tag, 'No user registered in table for this user_id')
            opJson = json.dumps(
                {'pass': False,
                    'message': 'No user registered in table for this user_id'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        user = UserDBHelper()
        device = DeviceDBHelper()
        enrollment = EnrollmentDBHelper()
        print 'print data here \n ... \n ', self.data

        user_list = user.get_user(str(self.data), company_id=self.company_id)
        if user_list is None:
            log.e(tag, 'No user registered in table for this user_id')
            opJson = json.dumps(
                {'pass': False,
                    'message': 'No user registered in table for this user_id'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            user_deleted = user.delete_user(str(user_list.get('id')))
            if not user_deleted:
                log.e(tag, 'Not able to delete from user table')
                opJson = json.dumps(
                    {'pass': False,
                        'message': 'Not able to delete from user table'})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            else:

                devices = device.get_devices_of_user(str(self.data))
                if devices is not None and len(devices) > 0:
                    for each_device in devices:
                        device_id = each_device.get('id')
                        device.delete_device(str(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})
                log.i(tag, 'User delelted')
                opJson = json.dumps({'pass': True,
                                     'message': 'User Successfully deleted'})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
    def run(self):
        log = Logger('PassVerifyerThread')
        tag = 'run'
        print 'In PassVerify\'s POST'

        loader = Loader("/opt/toppatch/mv/media/app/")
        passwd = str(self.request.get_argument('password', None))
        enrollment_id = self.request.get_argument('hidden', None)
        log.e(tag, 'enrollment id : ' + enrollment_id)

        ### check type of enrollment id ###
        try:
            enrollment_id = int(enrollment_id)
            invalid_enrollment_id = False
            enrollment_id = str(enrollment_id)
        except ValueError:
            invalid_enrollment_id = True

        # No enrollment ID sent
        if enrollment_id is None or invalid_enrollment_id:
            # print 'Some Error in enrollID not present corresponding\
            #     to the password or of invalid format'
            log.e(tag, 'Some Error in program deviceID not present \
                    corresponding to the password or of invalid format')
            self.request.write(loader.load("error_invalid.html").generate(
                message='Invalid link, Mr. intruder. :D ;)',
                status='alert-danger'))
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        # Password not found
        elif passwd is None:
            redirect_url = '''
/enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id)
            self.request.redirect(redirect_url)
            log.i(tag, 'password is incorrect')
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        # Enrollent ID and Password found
        else:

            enrollment = EnrollmentDBHelper()
            ret_dict = enrollment.get_enrollment(enrollment_id)
            # print ret_dict
            ret = None
            if ret_dict is not None:
                ret = str(ret_dict[c.ENROLLMENT_TABLE_PASSWORD])

            else:
                log.e(tag, 'Enrollment password cannot be reterived')

            if ret is None:
                log.e(
                    tag,
                    'DB did not sent the password from Enrollment table')
                self.request.write(loader.load("error_invalid.html").generate(
                    message='Invalid link, Mr. intruder. :D ;)',
                    status='alert-danger'))

                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

            else:
                # Password matched
                if ret == passwd:
                    print 'download the profile'

                    # Now find out the browser details
                    # Create the profile to download
                    thread = CreateProfileThread(enrollment_id)
                    thread.start()
                    thread.join()

                    filename = enrollment_id + '.mobileconfig'
                    signed_filename = 'mdm_' + enrollment_id + '.mobileconfig'

                    log.i(tag, 'Downloading the iOS profile')
                    log.i(tag, 'Signing the iOS profile')
                    sign_command = """
                           openssl smime \
                          -sign \
                         -signer /etc/ssl/star_toppatch_com.pem \
                          -inkey /etc/ssl/star_toppatch_com.key \
                -certfile /opt/toppatch/assets/ios/DigiCertPersonal_chain.pem \
                            -nodetach \
                            -outform der \
                            -in {0} \
                            -out {1}
                            """.format(filename, signed_filename)

                    os.system(sign_command)
                    f = file(signed_filename, 'rb')
                    self.request.set_header(
                        'Content-Type',
                        'application/x-apple-aspen-config; chatset=utf-8')
                    self.request.set_header(
                        'Content-Disposition',
                        'attachment; filename=' +
                        filename +
                        '')
                    self.request.write(f.read())
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)

                    # Delete the file from server after download 'Delay can be
                    # introduced'.
                    os.remove(filename)
                    os.remove(signed_filename)
                else:
                    redirect_url = '''
/enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id)

                    self.request.redirect(redirect_url)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)
                    log.i(tag, 'Incorrect Password for enrollment')
Ejemplo n.º 7
0
    def run(self):
        self.log = Logger('UpdateTokenThread')
        TAG = 'run'
        print 'In UpdateTokenThread\'s POST'

        # Get the parameters which are to be used
        password = str(self.request.get_argument('password', None))
        user_email = str(self.request.get_argument('email', None))
        token = str(self.request.get_argument('token', None))
        print password
        print user_email
        print token

        token = token.replace('<', '')
        token = token.replace('>', '')
        token = token.replace(' ', '')
        result_dict = {}

        user = UserDBHelper()

        user_detail_dict = user.get_user_with_email(user_email)
        print 'user_dict = ' + str(user_detail_dict)
        if user_detail_dict is None:
            self.log.e(
                TAG,
                'No user corresponding to the email = ' +
                str(user_email))
            result_dict['pass'] = False
            result_dict['is_enrolled'] = False
            opJson = json.dumps(result_dict)
            self.request.set_header('Content-Type', 'application/json')
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
        else:

            company = CompanyDBHelper()

            user_id = str(user_detail_dict[C.USER_TABLE_ID])
            user_name = str(user_detail_dict[C.USER_TABLE_NAME])
            company_id = str(user_detail_dict[C.USER_TABLE_COMPANY])

            company_detail_dict = company.get_company(company_id)
            company_name = str(company_detail_dict[C.COMPANY_TABLE_NAME])

            enrollment = EnrollmentDBHelper()
            filter_dict = {
                C.ENROLLMENT_TABLE_USER: str(user_id),
                C.ENROLLMENT_TABLE_PASSWORD: str(password)
            }
            enrollment_list = enrollment.get_enrollments(filter_dict)
            print 'enrollment_list = ' + str(enrollment_list)
            if enrollment_list is None:
                self.log.e(
                    TAG,
                    'No enrollment corresponding to the email = ' +
                    str(user_email) +
                    ' and password = '******'pass'] = False
                result_dict['is_enrolled'] = False
                opJson = json.dumps(result_dict)
                self.request.set_header('Content-Type', 'application/json')
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            else:

                device_id = enrollment_list[0][C.ENROLLMENT_TABLE_DEVICE]
                user_data = {'name': user_name, 'company': company_name}
                result_dict['data'] = user_data

                if device_id is None:
                    self.log.e(TAG, 'No device ID in enrollment table\
                             corresponding to the email = ' +
                               str(user_email) + ' and password = '******'pass'] = True
                    result_dict['is_enrolled'] = False
                    opJson = json.dumps(result_dict)
                    self.request.set_header('Content-Type', 'application/json')
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)
                else:

                    device_detail = DeviceDetailsDBHelper()
                    updated = device_detail.update_device_details(
                        str(device_id), {
                            C.DEVICE_DETAILS_TABLE_MESSAGE_TOKEN: str(token)})

                    if not updated:
                        self.log.e(
                            TAG,
                            'Not able to update Message Token in \
Device Details Table DeviceID = ' + str(device_id))
                        result_dict['pass'] = False
                        result_dict['is_enrolled'] = True
                        opJson = json.dumps(result_dict)
                        self.request.set_header(
                            'Content-Type',
                            'application/json')
                        self.request.write(opJson)
                        tornado.ioloop.IOLoop.instance().add_callback(
                            self.callback)
                    else:
                        self.log.i(
                            TAG,
                            'Device Messge Token updated successfully \
DeviceID = ' + str(device_id))
                        result_dict['pass'] = True
                        result_dict['is_enrolled'] = True
                        opJson = json.dumps(result_dict)
                        self.request.set_header(
                            'Content-Type',
                            'application/json')
                        self.request.write(opJson)
                        tornado.ioloop.IOLoop.instance().add_callback(
                            self.callback)
Ejemplo n.º 8
0
    def parse(self, excel_path, company, company_name=None, callback=None,
              user_added_callback=None):
        COMPANY = company
        company_name = company_name
        book = open_workbook(filename=excel_path)
        sheet = book.sheet_by_index(0)

        users = list()
        for row_index in range(sheet.nrows):
            user = dict()
            for col_index in range(sheet.ncols):
                cell = sheet.cell(row_index, col_index).value
                if col_index == 0:
                    user[C.USER_TABLE_EMAIL] = cell
                elif col_index == 1:
                    user[C.USER_TABLE_NAME] = cell
                elif col_index == 2:
                    user[C.USER_TABLE_TEAM] = cell
                elif col_index == 3:
                    user[C.USER_TABLE_ROLE] = cell
            users.append(user)
        roles_list = list()
        teams_list = list()
        for user in users:
            if C.USER_TABLE_ROLE in user:
                roles_list.append(user[C.USER_TABLE_ROLE])
            if C.USER_TABLE_TEAM in user:
                teams_list.append(user[C.USER_TABLE_TEAM])

        # get a set to get the unique elements.
        roles = dict()
        teams = dict()

        roles_helper = RoleDBHelper()
        teams_helper = TeamDBHelper()
        users_helper = UserDBHelper()
        enrollment_helper = EnrollmentDBHelper()

        for role_name in set(roles_list):
            role = dict()
            role[C.ROLE_TABLE_COMPANY] = COMPANY
            role[C.ROLE_TABLE_NAME] = role_name
            roles[role_name] = roles_helper.add_role(role)

        for team_name in set(teams_list):
            team = dict()
            team[C.TEAM_TABLE_COMPANY] = COMPANY
            team[C.TEAM_TABLE_NAME] = team_name
            team[C.TEAM_TABLE_DELETED] = False
            teams[team_name] = teams_helper.add_team(team)

        # Now we have id for all teams and roles... Insert the users now.
        for user in users:
            user_obj = dict()
            user_obj[C.USER_TABLE_COMPANY] = COMPANY
            user_obj[C.USER_TABLE_EMAIL] = user[C.USER_TABLE_EMAIL]
            user_obj[C.USER_TABLE_NAME] = user[C.USER_TABLE_NAME]
            user_obj[C.USER_TABLE_ROLE] = roles[user[C.USER_TABLE_ROLE]]
            user_obj[C.USER_TABLE_TEAM] = teams[user[C.USER_TABLE_TEAM]]
            user['id'] = users_helper.add_user_if_not_exists(user_obj)[0]
            if user_added_callback is not None:
                user_added_callback(user_obj)

        for user in users:
            enrollment = dict()
            enrollment[C.ENROLLMENT_TABLE_USER] = user['id']
            enrollment[C.ENROLLMENT_TABLE_PASSWORD] = generate_password()
            enrollment[C.ENROLLMENT_TABLE_IS_ENROLLED] = False
            user['passcode'] = enrollment[C.ENROLLMENT_TABLE_PASSWORD]
            print 'adding enrollment ', enrollment
            user['enrollment_id'] = enrollment_helper.add_enrollment(
                enrollment)
            user['company_name'] = company_name
        if callback is not None:
            callback(users)
        return users
Ejemplo n.º 9
0
    def run(self):
        # Find all the POST arguments required

        company_id = self.company_id
        # company_name = str(self.company_name)

        loader = Loader("/opt/toppatch/mv/media/app/")

        # thread1 = {}

        log = Logger('EnrollDevice')
        tag = 'POST'
        request_body = json.loads(self.request.request.body)

        try:
            self.user_email = str(request_body.get('user_email', None))
            self.user_name = str(request_body.get('user_name', None))
            self.team_id = str(request_body.get('team_id', None))
            self.role_id = str(request_body.get('role_id', None))
            self.company_id = str(company_id)
        except:
            self.request.write('Some arguments are not supplied')
            opJson = json.dumps({
                'pass': False,
                'user_name': None,
                'link': None,
                'password': None,
                'error': 'Some argument not supplied'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            log.e(tag,
                  'Some arguments not sent in POST request for enrollment')
            return

        if self.user_email is None or self.user_name is None or\
                self.company_id is None:
            log.e(tag, 'Email or user_name is NULL')
            opJson = json.dumps({
                'pass':
                False,
                'user_name':
                None,
                'link':
                None,
                'password':
                None,
                'error':
                'user_name or Email or Company \
is None'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        if self.user_name == '' or self.user_email == '':
            log.e(tag, 'Email or user_name is empty')
            opJson = json.dumps({
                'pass':
                False,
                'user_name':
                None,
                'link':
                None,
                'password':
                None,
                'error':
                'email or user_name or company \
is empty'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        password = generate_password()

        user = UserDBHelper()
        user_dict = {
            c.USER_TABLE_NAME: str(self.user_name),
            c.USER_TABLE_TEAM: str(self.team_id),
            c.USER_TABLE_ROLE: str(self.role_id),
            c.USER_TABLE_EMAIL: str(self.user_email),
            c.USER_TABLE_COMPANY: str(self.company_id)
        }
        user_id, duplicate = user.add_user_if_not_exists(user_dict)

        if duplicate:
            log.e(tag, 'No id from primary key ')
            opJson = json.dumps({
                'pass': False,
                'user_name': self.user_name,
                'link': None,
                'password': None,
                'duplicate': True,
                'error': 'DB has problem'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            enrollment_dict = {
                c.ENROLLMENT_TABLE_USER: user_id,
                c.ENROLLMENT_TABLE_PASSWORD: password,
                c.ENROLLMENT_TABLE_IS_ENROLLED: False
            }
            enrollment = EnrollmentDBHelper()
            enrollment_id = str(enrollment.add_enrollment(enrollment_dict))

            enrollment_dict = enrollment.get_enrollment(enrollment_id)

            if enrollment_id is not None:
                self.link += enrollment_id

                try:
                    message = loader.load('user_enroll_mail.html').generate(
                        company_name=self.company_name,
                        user_passwd=password,
                        activation_link=self.link)

                    ses_conn.send_email('*****@*****.**',
                                        'MDM Enrollment verification',
                                        message, [self.user_email],
                                        format='html')
                    print 'No error found'
                    log.i(tag, 'Enrollment request successful')
                    opJson = json.dumps({
                        'pass': True,
                        'user_name': self.user_name,
                        'link': 'link',
                        'password': '******',
                        'error': None
                    })

                except Exception as err:
                    print 'Mail Sending error exception is :', repr(err)

                    log.e(tag, 'Incorrect EmailID sent')
                    opJson = json.dumps({
                        'pass': False,
                        'user_name': self.user_name,
                        'link': None,
                        'password': None,
                        'error': 'Wrong emailID'
                    })

            else:
                log.e(
                    tag,
                    'Entry is not done in Enrollment table for UserID = ' +
                    str(user_id))
                opJson = json.dumps({
                    'pass': False,
                    'user_name': self.user_name,
                    'link': None,
                    'password': None,
                    'error': 'Wrong emailID'
                })

            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
    def run(self):
        self.log = Logger('UpdateTokenThread')
        TAG = 'run'
        print 'In UpdateTokenThread\'s POST'

        #Get the parameters which are to be used
        password = str(self.request.get_argument('password',None))
        user_email = str(self.request.get_argument('email', None))
        token = str(self.request.get_argument('token',None))
        print password
        print user_email
        print token

        token = token.replace('<', '')
        token = token.replace('>', '')
        token = token.replace(' ', '')
        result_dict = {}

        user = UserDBHelper()

        user_detail_dict = user.get_user_with_email(user_email)
        print 'user_dict = ' + str(user_detail_dict)
        if user_detail_dict is None:
            self.log.e(TAG, 'No user corresponding to the email = ' + str(user_email))
            result_dict['pass'] = False
            result_dict['is_enrolled'] = False
            opJson = json.dumps(result_dict)
            self.request.set_header ('Content-Type', 'application/json')
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
        else:
            
            company = CompanyDBHelper()

            user_id = str(user_detail_dict[C.USER_TABLE_ID])
            user_name = str(user_detail_dict[C.USER_TABLE_NAME])
            company_id = str(user_detail_dict[C.USER_TABLE_COMPANY])

            company_detail_dict = company.get_company(company_id)
            company_name = str(company_detail_dict[C.COMPANY_TABLE_NAME])
            
            enrollment = EnrollmentDBHelper()
            filter_dict = {
                           C.ENROLLMENT_TABLE_USER : str(user_id),
                           C.ENROLLMENT_TABLE_PASSWORD : str(password)
                           }
            enrollment_list = enrollment.get_enrollments(filter_dict)
            print 'enrollment_list = ' + str(enrollment_list)
            if enrollment_list is None:
                self.log.e(TAG, 'No enrollment corresponding to the email = ' + str(user_email) + ' and password = '******'pass'] = False
                result_dict['is_enrolled'] = False
                opJson = json.dumps(result_dict)
                self.request.set_header ('Content-Type', 'application/json')
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            else:
                
                device_id = enrollment_list[0][C.ENROLLMENT_TABLE_DEVICE]
                user_data = {'name': user_name, 'company': company_name}
                result_dict['data'] = user_data

                if device_id is None:
                    self.log.e(TAG, 'No device ID in enrollment table\
                             corresponding to the email = ' + \
                             str(user_email) + ' and password = '******'pass'] = True
                    result_dict['is_enrolled'] = False
                    opJson = json.dumps(result_dict)
                    self.request.set_header ('Content-Type', 'application/json')
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(self.callback)
                else:
                    
                    device_detail = DeviceDetailsDBHelper()
                    updated = device_detail.update_device_details(str(device_id), {C.DEVICE_DETAILS_TABLE_MESSAGE_TOKEN : str(token)})
                    
                    if not updated:
                        self.log.e(TAG, 'Not able to update Message Token in Device Details Table DeviceID = ' + str(device_id))
                        result_dict['pass'] = False
                        result_dict['is_enrolled'] = True
                        opJson = json.dumps(result_dict)
                        self.request.set_header ('Content-Type', 'application/json')
                        self.request.write(opJson)
                        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
                    else:
                        self.log.i(TAG, 'Device Messge Token updated successfully DeviceID = ' + str(device_id))
                        result_dict['pass'] = True
                        result_dict['is_enrolled'] = True
                        opJson = json.dumps(result_dict)
                        self.request.set_header ('Content-Type', 'application/json')
                        self.request.write(opJson)
                        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Ejemplo n.º 14
0
    def parse(self,
              excel_path,
              company,
              company_name=None,
              callback=None,
              user_added_callback=None):
        COMPANY = company
        company_name = company_name
        book = open_workbook(filename=excel_path)
        sheet = book.sheet_by_index(0)

        users = list()
        for row_index in range(sheet.nrows):
            user = dict()
            for col_index in range(sheet.ncols):
                cell = sheet.cell(row_index, col_index).value
                if col_index == 0:
                    user[C.USER_TABLE_EMAIL] = cell
                elif col_index == 1:
                    user[C.USER_TABLE_NAME] = cell
                elif col_index == 2:
                    user[C.USER_TABLE_TEAM] = cell
                elif col_index == 3:
                    user[C.USER_TABLE_ROLE] = cell
            users.append(user)
        roles_list = list()
        teams_list = list()
        for user in users:
            if C.USER_TABLE_ROLE in user:
                roles_list.append(user[C.USER_TABLE_ROLE])
            if C.USER_TABLE_TEAM in user:
                teams_list.append(user[C.USER_TABLE_TEAM])

        # get a set to get the unique elements.
        roles = dict()
        teams = dict()

        roles_helper = RoleDBHelper()
        teams_helper = TeamDBHelper()
        users_helper = UserDBHelper()
        enrollment_helper = EnrollmentDBHelper()

        for role_name in set(roles_list):
            role = dict()
            role[C.ROLE_TABLE_COMPANY] = COMPANY
            role[C.ROLE_TABLE_NAME] = role_name
            roles[role_name] = roles_helper.add_role(role)

        for team_name in set(teams_list):
            team = dict()
            team[C.TEAM_TABLE_COMPANY] = COMPANY
            team[C.TEAM_TABLE_NAME] = team_name
            team[C.TEAM_TABLE_DELETED] = False
            teams[team_name] = teams_helper.add_team(team)

        # Now we have id for all teams and roles... Insert the users now.
        for user in users:
            user_obj = dict()
            user_obj[C.USER_TABLE_COMPANY] = COMPANY
            user_obj[C.USER_TABLE_EMAIL] = user[C.USER_TABLE_EMAIL]
            user_obj[C.USER_TABLE_NAME] = user[C.USER_TABLE_NAME]
            user_obj[C.USER_TABLE_ROLE] = roles[user[C.USER_TABLE_ROLE]]
            user_obj[C.USER_TABLE_TEAM] = teams[user[C.USER_TABLE_TEAM]]
            user['id'] = users_helper.add_user_if_not_exists(user_obj)[0]
            if user_added_callback is not None:
                user_added_callback(user_obj)

        for user in users:
            enrollment = dict()
            enrollment[C.ENROLLMENT_TABLE_USER] = user['id']
            enrollment[C.ENROLLMENT_TABLE_PASSWORD] = generate_password()
            enrollment[C.ENROLLMENT_TABLE_IS_ENROLLED] = False
            user['passcode'] = enrollment[C.ENROLLMENT_TABLE_PASSWORD]
            print 'adding enrollment ', enrollment
            user['enrollment_id'] = enrollment_helper.add_enrollment(
                enrollment)
            user['company_name'] = company_name
        if callback is not None:
            callback(users)
        return users
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
    def run(self):
        log = Logger('PassVerifyerThread')
        tag = 'run'
        print 'In PassVerify\'s POST'

        loader = Loader("/opt/toppatch/mv/media/app/")
        passwd = str(self.request.get_argument('password', None))
        enrollment_id = self.request.get_argument('hidden', None)
        log.e(tag, 'enrollment id : ' + enrollment_id)

        ### check type of enrollment id ###
        try:
            enrollment_id = int(enrollment_id)
            invalid_enrollment_id = False
            enrollment_id = str(enrollment_id)
        except ValueError:
            invalid_enrollment_id = True

        # No enrollment ID sent
        if enrollment_id is None or invalid_enrollment_id:
            # print 'Some Error in enrollID not present corresponding\
            #     to the password or of invalid format'
            log.e(
                tag, 'Some Error in program deviceID not present \
                    corresponding to the password or of invalid format')
            self.request.write(
                loader.load("error_invalid.html").generate(
                    message='Invalid link, Mr. intruder. :D ;)',
                    status='alert-danger'))
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        # Password not found
        elif passwd is None:
            redirect_url = '''
/enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id)
            self.request.redirect(redirect_url)
            log.i(tag, 'password is incorrect')
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        # Enrollent ID and Password found
        else:

            enrollment = EnrollmentDBHelper()
            ret_dict = enrollment.get_enrollment(enrollment_id)
            # print ret_dict
            ret = None
            if ret_dict is not None:
                ret = str(ret_dict[c.ENROLLMENT_TABLE_PASSWORD])

            else:
                log.e(tag, 'Enrollment password cannot be reterived')

            if ret is None:
                log.e(tag,
                      'DB did not sent the password from Enrollment table')
                self.request.write(
                    loader.load("error_invalid.html").generate(
                        message='Invalid link, Mr. intruder. :D ;)',
                        status='alert-danger'))

                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

            else:
                # Password matched
                if ret == passwd:
                    print 'download the profile'

                    # Now find out the browser details
                    # Create the profile to download
                    thread = CreateProfileThread(enrollment_id)
                    thread.start()
                    thread.join()

                    filename = enrollment_id + '.mobileconfig'
                    signed_filename = 'mdm_' + enrollment_id + '.mobileconfig'

                    log.i(tag, 'Downloading the iOS profile')
                    log.i(tag, 'Signing the iOS profile')
                    sign_command = """
                           openssl smime \
                          -sign \
                         -signer /etc/ssl/star_toppatch_com.pem \
                          -inkey /etc/ssl/star_toppatch_com.key \
                -certfile /opt/toppatch/assets/ios/DigiCertPersonal_chain.pem \
                            -nodetach \
                            -outform der \
                            -in {0} \
                            -out {1}
                            """.format(filename, signed_filename)

                    os.system(sign_command)
                    f = file(signed_filename, 'rb')
                    self.request.set_header(
                        'Content-Type',
                        'application/x-apple-aspen-config; chatset=utf-8')
                    self.request.set_header(
                        'Content-Disposition',
                        'attachment; filename=' + filename + '')
                    self.request.write(f.read())
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)

                    # Delete the file from server after download 'Delay can be
                    # introduced'.
                    os.remove(filename)
                    os.remove(signed_filename)
                else:
                    redirect_url = '''
/enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id)

                    self.request.redirect(redirect_url)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)
                    log.i(tag, 'Incorrect Password for enrollment')
Ejemplo n.º 17
0
    def run(self):
        # Return All the users in the User table
        log = Logger('UserDeleteHandlerThread')
        tag = 'DELETE'

        if self.data is None:
            log.e(tag, 'No user registered in table for this user_id')
            opJson = json.dumps({
                'pass':
                False,
                'message':
                'No user registered in table for this user_id'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        user = UserDBHelper()
        device = DeviceDBHelper()
        enrollment = EnrollmentDBHelper()
        print 'print data here \n ... \n ', self.data

        user_list = user.get_user(str(self.data), company_id=self.company_id)
        if user_list is None:
            log.e(tag, 'No user registered in table for this user_id')
            opJson = json.dumps({
                'pass':
                False,
                'message':
                'No user registered in table for this user_id'
            })
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            user_deleted = user.delete_user(str(user_list.get('id')))
            if not user_deleted:
                log.e(tag, 'Not able to delete from user table')
                opJson = json.dumps({
                    'pass':
                    False,
                    'message':
                    'Not able to delete from user table'
                })
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            else:

                devices = device.get_devices_of_user(str(self.data))
                if devices is not None and len(devices) > 0:
                    for each_device in devices:
                        device_id = each_device.get('id')
                        device.delete_device(str(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
                                })
                log.i(tag, 'User delelted')
                opJson = json.dumps({
                    'pass': True,
                    'message': 'User Successfully deleted'
                })
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Ejemplo n.º 18
0
    def run(self):
        #Find all the POST arguments required

        company_id = self.company_id
        company_name = str(self.company_name)

        loader = Loader("/opt/toppatch/mv/media/app/")

        thread1 = {}

        log = Logger('EnrollDevice')
        tag = 'POST'
        request_body = json.loads(self.request.request.body)


        try:
            self.user_email = str(request_body.get('user_email', None))
            self.user_name = str(request_body.get('user_name', None))
            self.team_id = str(request_body.get('team_id', None))
            self.role_id = str(request_body.get('role_id', None))
            self.company_id = str(company_id)
        except:
            self.request.write('Some arguments are not supplied')
            opJson = json.dumps({'pass':False, 'user_name': None,
                                 'link' : None, 'password':None,
                                  'error':'Some argument not supplied'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
            log.e(tag, 'Some arguments not sent in POST request for enrollment')
            return

        if self.user_email is None or self.user_name is None or\
                         self.company_id is None:
            log.e(tag, 'Email or user_name is NULL')
            opJson = json.dumps({'pass':False, 'user_name': None,
                        'link' : None, 'password':None,
                         'error':'user_name or Email or Company is None'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)


        if self.user_name == '' or self.user_email == '':
            log.e(tag, 'Email or user_name is empty')
            opJson = json.dumps({'pass':False, 'user_name': None,
                             'link' : None, 'password':None,
                        'error':'email or user_name or company is empty'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)


        password = generate_password()

        user = UserDBHelper()
        user_dict = {
                    c.USER_TABLE_NAME: str(self.user_name),
                    c.USER_TABLE_TEAM : str(self.team_id),
                    c.USER_TABLE_ROLE: str(self.role_id),
                    c.USER_TABLE_EMAIL: str(self.user_email),
                    c.USER_TABLE_COMPANY: str(self.company_id)
                   }
        user_id, duplicate = user.add_user_if_not_exists(user_dict)

        if duplicate:
            log.e(tag,'No id from primary key ')
            opJson = json.dumps({'pass':False, 'user_name': self.user_name,
                         'link' : None, 'password':None, 'duplicate': True,
                        'error':'DB has problem'})
            self.request.write(opJson)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            enrollment_dict = {
                              c.ENROLLMENT_TABLE_USER: user_id,
                              c.ENROLLMENT_TABLE_PASSWORD: password,
                              c.ENROLLMENT_TABLE_IS_ENROLLED: False
                              }
            enrollment = EnrollmentDBHelper()
            enrollment_id = str(enrollment.add_enrollment(enrollment_dict))

            enrollment_dict = enrollment.get_enrollment(enrollment_id)

            if enrollment_id is not None:
                self.link += enrollment_id

                try:
                    message = loader.load('user_enroll_mail.html').generate(
                           company_name=self.company_name,
                           user_passwd=password, activation_link=self.link)

                    ses_conn.send_email('*****@*****.**',
                                'MDM Enrollment verification', message,
                                 [self.user_email], format='html')
                    print 'No error found'
                    log.i(tag, 'Enrollment request successful')
                    opJson = json.dumps({'pass':True, 'user_name': self.user_name,
                     'link' : 'link', 'password':'******', 'error':None})

                except Exception, err:
                    print 'Mail Sending error exception is :', repr(err)

                    log.e(tag, 'Incorrect EmailID sent')
                    opJson = json.dumps({'pass':False, 'user_name': self.user_name,
                      'link' : None, 'password':None, 'error':'Wrong emailID'})

            else:
    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)