Exemple #1
0
    def get(self, *args, **kwargs):
        user_id = self.get_current_id()

        redis_conn = cache_conn()
        page = redis_conn.hget("{}_rules".format(user_id), 'page')
        component = redis_conn.hget("{}_rules".format(user_id), 'component')

        data = dict(rules=dict(page=literal_eval(convert(page)),
                               component=literal_eval(convert(component))))
        return self.write(dict(data=data, code=0, msg='获取前端权限成功'))
    def post(self, *args, **kwargs):
        ### 发送邮件
        data = json.loads(self.request.body.decode('utf-8'))
        phone = data.get('phone', None)
        msg = data.get('msg', None)  # json格式 对应短信模板里设置的参数
        template_code = data.get('template_code', None)
        sign_name = data.get('sign_name', 'OPS')
        redis_conn = cache_conn()
        if not phone and not msg and not template_code:
            return self.write(dict(code=-1, msg='收件人、邮件标题、邮件内容不能为空'))

        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        try:
            obj = SendSms(config_info.get(const.SMS_REGION),
                          config_info.get(const.SMS_DOMAIN),
                          config_info.get(const.SMS_PRODUCT_NAME),
                          config_info.get(const.SMS_ACCESS_KEY_ID),
                          config_info.get(const.SMS_ACCESS_KEY_SECRET))

            params = json.dumps(msg)
            sms_response = obj.send_sms(phone,
                                        template_param=params,
                                        sign_name=sign_name,
                                        template_code=template_code)
            sms_response = json.loads(sms_response.decode('utf-8'))
            if sms_response.get("Message") == "OK":
                return self.write(dict(code=0, msg='短信发送成功'))
            else:
                return self.write(
                    dict(code=-2, msg='短信发送失败{}'.format(str(sms_response))))

        except Exception as e:
            return self.write(dict(code=-1, msg='短信发送失败 {}'.format(str(e))))
    def post(self, *args, **kwargs):
        ### 发送邮件
        data = json.loads(self.request.body.decode('utf-8'))
        to_list = data.get('to_list', None)
        subject = data.get('subject', None)
        content = data.get('content', None)
        subtype = data.get('subtype', None)
        att = data.get('att', None)
        redis_conn = cache_conn()
        if not to_list and not subject and not content:
            return self.write(dict(code=-1, msg='收件人、邮件标题、邮件内容不能为空'))

        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        try:
            obj = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

            obj.send_mail(to_list, subject, content, subtype=subtype, att=att)
            return self.write(dict(code=0, msg='邮件发送成功'))

        except Exception as e:
            return self.write(dict(code=-1, msg='邮件发送失败 {}'.format(str(e))))
Exemple #4
0
    def post(self, *args, **kwargs):
        ###文件保存到本地
        # Base_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        # upload_path = '{}/static'.format(Base_DIR)
        # file_metas = self.request.files.get('file', None)  # 提取表单中‘name’为‘file’的文件元数据
        # ret = {'result': 'OK'}
        # if not file_metas:
        #     ret['result'] = 'Invalid Args'
        #     return ret
        #
        # for meta in file_metas:
        #     filename = meta['filename']
        #     print('filename---->', filename)
        #     file_path = os.path.join(upload_path, filename)
        #     with open(file_path, 'wb') as up:
        #         up.write(meta['body'])
        #
        # self.write(json.dumps(ret))

        ###文件保存到OSS
        ###获取OSS的配置
        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
        if cache_config_info:
            config_info = convert(cache_config_info)
        else:
            return self.write(dict(code=-1, msg='【系统管理】-【系统配置】-【存储配置】中没有检测到OSS配置信息'))

        file_metas = self.request.files.get('file', None)  # 提取表单中‘name’为‘file’的文件元数据

        if not file_metas:
            return self.write(dict(code=-2, msg='没有文件数据'))

        for meta in file_metas:
            filename = meta['filename']
            # print('filename---->', filename)
            file_data = meta['body']
            oss_data = {
                'STORAGE_KEY_ID': config_info.get('STORAGE_KEY_ID'),
                'STORAGE_KEY_SECRET': config_info.get('STORAGE_KEY_SECRET'),
                'STORAGE_REGION': config_info.get('STORAGE_REGION'),
                'STORAGE_NAME': config_info.get('STORAGE_NAME'),
                'STORAGE_PATH': 'fault'  # https://opendevops.oss-cn-shanghai.aliyuncs.com/fault/xxx.pdf
            }
            #
            # obj = OSSApi(
            #     oss_data.get('STORAGE_KEY_ID'), 'xxxx',
            #     oss_data.get('STORAGE_REGION'),
            #     oss_data.get('STORAGE_NAME'), oss_data.get('STORAGE_PATH'))
            # obj.setObj(filename, file_data)
            try:
                obj = OSSApi(
                    oss_data.get('STORAGE_KEY_ID'), oss_data.get('STORAGE_KEY_SECRET'),
                    oss_data.get('STORAGE_REGION'),
                    oss_data.get('STORAGE_NAME'), oss_data.get('STORAGE_PATH'))
                obj.setObj(filename, file_data)
            except Exception as e:
                return self.write(dict(code=-1, msg='上传失败,请检查OSS配置'))


        self.write(dict(code=0, msg="上传成功"))
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode('utf-8'))
        check_key = data.get('check_key')
        user_id = self.get_current_id()

        redis_conn = cache_conn()
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)

        if check_key == 'EMAIL':
            with DBContext('r') as session:
                mail_to = session.query(Users.email).filter(Users.user_id == user_id).first()

            obj = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                           mail_user=config_info.get(const.EMAIL_HOST_USER),
                           mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                           mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

            obj.send_mail(mail_to[0], 'OPS测试邮件', '测试发送邮件成功', subtype='plain')
            return self.write(dict(code=0, msg='测试邮件已经发送'))

        elif check_key == 'SMS':
            obj = SendSms(config_info.get(const.SMS_REGION), config_info.get(const.SMS_DOMAIN),
                          config_info.get(const.SMS_PRODUCT_NAME), config_info.get(const.SMS_ACCESS_KEY_ID),
                          config_info.get(const.SMS_ACCESS_KEY_SECRET))

            query_response = obj.query_send_detail('', '11111111111', 1, 1, time.strftime("%Y%m%d", time.localtime()))
            query_response = json.loads(query_response.decode('utf-8'))
            if query_response.get("Message") == "OK":
                return self.write(dict(code=0, msg='测试短信成功'))
            else:
                return self.write(dict(code=-2, msg='测试短信失败{}'.format(str(query_response))))
        else:
            return self.write(dict(code=-1, msg='未知测试项目'))
Exemple #6
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        alerts = data.get('alerts')  # 获取AlertManager POST报警数据
        #alerts = [{'status': 'firing', 'labels': {'alertname': 'Node主机CPU利用率过高', 'instance': '172.16.1.53:9100', 'prometheus': 'monitoring/k8s', 'severity': '严重'}, 'annotations': {'detail': '172.16.1.53:9100: CPU利用率过高于75% (当前值: 92.11666666667345)', 'summary': '172.16.1.53:9100: CPU利用率过高'}, 'startsAt': '2019-03-18T05:34:54.025953211Z', 'endsAt': '0001-01-01T00:00:00Z', 'generatorURL': 'http://prometheus-k8s-1:9090/graph?g0.expr=100+-+%28avg+by%28instance%29+%28irate%28node_cpu_seconds_total%7Bjob%3D%22node-exporter%22%2Cmode%3D%22idle%22%7D%5B5m%5D%29%29+%2A+100%29+%3E+75&g0.tab=1'}]
        for alerts_data in alerts:
            labels = alerts_data.get('labels')
            alert_name = labels.get('alertname')
            print('alert_name---->', alert_name)
            cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
            if cache_config_info:
                config_info = convert(cache_config_info)
            else:
                config_info = configs['email_info']

            emails_list = redis_conn.hvals(alert_name)
            print('Email_list----->', emails_list)
            sm = SendMail(
                mail_host=config_info.get(const.EMAIL_HOST),
                mail_port=config_info.get(const.EMAIL_PORT),
                mail_user=config_info.get(const.EMAIL_HOST_USER),
                mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                mail_ssl=True
                if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
            ### 如果没有redis没有配置
            if not emails_list:
                # print(configs.get('default_email'))[0]  #元祖类型
                sm.send_mail(
                    configs.get('default_email')[0], alert_name,
                    alerts_data['annotations']['detail'])
                # print('msg=',alerts_data['annotations']['detail'])
                return self.write(dict(code=-1, msg="没有匹配到规则"))

            ### 默认发送邮件
            sm.send_mail(",".join(emails_list), alert_name,
                         alerts_data['annotations']['detail'])

            # 严重警告发短信
            if labels.get('severity') == "严重":
                if not configs.get('sign_name') or not configs.get(
                        'template_code'):
                    sm.send_mail(configs.get('default_email'), alert_name,
                                 '请配置短信的sign_name和template_code')
                else:
                    phone_numbers = redis_conn.hkeys(alert_name)
                    # 发送内容
                    params = {"msg": alerts_data['annotations']['detail']}
                    sms = SendSms(config_info.get(const.SMS_REGION),
                                  config_info.get(const.SMS_DOMAIN),
                                  config_info.get(const.SMS_PRODUCT_NAME),
                                  config_info.get(const.SMS_ACCESS_KEY_ID),
                                  config_info.get(const.SMS_ACCESS_KEY_SECRET))

                    sms.send_sms(phone_numbers=",".join(phone_numbers),
                                 template_param=params,
                                 sign_name=configs.get('sign_name')[0],
                                 template_code=configs.get('template_code')[0])

        return self.write(dict(code=0, msg="发送成功", data=alerts))
Exemple #7
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) != 1:
            return self.write(dict(code=-2, msg='一次只能选择一个用户,且不能为空'))

        user_id = user_list[0]
        with DBContext('r') as session:
            user_info = session.query(Users).filter(
                Users.user_id == user_id).first()

        ### 生成token
        if user_info.superuser == '0':
            is_superuser = True
        else:
            is_superuser = False

        token_info = dict(user_id=user_id,
                          username=user_info.username,
                          nickname=user_info.nickname,
                          is_superuser=is_superuser,
                          exp_time=1100)
        auth_token = AuthToken()
        auth_key = auth_token.encode_auth_token_v2(**token_info)
        if isinstance(auth_key, bytes): auth_key = auth_key.decode()

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            mail_to = session.query(Users.email).filter(
                Users.user_id == self.get_current_id()).first()

        if mail_to[0] == user_info.email:
            obj.send_mail(mail_to[0], '令牌,有效期三年', auth_key, subtype='plain')
        else:
            obj.send_mail(mail_to[0], '令牌,有效期三年', auth_key, subtype='plain')
            obj.send_mail(user_info.email,
                          '令牌,有效期三年',
                          auth_key,
                          subtype='plain')
        return self.write(dict(code=0, msg='Token已经发送到邮箱', data=auth_key))
Exemple #8
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode('utf-8'))
        check_key = data.get('check_key')
        user_id = self.get_current_id()

        redis_conn = cache_conn()
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)

        if check_key == 'EMAIL':
            with DBContext('r') as session:
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

            send_list = [mail_to[0], 'OPS测试邮件', '测试发送邮件成功', 'plain', None]
            res = yield self.send_mail_pool(send_list, config_info)
            return self.write(res)

        elif check_key == 'SMS':
            obj = SendSms(config_info.get(const.SMS_REGION),
                          config_info.get(const.SMS_DOMAIN),
                          config_info.get(const.SMS_PRODUCT_NAME),
                          config_info.get(const.SMS_ACCESS_KEY_ID),
                          config_info.get(const.SMS_ACCESS_KEY_SECRET))

            query_response = obj.query_send_detail(
                '', '11111111111', 1, 1,
                time.strftime("%Y%m%d", time.localtime()))
            query_response = json.loads(query_response.decode('utf-8'))
            if query_response.get("Message") == "OK":
                return self.write(dict(code=0, msg='测试短信成功'))
            else:
                return self.write(
                    dict(code=-2, msg='测试短信失败{}'.format(str(query_response))))
        elif check_key == 'LDAP':
            ldap_ssl = True if config_info.get(
                const.LDAP_USE_SSL) == '1' else False

            obj = LdapApi(config_info.get(const.LDAP_SERVER_HOST),
                          config_info.get(const.LDAP_ADMIN_DN),
                          config_info.get(const.LDAP_ADMIN_PASSWORD),
                          int(config_info.get(const.LDAP_SERVER_PORT, 389)),
                          ldap_ssl)

            if obj.ldap_server_test():
                return self.write(dict(code=0, msg='LDAP连接测试成功'))
            else:
                return self.write(dict(code=-1, msg='LDAP连接测试不成功,请仔细检查配置'))

        else:
            return self.write(dict(code=-1, msg='未知测试项目'))
Exemple #9
0
 def send_mail(self, content):
     """
     发送Mail
     :return:
     content: 邮件内容
     """
     cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
     if cache_config_info:
         config_info = convert(cache_config_info)
     else:
         config_info = configs['email_info']
     sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                   mail_user=config_info.get(const.EMAIL_HOST_USER),
                   mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                   mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
     sm.send_mail(AWS_EVENT_TO_EMAIL, 'AwsEvents告警', content)
Exemple #10
0
    def get(self, *args, **kwargs):
        """从redis获取阿里云OSS基本信息"""
        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)

        if cache_config_info:
            config_info = convert(cache_config_info)

            if not config_info['STORAGE_REGION'] and not config_info['STORAGE_REGION']:
                return self.write(dict(code=-1, msg='没有发现OSS配置信息'))

            oss_info = {
                'STORAGE_REGION': config_info.get('STORAGE_REGION'),
                'STORAGE_NAME': config_info.get('STORAGE_NAME')
            }
            self.write(dict(code=0, msg="获取成功", data=oss_info))
        else:
            self.write(dict(code=-2, msg="没有在redis缓存发现配置信息"))
    def post(self, *args, **kwargs):
        ### 发送短信
        data = json.loads(self.request.body.decode('utf-8'))
        phone = data.get('phone', None)
        msg = data.get('msg', None)  # json格式 对应短信模板里设置的参数
        template_code = data.get('template_code', None)
        sign_name = data.get('sign_name', 'OPS')
        redis_conn = cache_conn()
        if not phone and not msg and not template_code:
            return self.write(dict(code=-1, msg='收件人、邮件标题、邮件内容不能为空'))

        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        #
        send_list = [phone, msg, sign_name, template_code]
        res = yield self.send_sms_pool(send_list, config_info)
        return self.write(res)
    def post(self, *args, **kwargs):
        ### 发送邮件
        data = json.loads(self.request.body.decode('utf-8'))
        to_list = data.get('to_list', None)
        subject = data.get('subject', None)
        content = data.get('content', None)
        subtype = data.get('subtype', None)
        att = data.get('att', None)
        redis_conn = cache_conn()
        if not to_list and not subject and not content:
            return self.write(dict(code=-1, msg='收件人、邮件标题、邮件内容不能为空'))

        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        send_list = [to_list, subject, content, subtype, att]
        res = yield self.send_mail_pool(send_list, config_info)
        return self.write(res)
Exemple #13
0
    def send_email(self, alert_email_list, content):
        """
        发送邮件
        :return:
        """

        cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
        if cache_config_info:
            config_info = convert(cache_config_info)
        else:
            config_info = configs['email_info']

        # emails_list = redis_conn.hvals(alert_name)
        sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
                      mail_user=config_info.get(const.EMAIL_HOST_USER),
                      mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
                      mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)
        ### 默认发送邮件
        sm.send_mail(",".join(alert_email_list), 'DevOps消息提醒', content)
Exemple #14
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) < 1:
            return self.write(dict(code=-1, msg='用户不能为空'))

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            for user_id in user_list:
                mfa = base64.b32encode(
                    bytes(str(shortuuid.uuid() + shortuuid.uuid())[:-9],
                          encoding="utf-8")).decode("utf-8")
                session.query(Users).filter(Users.user_id == user_id).update({
                    Users.last_ip:
                    '',
                    Users.google_key:
                    mfa
                })
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

                obj.send_mail(mail_to[0], '重置MFA', mfa, subtype='plain')

        return self.write(dict(code=0, msg='重置MFA成功,新的MFA已经发送到邮箱'))
Exemple #15
0
    def put(self, *args, **kwargs):
        if not self.is_superuser:
            return self.write(dict(code=-1, msg='不是超级管理员,没有权限'))

        data = json.loads(self.request.body.decode("utf-8"))
        user_list = data.get('user_list', None)

        if len(user_list) < 1:
            return self.write(dict(code=-2, msg='用户不能为空'))

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            for user_id in user_list:
                md5_password = shortuuid.uuid()
                new_password = gen_md5(md5_password)
                session.query(Users).filter(Users.user_id == user_id).update(
                    {Users.password: new_password})
                mail_to = session.query(
                    Users.email).filter(Users.user_id == user_id).first()

                obj.send_mail(mail_to[0],
                              '修改密码',
                              md5_password,
                              subtype='plain')
        return self.write(dict(code=0, msg='重置密码成功,新密码已经发送到邮箱'))
Exemple #16
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        username = data.get('username', None)
        password = data.get('password', None)
        dynamic = data.get('dynamic', None)

        if not username or not password: return self.write(dict(code=-1, msg='账号密码不能为空'))

        redis_conn = cache_conn()
        configs_init('all')
        if is_mail(username):
            login_mail = redis_conn.hget(const.APP_SETTINGS, const.EMAILLOGIN_DOMAIN)
            if login_mail:
                if is_mail(username, login_mail.decode('utf-8')):
                    email = username
                    username = email.split("@")[0]
                    email_server = redis_conn.hget(const.APP_SETTINGS, const.EMAILLOGIN_SERVER).decode('utf-8')
                    if not email_server:
                        return self.write(dict(code=-9, msg='请配置邮箱服务的SMTP服务地址'))

                    if not mail_login(email, password, email_server):
                        return self.write(dict(code=-2, msg='邮箱登陆认证失败'))

                    with DBContext('r') as session:
                        user_info = session.query(Users).filter(Users.email == email, Users.username == username,
                                                                Users.status != '10').first()
                    if not user_info:
                        return self.write(dict(code=-3, msg='邮箱认证通过,请根据邮箱完善用户信息', username=username, email=email))

        else:
            with DBContext('r') as session:
                user_info = session.query(Users).filter(Users.username == username, Users.password == gen_md5(password),
                                                        Users.status != '10').first()

            if not user_info:
                # redis_conn = cache_conn()
                # configs_init('all')
                ldap_login = redis_conn.hget(const.APP_SETTINGS, const.LDAP_ENABLE)
                ldap_login = convert(ldap_login)
                if ldap_login != '1':
                    return self.write(dict(code=-4, msg='账号密码错误'))

                ### 如果开启了LDAP认证 则进行LDAP认证
                else:
                    ####
                    config_info = redis_conn.hgetall(const.APP_SETTINGS)
                    config_info = convert(config_info)
                    ldap_ssl = True if config_info.get(const.LDAP_USE_SSL) == '1' else False

                    obj = LdapApi(config_info.get(const.LDAP_SERVER_HOST), config_info.get(const.LDAP_ADMIN_DN),
                                  config_info.get(const.LDAP_ADMIN_PASSWORD),
                                  int(config_info.get(const.LDAP_SERVER_PORT, 389)),
                                  ldap_ssl)

                    ldap_pass_info = obj.ldap_auth(username, password, config_info.get(const.LDAP_SEARCH_BASE),
                                                   config_info.get(const.LDAP_SEARCH_FILTER))

                    if ldap_pass_info[0]:
                        with DBContext('r') as session:
                            if not ldap_pass_info[2]:
                                return self.write(dict(code=-11, msg='LDAP认证成功,但是没有找到用户邮箱,请完善!'))
                            else:
                                user_info = session.query(Users).filter(Users.email == ldap_pass_info[2],
                                                                        Users.username == username,
                                                                        Users.status != '10').first()
                            if not user_info:
                                return self.write(dict(code=-3, msg='LDAP认证通过,完善用户信息', username=ldap_pass_info[1],
                                                       email=ldap_pass_info[2]))
                    else:
                        return self.write(dict(code=-4, msg='账号密码错误'))

        if 'user_info' not in dir():
            return self.write(dict(code=-4, msg='账号异常'))

        if user_info.status != '0':
            return self.write(dict(code=-4, msg='账号被禁用'))

        is_superuser = True if user_info.superuser == '0' else False

        ### 如果被标记为必须动态验证切没有输入动态密钥,则跳转到二维码添加密钥的地方
        ### 默认为 True, False 则全局禁用MFA
        mfa_global = False if convert(redis_conn.hget(const.APP_SETTINGS, const.MFA_GLOBAL)) == '1' else True
        if mfa_global and user_info.google_key:
            if not dynamic:
                ### 第一次不带MFA的认证
                return self.write(dict(code=1, msg='跳转二次认证'))
            else:
                ### 二次认证
                t_otp = pyotp.TOTP(user_info.google_key)
                if t_otp.now() != str(dynamic):
                    return self.write(dict(code=-5, msg='MFA错误'))

        user_id = str(user_info.user_id)
        ### 生成token 并写入cookie
        token_exp_hours = redis_conn.hget(const.APP_SETTINGS, const.TOKEN_EXP_TIME)
        if token_exp_hours and convert(token_exp_hours):
            token_info = dict(user_id=user_id, username=user_info.username, nickname=user_info.nickname,
                              email=user_info.email, is_superuser=is_superuser, exp_hours=token_exp_hours)
        else:
            token_info = dict(user_id=user_id, username=user_info.username, nickname=user_info.nickname,
                              email=user_info.email, is_superuser=is_superuser)
        auth_token = AuthToken()
        auth_key = auth_token.encode_auth_token_v2(**token_info)
        login_ip_list = self.request.headers.get("X-Forwarded-For")
        if login_ip_list:
            login_ip = login_ip_list.split(",")[0]
            with DBContext('w', None, True) as session:
                session.query(Users).filter(Users.user_id == user_id).update({Users.last_ip: login_ip})
                session.commit()

        self.set_secure_cookie("nickname", user_info.nickname)
        self.set_secure_cookie("username", user_info.username)
        self.set_secure_cookie("user_id", str(user_info.user_id))
        self.set_cookie('auth_key', auth_key, expires_days=1)

        ### 后端权限写入缓存
        my_verify = MyVerify(user_id, is_superuser)
        my_verify.write_verify()
        ### 前端权限写入缓存
        # get_user_rules(user_id, is_superuser)

        return self.write(dict(code=0, auth_key=auth_key.decode(), username=user_info.username,
                               nickname=user_info.nickname, msg='登录成功'))
Exemple #17
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        username = data.get('username', None)
        nickname = data.get('nickname', None)
        password = data.get('password', None)
        department = data.get('department', None)
        tel = data.get('tel', None)
        wechat = data.get('wechat', None)
        no = data.get('no', None)
        email = data.get('email', None)
        if not username or not nickname or not department or not tel or not wechat or not no or not email:
            return self.write(dict(code=-1, msg='参数不能为空'))

        with DBContext('r') as session:
            user_info1 = session.query(Users).filter(
                Users.username == username).first()
            user_info2 = session.query(Users).filter(Users.tel == tel).first()
            user_info3 = session.query(Users).filter(
                Users.email == email).first()
            user_info4 = session.query(Users).filter(
                Users.nickname == nickname).first()

        if user_info1:
            return self.write(dict(code=-2, msg='用户名已注册'))

        if user_info2:
            return self.write(dict(code=-3, msg='手机号已注册'))

        if user_info3:
            return self.write(dict(code=-4, msg='邮箱已注册'))

        if user_info4:
            return self.write(dict(code=-4, msg='昵称已注册'))

        if not password:
            md5_password = shortuuid.uuid()
            password = gen_md5(md5_password)
        else:
            if not check_password(password):
                return self.write(
                    dict(code=-5, msg='密码复杂度必须为: 超过8位,包含数字,大小写字母 等'))
            password = gen_md5(password)

        mfa = base64.b32encode(
            bytes(str(shortuuid.uuid() + shortuuid.uuid())[:-9],
                  encoding="utf-8")).decode("utf-8")

        redis_conn = cache_conn()
        configs_init('all')
        config_info = redis_conn.hgetall(const.APP_SETTINGS)
        config_info = convert(config_info)
        obj = SendMail(
            mail_host=config_info.get(const.EMAIL_HOST),
            mail_port=config_info.get(const.EMAIL_PORT),
            mail_user=config_info.get(const.EMAIL_HOST_USER),
            mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
            mail_ssl=True
            if config_info.get(const.EMAIL_USE_SSL) == '1' else False,
            mail_tls=True
            if config_info.get(const.EMAIL_USE_TLS) == '1' else False)

        with DBContext('w', None, True) as session:
            session.add(
                Users(username=username,
                      password=password,
                      nickname=nickname,
                      department=department,
                      tel=tel,
                      wechat=wechat,
                      no=no,
                      email=email,
                      google_key=mfa,
                      superuser='******'))

        obj.send_mail(email,
                      '用户注册成功',
                      '密码为:{} \n MFA:{}'.format(password, mfa),
                      subtype='plain')
        return self.write(
            dict(code=0, msg='恭喜你! 注册成功,赶紧联系管理员给你添加权限吧!!!', mfa=mfa))
Exemple #18
0
def send_alarm():
    with DBContext('r', None, False, **configs) as session:
        error_info = session.query(TaskList).filter(
            TaskList.schedule == 'start', TaskList.status == '4',
            TaskList.start_time < datetime.datetime.now()).all()
        ### 查找出已经发出告警的订单
        old_warm = session.query(TaskMonitor).filter(
            TaskMonitor.call_status == 1).all()

    ### 没有错误订单则返回
    if not error_info:
        return

    old_warm_list = []
    error_list = []

    for o in old_warm:
        old_warm_list.append(o.list_id)

    old_warm_list = list(set(old_warm_list))

    with DBContext('w', None, True, **configs) as session:
        for i in error_info:
            error_list.append(int(i.list_id))
            if int(i.list_id) not in old_warm_list:
                print('The task-{0} is error'.format(i.list_id))
                call_info = 'ID-{} 任务-{} 类型-{}'.format(i.list_id,
                                                       i.task_name[0:25],
                                                       i.task_type[0:25])
                session.add(
                    TaskMonitor(
                        list_id=int(i.list_id),
                        call_info=call_info,
                        call_level=2,
                        call_users=','.join(
                            list(literal_eval(i.associated_user).values())[0]),
                        call_status=0))

        ### 错误记录里面里面的订单已经修复
        for o in old_warm_list:
            if int(o) not in error_list:
                session.query(TaskMonitor).filter(
                    TaskMonitor.list_id == int(o)).delete(
                        synchronize_session=False)

        ### 删除报警记录
        session.query(TaskMonitor).filter(
            TaskMonitor.ctime < time.localtime(time.time() - 6000)).delete(
                synchronize_session=False)
        session.commit()

    time.sleep(1)
    ### 告警
    with DBContext('r', None, False, **configs) as session:
        my_call = session.query(TaskMonitor).filter(
            TaskMonitor.call_status == 0).all()
        ### 如果没有告警信息,则返回
        if not len(my_call):
            return

    redis_conn = cache_conn()
    cache_config_info = redis_conn.hgetall(const.APP_SETTINGS)
    if cache_config_info:
        config_info = convert(cache_config_info)
    else:
        config_info = configs['email_info']

    ### 禁用邮箱
    # sm = SendMail(mail_host=config_info.get(const.EMAIL_HOST), mail_port=config_info.get(const.EMAIL_PORT),
    #               mail_user=config_info.get(const.EMAIL_HOST_USER),
    #               mail_password=config_info.get(const.EMAIL_HOST_PASSWORD),
    #               mail_ssl=True if config_info.get(const.EMAIL_USE_SSL) == '1' else False)

    ### 发送短信实例化
    sms = SendSms(config_info.get(const.SMS_REGION),
                  config_info.get(const.SMS_DOMAIN),
                  config_info.get(const.SMS_PRODUCT_NAME),
                  config_info.get(const.SMS_ACCESS_KEY_ID),
                  config_info.get(const.SMS_ACCESS_KEY_SECRET))
    for i in my_call:
        sms_to_list = []
        email_to_list = []
        for user in i.call_users.split(','):
            info__contact = convert(
                redis_conn.hgetall(bytes(user + '__contact',
                                         encoding='utf-8')))
            if info__contact:
                sms_to_list.append(info__contact['tel'])
                email_to_list.append(info__contact['email'])
        print(sms_to_list, email_to_list, i.call_info)
        ### 发送邮件
        # sm.send_mail(",".join(email_to_list), '自动化订单', i.call_info)

        ### 以下为注释为单独报警的示例,具体根据自己的需求修改
        # import sys
        # sys.path.append(sys.path[0])
        # print(exec_shell('python3 alert.py {} {}'.format(",".join(sms_to_list), i.call_info)))

        ### 发送短信
        if sms_to_list:
            params = {"msg": i.call_info}  # 对应短信模板里设置的参数
            sms.send_sms(phone_numbers=",".join(sms_to_list),
                         template_param=params,
                         sign_name=configs.get('sign_name')[0],
                         template_code=configs.get('template_code')[0])

    ### 发送完禁用
    with DBContext('w', None, True, **configs) as session:
        session.query(TaskMonitor).filter(TaskMonitor.call_status == 0).update(
            {TaskMonitor.call_status: 1})
        session.commit()

    return