Example #1
0
    def run(self):
        log = Logger('CompanyPutHandlerThread')
        TAG = 'run'
        # flag to track policy query
        status = False

        if self.data:
            # do stuff here
            company = CompanyDBHelper()
            url_data = self.data.split('/')
            request_data = json.loads(self.request.request.body)
            company_id =  self.company_id  #url_data[0]
            plugin_name = url_data[1]
            company_detail = company.get_company(str(company_id))

            if company_detail:

                company_policy_id = company_detail.get('policy_id')
                command_handler_json = {'to': 'company', 'id': str(company_id),
                                'company_id': self.company_id}

                if plugin_name != 'actions':
                    status = put_individual_plugin(company_policy_id,
                                         plugin_name, request_data)
                else:
                    status = True
                    command_handler_json['action'] = request_data.get('action')
                    command_handler_json['passcode'] = request_data.get(
                        'lock_key')

                if status:
                    create_command_handler_task.delay(command_handler_json)
                    request_data['_id'] = company_policy_id
                    request_data['object_type'] = 'Company'
                    request_data['name'] = company_detail.get(
                        c.COMPANY_TABLE_NAME)
                    opJson = json.dumps({'data': request_data, 'pass': True,
                            'count': 1, 'message': 'Everything fine'})
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)
                else:
                    opJson = json.dumps({'pass': False, 'count': 0,
                        'message': 'Update operation at policy table failed'})
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)

            else:
                log.e(TAG, 'No valid company id is sent in request')
                opJson = json.dumps({'pass': False,
                       'message': 'No valid company id is sent in request'})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            log.e(TAG, 'UnAuthorized Access for company policy ')
            self.request.set_status(401)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Example #2
0
    def run(self):
        log = Logger('LoginWorkerThread')
        TAG = 'run'
        print 'LoginWorkerThread'

        user_name = self.request.get_argument('name', None)
        password = self.request.get_argument('password', None)
        #ipdb.set_trace()

        login = LoginDBHelper()
        admin_detail = login.get_login(user_name)

        #print admin_detail
        if admin_detail is None:
            result = dict()
            result['pass']= False
            result['message']='Authentication failed'
            #self.request.add_header('Access-Control-Allow-Origin', '*')
            self.request.set_header ('Content-Type', 'application/json')
            self.request.redirect('/login.html?err=Invalid+Username+Password+Combination')

        elif admin_detail:
            ## Verify Mr. annonymous

            login_success = verify_password(str(password),
                                  d64(admin_detail.get('password')))

            if login_success:

                ### Session table entry will go here ###
                session = SessionDBHelper()
                session_dict = {}
                session_dict[c.SESSION_TABLE_USER] = admin_detail.get(c.LOGIN_TABLE_ID)
                session_dict[c.SESSION_TABLE_IP] = self.request.request.remote_ip
                session_dict[c.SESSION_TABLE_USER_AGENT] = self.request.request.headers.get(
                                                            'User-Agent')
                session.add_session(session_dict)

                company_helper = CompanyDBHelper()
                company_details = company_helper.get_company(str
                    (admin_detail[c.LOGIN_TABLE_COMPANY]))
                company_name = company_details[c.COMPANY_TABLE_NAME]
                self.request.set_secure_cookie("user",
                                self.request.get_argument("name"))
                self.request.set_secure_cookie("company",
                             str(admin_detail[c.LOGIN_TABLE_COMPANY]))
                self.request.set_secure_cookie("company_name", company_name)
                result = dict()
                result['pass'] = True
                result['message'] = 'Welcome'

                #self.request.write(json.dumps(result))
                if self.request.get_argument('next', None):
                    self.request.redirect('/index.html')
                    #tornado.ioloop.IOLoop.instance().add_callback(self.callback)
                else:
                    self.request.redirect('/index.html')
                    #tornado.ioloop.IOLoop.instance().add_callback(self.callback)

            else:
                print'else'
                result = dict()
                result['pass']= False
                result['message']='Authentication failed'
                #self.request.add_header('Access-Control-Allow-Origin', '*')
                self.request.set_header ('Content-Type', 'application/json')
                self.request.redirect('/login.html?err=Invalid+Username+Password+Combination')
Example #3
0
def admin_mailer(device_id, violation_id, *args, **kwargs):

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

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

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

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

    else:
        device_os = None
        device_os_version = None
        user_info = None

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

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

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

    ### Company information ###

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

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

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

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

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

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

    else:
        log.i(
            TAG,
            """No admin found for the violated device with company id :
{0}""".format(company_id))
Example #4
0
    def merge(self, device_id):
        user_helper = UserDBHelper()
        device_helper = DeviceDBHelper()
        roles_helper = RoleDBHelper()
        teams_helper = TeamDBHelper()
        company_helper = CompanyDBHelper()
        policy_helper = PolicyDBHelper()

        if device_id is not None:
            device_details = device_helper.get_device(device_id)
            if device_details is not None and 'user_id' in device_details:
                user_details = user_helper.get_user(
                    str(device_details['user_id']))
                team_id = user_details['team_id']
                role_id = user_details['role_id']
                company_id = user_details['company_id']

                team_details = teams_helper.get_team(str(team_id))
                role_details = roles_helper.get_role(str(role_id))
                company_details = company_helper.get_company(str(company_id))

                if user_details is not None and 'policy_id' in user_details:
                    policy_id_user = user_details['policy_id']
                else:
                    print 'No user details found'

                if team_details is not None and 'policy_id' in team_details:
                    policy_id_team = team_details['policy_id']
                else:
                    print 'no team details found'

                if role_details is not None and 'policy_id' in role_details:
                    policy_id_role = role_details['policy_id']
                else:
                    print 'no role details found'

                if (company_details is not None
                        and 'policy_id' in company_details):
                    policy_id_company = company_details['policy_id']
                else:
                    print 'no company details found'

                if policy_id_company is not None:
                    print 'company policy id=', policy_id_company
                    policy_company = policy_helper.get_policy(
                        str(policy_id_company))
                else:
                    policy_company = None
                if policy_id_role is not None:
                    print 'role policy id=', policy_id_role
                    policy_role = policy_helper.get_policy(str(policy_id_role))
                else:
                    policy_role = None
                if policy_id_team is not None:
                    print 'team policy id=', policy_id_team
                    policy_team = policy_helper.get_policy(str(policy_id_team))
                else:
                    policy_team = None
                if policy_id_user is not None:
                    print 'user policy id=', policy_id_user
                    policy_user = policy_helper.get_policy(str(policy_id_user))
                else:
                    policy_user = None

                return self.merge_policies(
                    policy_company,
                    policy_role,
                    policy_team,
                    policy_user)
            else:
                print 'Invalid device id'
Example #5
0
def admin_mailer(device_id, violation_id, *args, **kwargs):

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

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

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

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

    else:
        device_os = None
        device_os_version = None
        user_info = None

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

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

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

    ### Company information ###

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

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

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

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

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

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

    else:
        log.i(
            TAG, """No admin found for the violated device with company id :
{0}""".format(company_id))
Example #6
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)
Example #7
0
    def run(self):
        log = Logger('CompanyPutHandlerThread')
        TAG = 'run'
        # flag to track policy query
        status = False

        if self.data:
            # do stuff here
            company = CompanyDBHelper()
            url_data = self.data.split('/')
            request_data = json.loads(self.request.request.body)
            company_id = self.company_id  # url_data[0]
            plugin_name = url_data[1]
            company_detail = company.get_company(str(company_id))

            if company_detail:

                company_policy_id = company_detail.get('policy_id')
                command_handler_json = {'to': 'company', 'id': str(company_id),
                                        'company_id': self.company_id}

                if plugin_name != 'actions':
                    status = put_individual_plugin(company_policy_id,
                                                   plugin_name, request_data)
                else:
                    status = True
                    command_handler_json['action'] = request_data.get('action')
                    command_handler_json['passcode'] = request_data.get(
                        'lock_key')

                if status:
                    create_command_handler_task.delay(command_handler_json)
                    request_data['_id'] = company_policy_id
                    request_data['object_type'] = 'Company'
                    request_data['name'] = company_detail.get(
                        c.COMPANY_TABLE_NAME)
                    opJson = json.dumps(
                        {'data': request_data, 'pass': True,
                            'count': 1, 'message': 'Everything fine'})
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)
                else:
                    opJson = json.dumps(
                        {'pass': False, 'count': 0,
                            'message': 'Update operation at policy table \
failed'})
                    self.request.write(opJson)
                    tornado.ioloop.IOLoop.instance().add_callback(
                        self.callback)

            else:
                log.e(TAG, 'No valid company id is sent in request')
                opJson = json.dumps(
                    {'pass': False,
                        'message': 'No valid company id is sent in request'})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            log.e(TAG, 'UnAuthorized Access for company policy ')
            self.request.set_status(401)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Example #8
0
    def run(self):
        log = Logger('CompanyPolicyGetHandlerThread')
        TAG = 'run'
        if self.data:
            # do stuff here
            url_data = self.data.split('/')
            company_id = self.company_id
            plugin_name = url_data[1]
            company = CompanyDBHelper()
            company_detail = company.get_company(str(company_id))

            if company_detail:

                company_policy_id = company_detail.get('policy_id')

                if plugin_name == 'actions':
                    action_command = True
                else:
                    action_command = False

                if company_policy_id and not action_command:
                    plugin_data = get_individual_plugin(company_policy_id,
                                                        plugin_name)
                elif not action_command:
                    company_policy_id, plugin_data = setup_default_policy()

                    if company_policy_id:
                        company.set_company_policy(company_id,
                                                   company_policy_id)
                        plugin_data = plugin_data.get(plugin_name)
                    else:
                        log.e(TAG, 'Company Policy ID setup failed.')
                        opJson = json.dumps(
                            {'pass': False, 'count': 0,
                                'message': 'Company policy creation failed.'})
                        self.request.write(opJson)
                        tornado.ioloop.IOLoop.instance().add_callback(
                            self.callback)
                else:
                    plugin_data = {}

                if isinstance(plugin_data, str):
                    plugin_data = json.loads(plugin_data)

                plugin_data['_id'] = company_policy_id
                plugin_data['object_type'] = 'Company'
                plugin_data['name'] = company_detail.get(c.COMPANY_TABLE_NAME)
                opJson = json.dumps({'count': 1, 'message': 'Successfull',
                                     'data': plugin_data, 'pass': True})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

            else:
                log.e(TAG, 'No valid company id is sent in request')
                opJson = json.dumps(
                    {'pass': False,
                        'message': 'No valid company id is sent in request'})
                self.request.write(opJson)
                tornado.ioloop.IOLoop.instance().add_callback(self.callback)

        else:
            log.e(TAG, 'UnAuthorized Access for company policy ')
            self.request.set_status(401)
            tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Example #9
0
    def run(self):
        log = Logger('RegisterWorkerThread')
        TAG = 'run'
        print 'RegisterWorkerThread'
        final_dict = {}

        company = CompanyDBHelper()
        admin = LoginDBHelper()

        request_data = json.loads(self.request.request.body)

        company_name = request_data.get('company_name')
        company_email = request_data.get('company_email')
        company_address = request_data.get('company_address')
        company_contact = request_data.get('company_contact')
        admin_name = request_data.get('admin_name')
        admin_email = request_data.get('admin_email')
        admin_password = request_data.get('admin_password')

        company_id, duplicate_company = company.add_company(
                {'name': company_name, 'email': company_email,
                 'contact': company_contact, 'address': company_address})

        # if company_id and duplicate_company:
        #     ## Send mail to admin registered for this company
        #     pass

        if company_id:

            temp_hash = make_verifier(str(admin_password))
            final_hash = e64(temp_hash).strip()
            pass_id = admin.set_login_password(final_hash)

            if pass_id:
                admin_id, duplicate_admin = admin.add_admin(
                    {'email':admin_email, 'name': admin_name,
                    'login_id': pass_id, 'company_id':company_id})

                if admin_id and duplicate_admin:
                    ## Admin already registered, set pass false
                    final_dict['admin'] = True
                    final_dict['pass'] = False


                elif admin_id and not duplicate_admin:
                    final_dict['pass'] = True
                    final_dict['admin'] = False

                    ## send verification mail to this admin
                    admin_signup(admin_id, company_id, admin_email,
                                          company_email)
                else:
                    final_dict['pass'] = False
                    final_dict['admin'] = False

            else:
                final_dict['pass'] = False
                final_dict['admin'] = False
        else:
            final_dict['pass'] = False
            final_dict['admin'] = False

        self.request.write(json.dumps(final_dict))
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
Example #10
0
    def run(self):
        # log = Logger('LoginWorkerThread')
        # TAG = 'run'
        print 'LoginWorkerThread'

        user_name = self.request.get_argument('name', None)
        password = self.request.get_argument('password', None)
        # ipdb.set_trace()

        login = LoginDBHelper()
        admin_detail = login.get_login(user_name)

        # print admin_detail
        if admin_detail is None:
            result = dict()
            result['pass'] = False
            result['message'] = 'Authentication failed'
            #self.request.add_header('Access-Control-Allow-Origin', '*')
            self.request.set_header('Content-Type', 'application/json')
            self.request.redirect(
                '/login.html?err=Invalid+Username+Password+Combination')

        elif admin_detail:
            # Verify Mr. annonymous

            login_success = verify_password(str(password),
                                            d64(admin_detail.get('password')))

            if login_success:

                ### Session table entry will go here ###
                session = SessionDBHelper()
                session_dict = {}
                session_dict[c.SESSION_TABLE_USER] = admin_detail.get(
                    c.LOGIN_TABLE_ID)
                session_dict[
                    c.SESSION_TABLE_IP] = self.request.request.remote_ip
                session_dict[c.SESSION_TABLE_USER_AGENT] = (
                    self.request.request.headers.get('User-Agent'))
                session.add_session(session_dict)

                company_helper = CompanyDBHelper()
                company_details = company_helper.get_company(
                    str(admin_detail[c.LOGIN_TABLE_COMPANY]))
                company_name = company_details[c.COMPANY_TABLE_NAME]
                self.request.set_secure_cookie(
                    "user", self.request.get_argument("name"))
                self.request.set_secure_cookie(
                    "company", str(admin_detail[c.LOGIN_TABLE_COMPANY]))
                self.request.set_secure_cookie("company_name", company_name)
                result = dict()
                result['pass'] = True
                result['message'] = 'Welcome'

                # self.request.write(json.dumps(result))
                if self.request.get_argument('next', None):
                    self.request.redirect('/index.html')
                    # tornado.ioloop.IOLoop.instance().add_callback(
                    #    self.callback)
                else:
                    self.request.redirect('/index.html')
                    # tornado.ioloop.IOLoop.instance().add_callback(
                    #    self.callback)

            else:
                print 'else'
                result = dict()
                result['pass'] = False
                result['message'] = 'Authentication failed'
                #self.request.add_header('Access-Control-Allow-Origin', '*')
                self.request.set_header('Content-Type', 'application/json')
                self.request.redirect(
                    '/login.html?err=Invalid+Username+Password+Combination')
Example #11
0
    def perform(self):
        TAG = 'run'
        print 'In RuN'
        self.insert = True
        json_data = self.data
        print json_data['to']
        #Find out the category of the Device on the basis of 'to' field
        # Case 1 : Command is sent to the USER
        if str(json_data['to']) == 'user':
            to_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            user = UserDBHelper()
            user_dict = user.get_user(str(to_id), company_id=company_id,
                     pluck=[c.USER_TABLE_NAME])
            if user_dict is not None:
                user_name = str(user_dict[c.USER_TABLE_NAME])
                message = "Command sent to " + user_name +\
                        "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(to_id, str(json_data['to']), 'info',
                        None, message, raw=None, company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_user(json_data)
            else:
                self.log.e(TAG, 'No details corresponding to user found')

        #Case 2: Command is sent to the Teams
        elif str(json_data['to']) == 'team':
            print 'sending to teams'
            team_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            team = TeamDBHelper()
            team_dict = team.get_team(str(team_id), company_id=company_id,
                       pluck=[c.TEAM_TABLE_NAME])
            if team_dict is not None:
                team_name = str(team_dict[c.TEAM_TABLE_NAME])

                message = "Command sent to " + team_name +\
                                        "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(team_id, str(json_data['to']), 'info',
                        None, message, raw=None, company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_team(json_data)
            else:
                self.log.e(TAG, "No details corresponding to team_id found. ")

        #Case 3: Command is sent to the Role
        elif str(json_data['to']) == 'role':
            role_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            role = RoleDBHelper()
            role_dict = role.get_role(str(role_id), company_id=company_id,
                            pluck=[c.ROLE_TABLE_NAME])
            if role_dict is not None:
                role_name = str(role_dict[c.ROLE_TABLE_NAME])

                message = "Command sent to " + role_name +\
                                        "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(role_id, str(json_data['to']), 'info',
                        None, message, raw=None, company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_role(json_data)
            else:
                self.log.e(TAG, 'No role corresponding to given role_id found')

        elif str(json_data['to']) == 'company':
            company_id = str(json_data['id'])
            company = CompanyDBHelper()
            company_dict = company.get_company(str(company_id))
            if company_dict is not None:
                company_name = str(company_dict[c.COMPANY_TABLE_NAME])

                message = "Command sent to " + company_name\
                                    +"  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(company_id, str(json_data['to']),
                     'info', None, message, raw=None, company=company_id)
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')

                self.command_to_company(json_data)
            else:
                self.log.e(TAG, 'No data corresponding to team id given found')

        #Case 5: Some other parameter sent in 'to' field
        else:
            self.log.e(TAG, 'Somthing wrong with \'to\' field of POST data')
            ##Create the O/P JSON
            opJson = json.dumps({'pass':False, 'error':'Correct TO field'})
            self.log.e(TAG, str(opJson))
Example #12
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)
Example #13
0
    def merge(self, device_id):
        user_helper = UserDBHelper()
        device_helper = DeviceDBHelper()
        roles_helper = RoleDBHelper()
        teams_helper = TeamDBHelper()
        company_helper = CompanyDBHelper()
        policy_helper = PolicyDBHelper()

        if device_id is not None:
            device_details = device_helper.get_device(device_id)
            if device_details is not None and 'user_id' in device_details:
                user_details = user_helper.get_user(
                    str(device_details['user_id']))
                team_id = user_details['team_id']
                role_id = user_details['role_id']
                company_id = user_details['company_id']

                team_details = teams_helper.get_team(str(team_id))
                role_details = roles_helper.get_role(str(role_id))
                company_details = company_helper.get_company(str(company_id))

                if user_details is not None and 'policy_id' in user_details:
                    policy_id_user = user_details['policy_id']
                else:
                    print 'No user details found'

                if team_details is not None and 'policy_id' in team_details:
                    policy_id_team = team_details['policy_id']
                else:
                    print 'no team details found'

                if role_details is not None and 'policy_id' in role_details:
                    policy_id_role = role_details['policy_id']
                else:
                    print 'no role details found'

                if (company_details is not None
                        and 'policy_id' in company_details):
                    policy_id_company = company_details['policy_id']
                else:
                    print 'no company details found'

                if policy_id_company is not None:
                    print 'company policy id=', policy_id_company
                    policy_company = policy_helper.get_policy(
                        str(policy_id_company))
                else:
                    policy_company = None
                if policy_id_role is not None:
                    print 'role policy id=', policy_id_role
                    policy_role = policy_helper.get_policy(str(policy_id_role))
                else:
                    policy_role = None
                if policy_id_team is not None:
                    print 'team policy id=', policy_id_team
                    policy_team = policy_helper.get_policy(str(policy_id_team))
                else:
                    policy_team = None
                if policy_id_user is not None:
                    print 'user policy id=', policy_id_user
                    policy_user = policy_helper.get_policy(str(policy_id_user))
                else:
                    policy_user = None

                return self.merge_policies(policy_company, policy_role,
                                           policy_team, policy_user)
            else:
                print 'Invalid device id'
Example #14
0
    def perform(self):
        TAG = 'run'
        print 'In RuN'
        self.insert = True
        json_data = self.data
        print json_data['to']
        # Find out the category of the Device on the basis of 'to' field
        # Case 1 : Command is sent to the USER
        if str(json_data['to']) == 'user':
            to_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            user = UserDBHelper()
            user_dict = user.get_user(str(to_id), company_id=company_id,
                                      pluck=[c.USER_TABLE_NAME])
            if user_dict is not None:
                user_name = str(user_dict[c.USER_TABLE_NAME])
                message = "Command sent to " + user_name +\
                    "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(to_id,
                                       str(json_data['to']),
                                       'info',
                                       None,
                                       message,
                                       raw=None,
                                       company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_user(json_data)
            else:
                self.log.e(TAG, 'No details corresponding to user found')

        # Case 2: Command is sent to the Teams
        elif str(json_data['to']) == 'team':
            print 'sending to teams'
            team_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            team = TeamDBHelper()
            team_dict = team.get_team(str(team_id), company_id=company_id,
                                      pluck=[c.TEAM_TABLE_NAME])
            if team_dict is not None:
                team_name = str(team_dict[c.TEAM_TABLE_NAME])

                message = "Command sent to " + team_name +\
                    "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(team_id,
                                       str(json_data['to']),
                                       'info',
                                       None,
                                       message,
                                       raw=None,
                                       company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_team(json_data)
            else:
                self.log.e(TAG, "No details corresponding to team_id found. ")

        # Case 3: Command is sent to the Role
        elif str(json_data['to']) == 'role':
            role_id = str(json_data['id'])
            company_id = json_data.get('company_id')
            role = RoleDBHelper()
            role_dict = role.get_role(str(role_id), company_id=company_id,
                                      pluck=[c.ROLE_TABLE_NAME])
            if role_dict is not None:
                role_name = str(role_dict[c.ROLE_TABLE_NAME])

                message = "Command sent to " + role_name +\
                    "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(role_id,
                                       str(json_data['to']),
                                       'info',
                                       None,
                                       message,
                                       raw=None,
                                       company=str(company_id))
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')
                self.command_to_role(json_data)
            else:
                self.log.e(TAG, 'No role corresponding to given role_id found')

        elif str(json_data['to']) == 'company':
            company_id = str(json_data['id'])
            company = CompanyDBHelper()
            company_dict = company.get_company(str(company_id))
            if company_dict is not None:
                company_name = str(company_dict[c.COMPANY_TABLE_NAME])

                message = "Command sent to " + company_name\
                    + "  having ID = " + str(json_data['id'])
                logs = LogsDBHelper()
                logs_id = logs.add_log(company_id,
                                       str(json_data['to']),
                                       'info',
                                       None,
                                       message,
                                       raw=None,
                                       company=company_id)
                if logs_id is None:
                    self.log.e(TAG, 'Not able to insert the logs')

                self.command_to_company(json_data)
            else:
                self.log.e(TAG, 'No data corresponding to team id given found')

        # Case 5: Some other parameter sent in 'to' field
        else:
            self.log.e(TAG, 'Somthing wrong with \'to\' field of POST data')
            # Create the O/P JSON
            opJson = json.dumps({'pass': False, 'error': 'Correct TO field'})
            self.log.e(TAG, str(opJson))
Example #15
0
def admin_mailer(device_id, violation_id, *args, **kwargs):

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

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

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

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

    else:
        device_os = None
        device_os_version = None
        user_info = None



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

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

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

    ### Company information ###

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

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

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

        else:
            log.i(TAG, """No admin user found for the violated device with company id : {0}""".format(company_id))
            print "Query over admin went wrong"
Example #16
0
    def run(self):
        # log = Logger('RegisterWorkerThread')
        # TAG = 'run'
        print 'RegisterWorkerThread'
        final_dict = {}

        company = CompanyDBHelper()
        admin = LoginDBHelper()

        request_data = json.loads(self.request.request.body)

        company_name = request_data.get('company_name')
        company_email = request_data.get('company_email')
        company_address = request_data.get('company_address')
        company_contact = request_data.get('company_contact')
        admin_name = request_data.get('admin_name')
        admin_email = request_data.get('admin_email')
        admin_password = request_data.get('admin_password')

        company_id, duplicate_company = company.add_company({
            'name':
            company_name,
            'email':
            company_email,
            'contact':
            company_contact,
            'address':
            company_address
        })

        # if company_id and duplicate_company:
        # Send mail to admin registered for this company
        #     pass

        if company_id:

            temp_hash = make_verifier(str(admin_password))
            final_hash = e64(temp_hash).strip()
            pass_id = admin.set_login_password(final_hash)

            if pass_id:
                admin_id, duplicate_admin = admin.add_admin({
                    'email':
                    admin_email,
                    'name':
                    admin_name,
                    'login_id':
                    pass_id,
                    'company_id':
                    company_id
                })

                if admin_id and duplicate_admin:
                    # Admin already registered, set pass false
                    final_dict['admin'] = True
                    final_dict['pass'] = False

                elif admin_id and not duplicate_admin:
                    final_dict['pass'] = True
                    final_dict['admin'] = False

                    # send verification mail to this admin
                    admin_signup(admin_id, company_id, admin_email,
                                 company_email)
                else:
                    final_dict['pass'] = False
                    final_dict['admin'] = False

            else:
                final_dict['pass'] = False
                final_dict['admin'] = False
        else:
            final_dict['pass'] = False
            final_dict['admin'] = False

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