Пример #1
0
def set_password(handler, user_id, password):
    db = get_db()

    operator = handler.get_current_user()
    # print('----------', operator)

    # 1. get user info (user name)
    s = SQL(db)
    err = s.reset().select_from('user', ['username', 'surname']).where('user.id={}'.format(user_id)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    name = s.recorder[0]['username']
    surname = s.recorder[0]['surname']
    if len(surname) == 0:
        surname = name

    sql = 'UPDATE `{}user` SET password="******" WHERE id={user_id};' \
          ''.format(db.table_prefix, password=password, user_id=user_id)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    if operator['id'] == 0:
        syslog.sys_log({'username': name, 'surname': surname}, handler.request.remote_ip, TPE_OK,
                       "用户 {} 通过邮件方式重置了密码".format(name))
    else:
        syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "为用户 {} 手动重置了密码".format(name))

    return TPE_OK
Пример #2
0
def update_oath_secret(handler, user_id, oath_secret):
    db = get_db()

    s = SQL(db)
    err = s.select_from('user', ['username', 'surname'], alt_name='u').where(
        'u.id={user_id}'.format(user_id=user_id)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    username = s.recorder[0].username
    surname = s.recorder[0].surname

    sql = 'UPDATE `{dbtp}user` SET oath_secret="{secret}" WHERE id={user_id}' \
          ''.format(dbtp=db.table_prefix, secret=oath_secret, user_id=user_id)
    if db.exec(sql):
        if len(oath_secret) > 0:
            syslog.sys_log({
                'username': username,
                'surname': surname
            }, handler.request.remote_ip, TPE_OK,
                           "用户 {} 更新了身份认证器绑定信息".format(username))
        else:
            syslog.sys_log({
                'username': username,
                'surname': surname
            }, handler.request.remote_ip, TPE_OK,
                           "用户 {} 清除了身份认证器绑定信息".format(username))

        return TPE_OK
    else:
        return TPE_DATABASE
Пример #3
0
def create(handler, gtype, name, desc):
    if gtype not in TP_GROUP_TYPES:
        return TPE_PARAM, 0

    db = get_db()
    _time_now = tp_timestamp_utc_now()

    # 1. 判断是否已经存在了
    sql = 'SELECT id FROM {dbtp}group WHERE type={gtype} AND name="{gname}";'.format(dbtp=db.table_prefix, gtype=gtype, gname=name)
    db_ret = db.query(sql)
    if db_ret is not None and len(db_ret) > 0:
        return TPE_EXISTS, 0

    operator = handler.get_current_user()

    # 2. 插入记录
    sql = 'INSERT INTO `{dbtp}group` (`type`, `name`, `creator_id`, `create_time`, `desc`) VALUES ' \
          '({gtype}, "{gname}", {creator_id}, {create_time}, "{desc}");' \
          ''.format(dbtp=db.table_prefix,
                    gtype=gtype, gname=name, creator_id=operator['id'],
                    create_time=_time_now, desc=desc)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "创建{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype], gname=name))

    return TPE_OK, _id
Пример #4
0
def make_groups(handler, gtype, glist, failed):
    """
    根据传入的组列表,查询每个组的名称对应的id,如果没有,则创建之
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    operator = handler.get_current_user()
    name_list = list()

    for g in glist:
        sql = 'SELECT id FROM {dbtp}group WHERE type={gtype} AND name="{gname}";'.format(dbtp=db.table_prefix, gtype=gtype, gname=g)
        db_ret = db.query(sql)
        if db_ret is None or len(db_ret) == 0:
            # need create group.
            sql = 'INSERT INTO `{dbtp}group` (`type`, `name`, `creator_id`, `create_time`) VALUES ' \
                  '({gtype}, "{name}", {creator_id}, {create_time});' \
                  ''.format(dbtp=db.table_prefix,
                            gtype=gtype, name=g, creator_id=operator['id'], create_time=_time_now)

            db_ret = db.exec(sql)
            if not db_ret:
                failed.append({'line': 0, 'error': '创建{gtype} `{gname}` 失败,写入数据库时发生错误'.format(gtype=TP_GROUP_TYPES[gtype], gname=g)})
                continue

            glist[g] = db.last_insert_id()
            name_list.append(g)

        else:
            glist[g] = db_ret[0][0]

    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "创建{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype], gname=','.join(name_list)))
    return TPE_OK
Пример #5
0
def create(handler, gtype, name, desc):
    if gtype not in TP_GROUP_TYPES:
        return TPE_PARAM, 0

    db = get_db()
    _time_now = tp_timestamp_utc_now()

    # 1. 判断是否已经存在了
    sql = 'SELECT id FROM {dbtp}group WHERE type={gtype} AND name="{gname}";'.format(
        dbtp=db.table_prefix, gtype=gtype, gname=name)
    db_ret = db.query(sql)
    if db_ret is not None and len(db_ret) > 0:
        return TPE_EXISTS, 0

    operator = handler.get_current_user()

    # 2. 插入记录
    sql = 'INSERT INTO `{dbtp}group` (`type`, `name`, `creator_id`, `create_time`, `desc`) VALUES ' \
          '({gtype}, "{gname}", {creator_id}, {create_time}, "{desc}");' \
          ''.format(dbtp=db.table_prefix,
                    gtype=gtype, gname=name, creator_id=operator['id'],
                    create_time=_time_now, desc=desc)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(
        operator, handler.request.remote_ip, TPE_OK,
        "创建{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype], gname=name))

    return TPE_OK, _id
Пример #6
0
def create_users(handler, user_list, success, failed):
    """
    批量创建用户
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    operator = handler.get_current_user()
    name_list = list()

    s = SQL(db)

    for i in range(len(user_list)):
        user = user_list[i]
        if 'type' not in user:
            user['type'] = TP_USER_TYPE_LOCAL
        if 'ldap_dn' not in user:
            user['ldap_dn'] = ''

        err = s.reset().select_from('user', ['id']).where('user.username="******"'.format(user['username'])).query()
        if err != TPE_OK:
            failed.append({'line': user['_line'], 'error': '数据库查询失败'})
        if len(s.recorder) > 0:
            failed.append({'line': user['_line'], 'error': '账号 `{}` 已经存在'.format(user['username'])})
            continue

        if user['type'] == TP_USER_TYPE_LOCAL:
            _password = tp_password_generate_secret(user['password'])
        else:
            _password = ''

        sql = 'INSERT INTO `{}user` (' \
              '`role_id`, `username`, `surname`, `type`, `ldap_dn`, `auth_type`, `password`, ' \
              '`state`, `email`, `creator_id`, `create_time`, `last_login`, `last_chpass`, `desc`' \
              ') VALUES (' \
              '0, "{username}", "{surname}", {user_type}, "{ldap_dn}", 0, "{password}", ' \
              '{state}, "{email}", {creator_id}, {create_time}, {last_login}, {last_chpass}, "{desc}");' \
              ''.format(db.table_prefix, username=user['username'], surname=user['surname'], user_type=user['type'],
                        ldap_dn=user['ldap_dn'], password=_password, state=TP_STATE_NORMAL, email=user['email'],
                        creator_id=operator['id'], create_time=_time_now, last_login=0, last_chpass=_time_now,
                        desc=user['desc'])
        db_ret = db.exec(sql)
        if not db_ret:
            failed.append({'line': user['_line'], 'error': '写入数据库时发生错误'})
            continue

        success.append(user['username'])
        name_list.append(user['username'])
        user['_id'] = db.last_insert_id()

    if len(name_list) > 0:
        syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "批量导入方式创建用户:{}".format(','.join(name_list)))
        # tp_stats().user_counter_change(len(name_list))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)
Пример #7
0
def remove_users(handler, users):
    db = get_db()
    s = SQL(db)

    str_users = ','.join([str(i) for i in users])

    # 1. 获取用户名称,用于记录系统日志
    where = 'u.id IN ({})'.format(str_users)
    err = s.select_from('user', ['username'],
                        alt_name='u').where(where).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    str_names = ','.join([n['username'] for n in s.recorder])

    sql_list = []

    # 将用户从所在组中移除
    sql = 'DELETE FROM `{tpdp}group_map` WHERE type={t} AND mid IN ({ids});' \
          ''.format(tpdp=db.table_prefix, t=TP_GROUP_USER, ids=str_users)
    sql_list.append(sql)
    # 删除用户
    sql = 'DELETE FROM `{tpdp}user` WHERE id IN ({ids});'.format(
        tpdp=db.table_prefix, ids=str_users)
    sql_list.append(sql)
    # 将用户从运维授权中移除
    sql = 'DELETE FROM `{}ops_auz` WHERE rtype={rtype} AND rid IN ({ids});' \
          ''.format(db.table_prefix, rtype=TP_USER, ids=str_users)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}ops_map` WHERE u_id IN ({ids});'.format(
        db.table_prefix, ids=str_users)
    sql_list.append(sql)
    # 将用户从审计授权中移除
    sql = 'DELETE FROM `{}audit_auz` WHERE rtype={rtype} AND rid IN ({ids});' \
          ''.format(db.table_prefix, rtype=TP_USER, ids=str_users)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}audit_map` WHERE u_id IN ({ids});'.format(
        db.table_prefix, ids=str_users)
    sql_list.append(sql)

    if not db.transaction(sql_list):
        return TPE_DATABASE

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip,
                   TPE_OK, "删除用户:{}".format(str_names))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)

    return TPE_OK
Пример #8
0
def create_user(handler, user):
    """
    创建一个用户账号
    """
    db = get_db()
    _time_now = tp_timestamp_sec()
    operator = handler.get_current_user()

    if 'type' not in user:
        user['type'] = TP_USER_TYPE_LOCAL
    if 'ldap_dn' not in user:
        user['ldap_dn'] = ''

    # 1. 判断此账号是否已经存在了
    s = SQL(db)
    err = s.reset().select_from('user', ['id']).where(
        'user.username="******"'.format(user['username'])).query()
    if err != TPE_OK:
        return err, 0
    if len(s.recorder) > 0:
        return TPE_EXISTS, 0

    # _password = tp_password_generate_secret(user['password'])
    if user['type'] == TP_USER_TYPE_LOCAL:
        _password = tp_password_generate_secret(user['password'])
    else:
        _password = ''

    sql = 'INSERT INTO `{}user` (' \
          '`role_id`, `username`, `surname`, `type`, `ldap_dn`, `auth_type`, `password`, `state`, ' \
          '`email`, `creator_id`, `create_time`, `last_login`, `last_chpass`, `valid_from`, `valid_to`, `desc`' \
          ') VALUES (' \
          '{role}, "{username}", "{surname}", {user_type}, "{ldap_dn}", {auth_type}, "{password}", {state}, ' \
          '"{email}", {creator_id}, {create_time}, {last_login}, {last_chpass}, {valid_from}, '\
          '{valid_to}, "{desc}");' \
          ''.format(db.table_prefix, role=user['role'], username=user['username'], surname=user['surname'],
                    user_type=user['type'], ldap_dn=user['ldap_dn'], auth_type=user['auth_type'], password=_password,
                    state=TP_STATE_NORMAL, email=user['email'], creator_id=operator['id'], create_time=_time_now,
                    last_login=0, last_chpass=_time_now, valid_from=user['valid_from'], valid_to=user['valid_to'], desc=user['desc'])
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                   "创建用户:{}".format(user['username']))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)

    return TPE_OK, _id
Пример #9
0
def rank_reorder(handler, pid, new_rank, start_rank, end_rank, direct):
    db = get_db()

    # 调节顺序:
    # 由pid获取被移动的策略,得到其rank,即,p_rank
    #  p_rank > new_rank,向前移动
    #    所有 new_rank <= rank < p_rank 的条目,其rank+1
    #  p_rank < new_rank,向后移动
    #    所有 new_rank >= rank > p_rank 的条目,其rank-1
    # 最后令pid条目的rank为new_rank

    # 1. 判断此账号是否已经存在
    s = SQL(db)
    err = s.select_from('ops_policy', ['id', 'name', 'rank']).where(
        'ops_policy.id={}'.format(pid)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    p_name = s.recorder[0]['name']
    p_rank = s.recorder[0]['rank']

    # if p_rank > new_rank:
    #     compare = '>'
    #     if insert_before:
    #         compare = '>='
    #     sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank+1 WHERE (rank{compare}{new_rank} AND rank<{p_rank});' \
    #           ''.format(dbtp=db.table_prefix, compare=compare, new_rank=new_rank, p_rank=p_rank)
    # else:
    #     compare = '<'
    #     if insert_before:
    #         compare = '<='
    #     sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank-1 WHERE (rank{compare}{new_rank} AND rank>{p_rank});' \
    #           ''.format(dbtp=db.table_prefix, compare=compare, new_rank=new_rank, p_rank=p_rank)
    sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank{direct} WHERE (rank>={start_rank} AND rank<={end_rank});' \
          ''.format(dbtp=db.table_prefix, direct=direct, start_rank=start_rank, end_rank=end_rank)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    sql = 'UPDATE `{dbtp}ops_policy` SET rank={new_rank} WHERE id={pid};' \
          ''.format(dbtp=db.table_prefix, new_rank=new_rank, pid=pid)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip,
                   TPE_OK,
                   "调整运维授权策略顺序:{},从{}到{}".format(p_name, p_rank, new_rank))

    return policy.rebuild_ops_auz_map()
Пример #10
0
def create_user(handler, user):
    """
    创建一个用户账号
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()
    operator = handler.get_current_user()

    if 'type' not in user:
        user['type'] = TP_USER_TYPE_LOCAL
    if 'ldap_dn' not in user:
        user['ldap_dn'] = ''

    # 1. 判断此账号是否已经存在了
    s = SQL(db)
    err = s.reset().select_from('user', ['id']).where('user.username="******"'.format(user['username'])).query()
    if err != TPE_OK:
        return err, 0
    if len(s.recorder) > 0:
        return TPE_EXISTS, 0

    # _password = tp_password_generate_secret(user['password'])
    if user['type'] == TP_USER_TYPE_LOCAL:
        _password = tp_password_generate_secret(user['password'])
    else:
        _password = ''

    sql = 'INSERT INTO `{}user` (' \
          '`role_id`, `username`, `surname`, `type`, `ldap_dn`, `auth_type`, `password`, `state`, ' \
          '`email`, `creator_id`, `create_time`, `last_login`, `last_chpass`, `desc`' \
          ') VALUES (' \
          '{role}, "{username}", "{surname}", {user_type}, "{ldap_dn}", {auth_type}, "{password}", {state}, ' \
          '"{email}", {creator_id}, {create_time}, {last_login}, {last_chpass}, "{desc}");' \
          ''.format(db.table_prefix, role=user['role'], username=user['username'], surname=user['surname'],
                    user_type=user['type'], ldap_dn=user['ldap_dn'], auth_type=user['auth_type'], password=_password,
                    state=TP_STATE_NORMAL, email=user['email'], creator_id=operator['id'], create_time=_time_now,
                    last_login=0, last_chpass=_time_now, desc=user['desc'])
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "创建用户:{}".format(user['username']))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)

    return TPE_OK, _id
Пример #11
0
def create_users(handler, user_list, success, failed):
    """
    批量创建用户
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    operator = handler.get_current_user()
    name_list = list()

    s = SQL(db)

    for i in range(len(user_list)):
        user = user_list[i]

        err = s.reset().select_from('user', ['id']).where(
            'user.username="******"'.format(user['username'])).query()
        if err != TPE_OK:
            failed.append({'line': user['_line'], 'error': '数据库查询失败'})
        if len(s.recorder) > 0:
            failed.append({
                'line': user['_line'],
                'error': '账号 `{}` 已经存在'.format(user['username'])
            })
            continue

        _password = tp_password_generate_secret(user['password'])

        sql = 'INSERT INTO `{}user` (`type`, `auth_type`, `password`, `username`, `surname`, `role_id`, `state`, `email`, `creator_id`, `create_time`, `last_login`, `last_chpass`, `desc`) VALUES ' \
              '(1, 0, "{password}", "{username}", "{surname}", 0, {state}, "{email}", {creator_id}, {create_time}, {last_login}, {last_chpass}, "{desc}");' \
              ''.format(db.table_prefix,
                        username=user['username'], surname=user['surname'], password=_password, state=TP_STATE_NORMAL, email=user['email'],
                        creator_id=operator['id'], create_time=_time_now, last_login=0, last_chpass=0, desc=user['desc'])
        db_ret = db.exec(sql)
        if not db_ret:
            failed.append({'line': user['_line'], 'error': '写入数据库时发生错误'})
            continue

        success.append(user['username'])
        name_list.append(user['username'])
        user['_id'] = db.last_insert_id()

    if len(name_list) > 0:
        syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                       "批量导入方式创建用户:{}".format(','.join(name_list)))
        # tp_stats().user_counter_change(len(name_list))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)
Пример #12
0
def rank_reorder(handler, pid, new_rank, start_rank, end_rank, direct):
    db = get_db()

    # 调节顺序:
    # 由pid获取被移动的策略,得到其rank,即,p_rank
    #  p_rank > new_rank,向前移动
    #    所有 new_rank <= rank < p_rank 的条目,其rank+1
    #  p_rank < new_rank,向后移动
    #    所有 new_rank >= rank > p_rank 的条目,其rank-1
    # 最后令pid条目的rank为new_rank

    # 1. 判断此账号是否已经存在
    s = SQL(db)
    err = s.select_from('ops_policy', ['id', 'name', 'rank']).where('ops_policy.id={}'.format(pid)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    p_name = s.recorder[0]['name']
    p_rank = s.recorder[0]['rank']

    # if p_rank > new_rank:
    #     compare = '>'
    #     if insert_before:
    #         compare = '>='
    #     sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank+1 WHERE (rank{compare}{new_rank} AND rank<{p_rank});' \
    #           ''.format(dbtp=db.table_prefix, compare=compare, new_rank=new_rank, p_rank=p_rank)
    # else:
    #     compare = '<'
    #     if insert_before:
    #         compare = '<='
    #     sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank-1 WHERE (rank{compare}{new_rank} AND rank>{p_rank});' \
    #           ''.format(dbtp=db.table_prefix, compare=compare, new_rank=new_rank, p_rank=p_rank)
    sql = 'UPDATE `{dbtp}ops_policy` SET rank=rank{direct} WHERE (rank>={start_rank} AND rank<={end_rank});' \
          ''.format(dbtp=db.table_prefix, direct=direct, start_rank=start_rank, end_rank=end_rank)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    sql = 'UPDATE `{dbtp}ops_policy` SET rank={new_rank} WHERE id={pid};' \
          ''.format(dbtp=db.table_prefix, new_rank=new_rank, pid=pid)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip, TPE_OK, "调整运维授权策略顺序:{},从{}到{}".format(p_name, p_rank, new_rank))

    return policy.rebuild_ops_auz_map()
Пример #13
0
def remove_users(handler, users):
    db = get_db()
    s = SQL(db)

    str_users = ','.join([str(i) for i in users])

    # 1. 获取用户名称,用于记录系统日志
    where = 'u.id IN ({})'.format(str_users)
    err = s.select_from('user', ['username'], alt_name='u').where(where).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    str_names = ','.join([n['username'] for n in s.recorder])

    sql_list = []

    # 将用户从所在组中移除
    sql = 'DELETE FROM `{tpdp}group_map` WHERE type={t} AND mid IN ({ids});' \
          ''.format(tpdp=db.table_prefix, t=TP_GROUP_USER, ids=str_users)
    sql_list.append(sql)
    # 删除用户
    sql = 'DELETE FROM `{tpdp}user` WHERE id IN ({ids});'.format(tpdp=db.table_prefix, ids=str_users)
    sql_list.append(sql)
    # 将用户从运维授权中移除
    sql = 'DELETE FROM `{}ops_auz` WHERE rtype={rtype} AND rid IN ({ids});' \
          ''.format(db.table_prefix, rtype=TP_USER, ids=str_users)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}ops_map` WHERE u_id IN ({ids});'.format(db.table_prefix, ids=str_users)
    sql_list.append(sql)
    # 将用户从审计授权中移除
    sql = 'DELETE FROM `{}audit_auz` WHERE rtype={rtype} AND rid IN ({ids});' \
          ''.format(db.table_prefix, rtype=TP_USER, ids=str_users)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}audit_map` WHERE u_id IN ({ids});'.format(db.table_prefix, ids=str_users)
    sql_list.append(sql)

    if not db.transaction(sql_list):
        return TPE_DATABASE

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip, TPE_OK, "删除用户:{}".format(str_names))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)

    return TPE_OK
Пример #14
0
def make_groups(handler, gtype, glist, failed):
    """
    根据传入的组列表,查询每个组的名称对应的id,如果没有,则创建之
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    operator = handler.get_current_user()
    name_list = list()

    for g in glist:
        sql = 'SELECT id FROM {dbtp}group WHERE type={gtype} AND name="{gname}";'.format(
            dbtp=db.table_prefix, gtype=gtype, gname=g)
        db_ret = db.query(sql)
        if db_ret is None or len(db_ret) == 0:
            # need create group.
            sql = 'INSERT INTO `{dbtp}group` (`type`, `name`, `creator_id`, `create_time`) VALUES ' \
                  '({gtype}, "{name}", {creator_id}, {create_time});' \
                  ''.format(dbtp=db.table_prefix,
                            gtype=gtype, name=g, creator_id=operator['id'], create_time=_time_now)

            db_ret = db.exec(sql)
            if not db_ret:
                failed.append({
                    'line':
                    0,
                    'error':
                    '创建{gtype} `{gname}` 失败,写入数据库时发生错误'.format(
                        gtype=TP_GROUP_TYPES[gtype], gname=g)
                })
                continue

            glist[g] = db.last_insert_id()
            name_list.append(g)

        else:
            glist[g] = db_ret[0][0]

    syslog.sys_log(
        operator, handler.request.remote_ip, TPE_OK,
        "创建{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype],
                                   gname=','.join(name_list)))
    return TPE_OK
Пример #15
0
def create_user(handler, args):
    """
    创建一个用户账号
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()
    operator = handler.get_current_user()

    # 1. 判断此账号是否已经存在了
    s = SQL(db)
    err = s.reset().select_from('user', ['id']).where(
        'user.username="******"'.format(args['username'])).query()
    if err != TPE_OK:
        return err, 0
    if len(s.recorder) > 0:
        return TPE_EXISTS, 0

    _password = tp_password_generate_secret(args['password'])

    sql = 'INSERT INTO `{}user` (`type`, `auth_type`, `password`, `username`, `surname`, `role_id`, `state`, `email`, `creator_id`, `create_time`, `last_login`, `last_chpass`, `desc`) VALUES ' \
          '(1, {auth_type}, "{password}", "{username}", "{surname}", {role}, {state}, "{email}", {creator_id}, {create_time}, {last_login}, {last_chpass}, "{desc}");' \
          ''.format(db.table_prefix, auth_type=args['auth_type'], password=_password,
                    username=args['username'], surname=args['surname'], role=args['role'], state=TP_STATE_NORMAL, email=args['email'],
                    creator_id=operator['id'],
                    create_time=_time_now, last_login=0, last_chpass=0, desc=args['desc'])
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                   "创建用户:{}".format(args['username']))

    # calc count of users.
    err, cnt = s.reset().count('user')
    if err == TPE_OK:
        tp_stats().user_counter_change(cnt)

    return TPE_OK, _id
Пример #16
0
def create_policy(handler, args):
    """
    创建一个授权策略
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    # 1. 判断此账号是否已经存在了
    s = SQL(db)
    err = s.reset().select_from('audit_policy', ['id']).where(
        'audit_policy.name="{}"'.format(args['name'])).query()
    if err != TPE_OK:
        return err, 0
    if len(s.recorder) > 0:
        return TPE_EXISTS, 0

    # 2. get total count
    sql = 'SELECT COUNT(*) FROM {}audit_policy'.format(db.table_prefix)
    db_ret = db.query(sql)
    if not db_ret or len(db_ret) == 0:
        return TPE_DATABASE, 0
    rank = db_ret[0][0] + 1

    sql = 'INSERT INTO `{}audit_policy` (`rank`, `name`, `desc`, `creator_id`, `create_time`) VALUES ' \
          '({rank}, "{name}", "{desc}", {creator_id}, {create_time});' \
          ''.format(db.table_prefix,
                    rank=rank, name=args['name'], desc=args['desc'],
                    creator_id=handler.get_current_user()['id'],
                    create_time=_time_now)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip,
                   TPE_OK, "创建审计授权策略:{}".format(args['name']))

    return TPE_OK, _id
Пример #17
0
def update_oath_secret(handler, user_id, oath_secret):
    db = get_db()

    s = SQL(db)
    err = s.select_from('user', ['username', 'surname'], alt_name='u').where(
        'u.id={user_id}'.format(user_id=user_id)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    username = s.recorder[0].username
    surname = s.recorder[0].surname

    sql = 'UPDATE `{dbtp}user` SET oath_secret="{secret}" WHERE id={user_id}' \
          ''.format(dbtp=db.table_prefix, secret=oath_secret, user_id=user_id)
    if db.exec(sql):
        syslog.sys_log({'username': username, 'surname': surname}, handler.request.remote_ip, TPE_OK,
                       "用户 {} 绑定了身份认证器".format(username))
        return TPE_OK
    else:
        return TPE_DATABASE
Пример #18
0
def create_policy(handler, args):
    """
    创建一个授权策略
    """
    db = get_db()
    _time_now = tp_timestamp_utc_now()

    # 1. 判断此账号是否已经存在了
    s = SQL(db)
    err = s.reset().select_from('ops_policy', ['id']).where('ops_policy.name="{}"'.format(args['name'])).query()
    if err != TPE_OK:
        return err, 0
    if len(s.recorder) > 0:
        return TPE_EXISTS, 0

    # 2. get total count
    sql = 'SELECT COUNT(*) FROM {}ops_policy'.format(db.table_prefix)
    db_ret = db.query(sql)
    if not db_ret or len(db_ret) == 0:
        return TPE_DATABASE, 0
    rank = db_ret[0][0] + 1

    sql = 'INSERT INTO `{}ops_policy` (`rank`, `name`, `desc`, `creator_id`, `create_time`) VALUES ' \
          '({rank}, "{name}", "{desc}", {creator_id}, {create_time});' \
          ''.format(db.table_prefix,
                    rank=rank, name=args['name'], desc=args['desc'],
                    creator_id=handler.get_current_user()['id'],
                    create_time=_time_now)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE, 0

    _id = db.last_insert_id()

    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip, TPE_OK, "创建运维授权策略:{}".format(args['name']))

    return TPE_OK, _id
Пример #19
0
def set_password(handler, user_id, password):
    db = get_db()

    operator = handler.get_current_user()
    # print('----------', operator)

    # 1. get user info (user name)
    s = SQL(db)
    err = s.reset().select_from('user', ['username', 'surname']).where(
        'user.id={}'.format(user_id)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    name = s.recorder[0]['username']
    surname = s.recorder[0]['surname']
    if len(surname) == 0:
        surname = name

    sql = 'UPDATE `{}user` SET password="******" WHERE id={user_id};' \
          ''.format(db.table_prefix, password=password, user_id=user_id)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    if operator['id'] == 0:
        syslog.sys_log({
            'username': name,
            'surname': surname
        }, handler.request.remote_ip, TPE_OK, "用户 {} 通过邮件方式重置了密码".format(name))
    else:
        syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                       "为用户 {} 手动重置了密码".format(name))

    return TPE_OK
Пример #20
0
def set_password(handler, mode, user_id, password):
    db = get_db()

    operator = handler.get_current_user()
    # print('----------', operator)

    # 1. get user info (user name)
    s = SQL(db)
    err = s.reset().select_from('user', ['username', 'surname']).where(
        'user.id={}'.format(user_id)).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    name = s.recorder[0]['username']
    surname = s.recorder[0]['surname']
    if len(surname) == 0:
        surname = name

    _time_now = tp_timestamp_sec()

    sql = 'UPDATE `{}user` SET `password`="{password}", `last_chpass`={last_chpass} WHERE `id`={user_id};' \
          ''.format(db.table_prefix, password=password, last_chpass=_time_now, user_id=user_id)
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    if mode in [3, 4, 5, 6]:
        if mode == 6:
            syslog.sys_log({
                'username': name,
                'surname': surname
            }, handler.request.remote_ip, TPE_OK,
                           "用户 {} 修改了过期的密码".format(name))
        else:
            syslog.sys_log({
                'username': name,
                'surname': surname
            }, handler.request.remote_ip, TPE_OK,
                           "用户 {} 通过邮件方式重置了密码".format(name))
    else:
        syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                       "为用户 {} 手动重置了密码".format(name))

    return TPE_OK
Пример #21
0
def login(handler, username, password=None, oath_code=None, check_bind_oath=False):
    sys_cfg = tp_cfg().sys

    err, user_info = get_by_username(username)
    if err != TPE_OK:
        # if err == TPE_NOT_EXISTS:
        #     syslog.sys_log({'username': username, 'surname': username}, handler.request.remote_ip, TPE_NOT_EXISTS,
        #                    '用户身份验证失败,用户`{}`不存在'.format(username))
        return err, None

    if user_info.privilege == 0:
        # 尚未为此用户设置角色
        return TPE_PRIVILEGE, None

    if check_bind_oath and len(user_info['oath_secret']) != 0:
        return TPE_OATH_ALREADY_BIND, None

    if user_info['state'] == TP_STATE_LOCKED:
        # 用户已经被锁定,如果系统配置为一定时间后自动解锁,则更新一下用户信息
        if sys_cfg.login.lock_timeout != 0:
            if tp_timestamp_utc_now() - user_info.lock_time > sys_cfg.login.lock_timeout * 60:
                user_info.fail_count = 0
                user_info.state = TP_STATE_NORMAL
        if user_info['state'] == TP_STATE_LOCKED:
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_LOCKED, '登录失败,用户已被临时锁定')
            return TPE_USER_LOCKED, None
    elif user_info['state'] == TP_STATE_DISABLED:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_DISABLED, '登录失败,用户已被禁用')
        return TPE_USER_DISABLED, None
    elif user_info['state'] != TP_STATE_NORMAL:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_FAILED, '登录失败,用户状态异常')
        return TPE_FAILED, None

    err_msg = ''
    if password is not None:
        if user_info['type'] == TP_USER_TYPE_LOCAL:
            # 如果系统配置了密码有效期,则检查用户的密码是否失效
            if sys_cfg.password.timeout != 0:
                _time_now = tp_timestamp_utc_now()
                if user_info['last_chpass'] + (sys_cfg.password.timeout * 60 * 60 * 24) < _time_now:
                    syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, '登录失败,用户密码已过期')
                    return TPE_USER_AUTH, None

            if not tp_password_verify(password, user_info['password']):
                err, is_locked = update_fail_count(handler, user_info)
                if is_locked:
                    err_msg = ',用户已被临时锁定'
                syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, '登录失败,密码错误{}'.format(err_msg))
                return TPE_USER_AUTH, None
        elif user_info['type'] == TP_USER_TYPE_LDAP:
            try:
                if len(tp_cfg().sys_ldap_password) == 0:
                    syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, 'LDAP未能正确配置,需要管理员密码')
                    return TPE_USER_AUTH, None
                else:
                    _ldap_password = tp_cfg().sys_ldap_password
                _ldap_server = tp_cfg().sys.ldap.server
                _ldap_port = tp_cfg().sys.ldap.port
                _ldap_base_dn = tp_cfg().sys.ldap.base_dn
            except:
                syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, 'LDAP未能正确配置')
                return TPE_USER_AUTH, None

            try:
                ldap = Ldap(_ldap_server, _ldap_port, _ldap_base_dn)
                ret, err_msg = ldap.valid_user(user_info['ldap_dn'], password)
                if ret != TPE_OK:
                    if ret == TPE_USER_AUTH:
                        err, is_locked = update_fail_count(handler, user_info)
                        if is_locked:
                            err_msg = ',用户已被临时锁定'
                        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH,
                                       'LDAP用户登录失败,密码错误{}'.format(err_msg))
                        return TPE_USER_AUTH, None
                    else:
                        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH,
                                       'LDAP用户登录失败,{}'.format(err_msg))
                        return TPE_USER_AUTH, None
            except:
                syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, 'LDAP用户登录失败,发生内部错误')
                return TPE_USER_AUTH, None

        else:
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH, '登录失败,系统内部错误')
            return TPE_USER_AUTH, None

    if oath_code is not None:
        # use oath
        if len(user_info['oath_secret']) == 0:
            return TPE_OATH_MISMATCH, None

        if not tp_oath_verify_code(user_info['oath_secret'], oath_code):
            err, is_locked = update_fail_count(handler, user_info)
            if is_locked:
                err_msg = ',用户已被临时锁定!'
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_OATH_MISMATCH,
                           "登录失败,身份验证器动态验证码错误{}".format(err_msg))
            return TPE_OATH_MISMATCH, None

    del user_info['password']
    del user_info['oath_secret']

    if len(user_info['surname']) == 0:
        user_info['surname'] = user_info['username']
    return TPE_OK, user_info
Пример #22
0
def remove(handler, gtype, glist):
    if gtype not in TP_GROUP_TYPES:
        return TPE_PARAM

    group_ids = ','.join([str(i) for i in glist])

    # 1. 获取组的名称,用于记录系统日志
    where = 'g.type={gtype} AND g.id IN ({gids})'.format(gtype=gtype, gids=group_ids)

    db = get_db()
    s = SQL(db)
    err = s.select_from('group', ['name'], alt_name='g').where(where).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    name_list = [n['name'] for n in s.recorder]

    sql_list = []

    # 删除组与成员的映射关系
    sql = 'DELETE FROM `{tpdp}group_map` WHERE `type`={t} AND `gid` IN ({ids});'.format(tpdp=db.table_prefix, t=gtype, ids=group_ids)
    sql_list.append(sql)

    # where = 'type={} AND gid IN ({})'.format(gtype, ','.join(group_list))
    # err = s.reset().delete_from('group_map').where(where).exec()
    # if err != TPE_OK:
    #     return err

    # 删除组
    sql = 'DELETE FROM `{tpdp}group` WHERE `type`={t} AND `id` IN ({ids});'.format(tpdp=db.table_prefix, t=gtype, ids=group_ids)
    sql_list.append(sql)
    # where = 'type={gtype} AND id IN ({gids})'.format(gtype=gtype, gids=','.join(group_list))
    # err = s.reset().delete_from('group').where(where).exec()
    # if err != TPE_OK:
    #     return err

    if gtype == TP_GROUP_USER:
        gname = 'gu'
    elif gtype == TP_GROUP_HOST:
        gname = 'gh'
    elif gtype == TP_GROUP_ACCOUNT:
        gname = 'ga'
    else:
        return TPE_PARAM

    # 将组从运维授权中移除
    sql = 'DELETE FROM `{}ops_auz` WHERE `rtype`={rtype} AND `rid` IN ({ids});'.format(db.table_prefix, rtype=gtype, ids=group_ids)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}ops_map` WHERE `{gname}_id` IN ({ids});'.format(db.table_prefix, gname=gname, ids=group_ids)
    sql_list.append(sql)
    # 将组从审计授权中移除
    sql = 'DELETE FROM `{}audit_auz` WHERE `rtype`={rtype} AND `rid` IN ({ids});'.format(db.table_prefix, rtype=gtype, ids=group_ids)
    sql_list.append(sql)
    # 注意,审计授权映射表中,没有远程账号相关信息,所以如果是远程账号组,则忽略
    if gtype != TP_GROUP_ACCOUNT:
        sql = 'DELETE FROM `{}audit_map` WHERE `{gname}_id` IN ({ids});'.format(db.table_prefix, gname=gname, ids=group_ids)
        sql_list.append(sql)

    if not db.transaction(sql_list):
        return TPE_DATABASE

    # 记录系统日志
    syslog.sys_log(handler.get_current_user(), handler.request.remote_ip, TPE_OK, "删除{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype], gname=','.join(name_list)))

    return TPE_OK
Пример #23
0
    def post(self):
        sys_cfg = tp_cfg().sys

        args = self.get_argument('args', None)
        if args is None:
            return self.write_json(TPE_PARAM)

        try:
            args = json.loads(args)
        except:
            return self.write_json(TPE_JSON_FORMAT, '参数错误')

        try:
            login_type = args['type']
            captcha = args['captcha'].strip()
            username = args['username'].strip().lower()
            password = args['password']
            oath = args['oath'].strip()
            remember = args['remember']
        except:
            return self.write_json(TPE_PARAM)

        if login_type not in [TP_LOGIN_AUTH_USERNAME_PASSWORD,
                              TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                              TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                              TP_LOGIN_AUTH_USERNAME_OATH
                              ]:
            return self.write_json(TPE_PARAM, '未知的认证方式')

        if login_type == TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA:
            oath = None
            code = self.get_session('captcha')
            if code is None:
                return self.write_json(TPE_CAPTCHA_EXPIRED, '验证码已失效')
            if code.lower() != captcha.lower():
                return self.write_json(TPE_CAPTCHA_MISMATCH, '验证码错误')
        elif login_type in [TP_LOGIN_AUTH_USERNAME_OATH, TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH]:
            if len(oath) == 0:
                return self.write_json(TPE_OATH_MISMATCH, '未提供身份验证器动态验证码')

        self.del_session('captcha')

        if len(username) == 0:
            return self.write_json(TPE_PARAM, '未提供登录用户名')

        if login_type not in [TP_LOGIN_AUTH_USERNAME_PASSWORD,
                              TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                              TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH
                              ]:
            password = None
        if login_type not in [TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                              TP_LOGIN_AUTH_USERNAME_OATH
                              ]:
            oath = None

        # 检查用户名合法性,防止SQL注入攻击
        if '<' in username or '>' in username:
            username = username.replace('<', '&lt;')
            username = username.replace('>', '&gt;')
            err = TPE_USER_AUTH
            syslog.sys_log({'username': '******', 'surname': '???'}, self.request.remote_ip, TPE_NOT_EXISTS, '登录失败,可能是攻击行为。试图使用用户名 {} 进行登录。'.format(username))
            return self.write_json(err)

        err, user_info = user.login(self, username, password=password, oath_code=oath)
        if err != TPE_OK:
            if err == TPE_NOT_EXISTS:
                err = TPE_USER_AUTH
                syslog.sys_log({'username': '******', 'surname': '???'}, self.request.remote_ip, TPE_NOT_EXISTS, '登录失败,用户`{}`不存在'.format(username))
            return self.write_json(err)

        # 判断此用户是否被允许使用当前登录认证方式
        auth_type = user_info.auth_type
        if auth_type == 0:
            auth_type = sys_cfg.login.auth

        if (auth_type & login_type) != login_type:
            return self.write_json(TPE_USER_AUTH, '不允许使用此身份认证方式')

        self._user = user_info
        self._user['_is_login'] = True
        # del self._user['password']
        # del self._user['oath_secret']

        if remember:
            self.set_session('user', self._user, 12 * 60 * 60)
        else:
            self.set_session('user', self._user)

        user.update_login_info(self, user_info['id'])

        # 记录登录日志
        syslog.sys_log(self._user, self.request.remote_ip, TPE_OK, "登录成功")

        self.set_cookie('username', username)

        return self.write_json(TPE_OK)
Пример #24
0
def login(handler,
          username,
          password=None,
          oath_code=None,
          check_bind_oath=False):
    sys_cfg = tp_cfg().sys

    err, user_info = get_by_username(username)
    if err != TPE_OK:
        # if err == TPE_NOT_EXISTS:
        #     syslog.sys_log({'username': username, 'surname': username}, handler.request.remote_ip, TPE_NOT_EXISTS, '用户身份验证失败,用户`{}`不存在'.format(username))
        return err, None

    if user_info.privilege == 0:
        # 尚未为此用户设置角色
        return TPE_PRIVILEGE, None

    if check_bind_oath == True and len(user_info['oath_secret']) != 0:
        return TPE_OATH_ALREADY_BIND, None

    if user_info['state'] == TP_STATE_LOCKED:
        # 用户已经被锁定,如果系统配置为一定时间后自动解锁,则更新一下用户信息
        if sys_cfg.login.lock_timeout != 0:
            if tp_timestamp_utc_now(
            ) - user_info.lock_time > sys_cfg.login.lock_timeout * 60:
                user_info.fail_count = 0
                user_info.state = TP_STATE_NORMAL
        if user_info['state'] == TP_STATE_LOCKED:
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_USER_LOCKED, '登录失败,用户已被临时锁定')
            return TPE_USER_LOCKED, None
    elif user_info['state'] == TP_STATE_DISABLED:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_DISABLED,
                       '登录失败,用户已被禁用')
        return TPE_USER_DISABLED, None
    elif user_info['state'] != TP_STATE_NORMAL:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_FAILED,
                       '登录失败,用户状态异常')
        return TPE_FAILED, None

    err_msg = ''
    if password is not None:
        # 如果系统配置了密码有效期,则检查用户的密码是否失效
        if sys_cfg.password.timeout != 0:
            pass

        if not tp_password_verify(password, user_info['password']):
            err, is_locked = update_fail_count(handler, user_info)
            if is_locked:
                err_msg = ',用户已被临时锁定'
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH,
                           '登录失败,密码错误{}'.format(err_msg))
            return TPE_USER_AUTH, None

    if oath_code is not None:
        # use oath
        if len(user_info['oath_secret']) == 0:
            return TPE_OATH_MISMATCH, None

        if not tp_oath_verify_code(user_info['oath_secret'], oath_code):
            err, is_locked = update_fail_count(handler, user_info)
            if is_locked:
                err_msg = ',用户已被临时锁定!'
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_OATH_MISMATCH,
                           "登录失败,身份验证器动态验证码错误{}".format(err_msg))
            return TPE_OATH_MISMATCH, None

    del user_info['password']
    del user_info['oath_secret']

    if len(user_info['surname']) == 0:
        user_info['surname'] = user_info['username']
    return TPE_OK, user_info
Пример #25
0
def login(handler,
          username,
          password=None,
          oath_code=None,
          check_bind_oath=False):
    sys_cfg = tp_cfg().sys
    msg = ''
    current_unix_time = int(time.mktime(datetime.datetime.now().timetuple()))
    #    log.e('current:',current_unix_time,'validfrom:', user_info['valid_from'])

    err, user_info = get_by_username(username)
    if err != TPE_OK:
        return err, None, msg

    if user_info.privilege == 0:
        # 尚未为此用户设置角色
        msg = '登录失败,用户尚未分配权限'
        return TPE_PRIVILEGE, None, msg

    if check_bind_oath and len(user_info['oath_secret']) != 0:
        return TPE_OATH_ALREADY_BIND, None, msg

    if user_info['state'] == TP_STATE_LOCKED:
        # 用户已经被锁定,如果系统配置为一定时间后自动解锁,则更新一下用户信息
        if sys_cfg.login.lock_timeout != 0:
            if tp_timestamp_sec(
            ) - user_info.lock_time > sys_cfg.login.lock_timeout * 60:
                user_info.fail_count = 0
                user_info.state = TP_STATE_NORMAL
        if user_info['state'] == TP_STATE_LOCKED:
            msg = '登录失败,用户已被临时锁定'
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_USER_LOCKED, msg)
            return TPE_USER_LOCKED, None, msg
    elif user_info['state'] == TP_STATE_DISABLED:
        msg = '登录失败,用户已被禁用'
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_DISABLED,
                       msg)
        return TPE_USER_DISABLED, None, msg
    elif user_info['state'] != TP_STATE_NORMAL:
        msg = '登录失败,用户状态异常'
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_FAILED, msg)
        return TPE_FAILED, None, msg
    elif current_unix_time < user_info['valid_from'] or (
            current_unix_time > user_info['valid_to']
            and user_info['valid_to'] != 0):
        msg = '登录失败,用户已过期'
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_FAILED, msg)
        return TPE_FAILED, None, msg

    err_msg = ''
    if password is not None:
        if user_info['type'] == TpUserType.LOCAL:
            # 如果系统配置了密码有效期,则检查用户的密码是否失效
            if sys_cfg.password.timeout != 0:
                _time_now = tp_timestamp_sec()
                if user_info['last_chpass'] + (sys_cfg.password.timeout * 60 *
                                               60 * 24) < _time_now:
                    msg = '登录失败,用户密码已过期'
                    syslog.sys_log(user_info, handler.request.remote_ip,
                                   TPE_USER_AUTH, msg)
                    return TPE_EXPIRED, None, msg

            if not tp_password_verify(password, user_info['password']):
                err, is_locked = update_fail_count(handler, user_info)
                if is_locked:
                    err_msg = ',用户已被临时锁定'
                msg = '登录失败,密码错误{}'.format(err_msg)
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, msg)
                return TPE_USER_AUTH, None, msg
        elif user_info['type'] == TP_USER_TYPE_LDAP:
            try:
                if len(tp_cfg().sys_ldap_password) == 0:
                    msg = 'LDAP尚未配置'
                    syslog.sys_log(user_info, handler.request.remote_ip,
                                   TPE_USER_AUTH, msg)
                    return TPE_USER_AUTH, None, msg
                else:
                    _ldap_password = tp_cfg().sys_ldap_password
                _ldap_server = tp_cfg().sys.ldap.server
                _ldap_port = tp_cfg().sys.ldap.port
                _ldap_base_dn = tp_cfg().sys.ldap.base_dn
            except:
                msg = 'LDAP尚未正确配置'
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, msg)
                return TPE_USER_AUTH, None, msg

            try:
                ldap = Ldap(_ldap_server, _ldap_port, _ldap_base_dn)
                ret, err_msg = ldap.valid_user(user_info['ldap_dn'], password)
                if ret != TPE_OK:
                    if ret == TPE_USER_AUTH:
                        err, is_locked = update_fail_count(handler, user_info)
                        if is_locked:
                            err_msg = ',用户已被临时锁定'
                        msg = 'LDAP用户验证失败{}'.format(err_msg)
                        syslog.sys_log(user_info, handler.request.remote_ip,
                                       TPE_USER_AUTH, msg)
                        return TPE_USER_AUTH, None, msg
                    else:
                        msg = 'LDAP用户登录失败,{}'.format(err_msg)
                        syslog.sys_log(user_info, handler.request.remote_ip,
                                       TPE_USER_AUTH, msg)
                        return TPE_USER_AUTH, None, msg
            except:
                msg = 'LDAP用户登录失败,发生内部错误'
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, msg)
                return TPE_USER_AUTH, None, msg

        else:
            msg = '登录失败,系统内部错误'
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH,
                           msg)
            return TPE_USER_AUTH, None, msg

    if oath_code is not None:
        # use oath
        if len(user_info['oath_secret']) == 0:
            return TPE_OATH_MISMATCH, None, msg

        if not tp_oath_verify_code(user_info['oath_secret'], oath_code):
            err, is_locked = update_fail_count(handler, user_info)
            if is_locked:
                err_msg = ',用户已被临时锁定!'
            msg = '登录失败,身份验证器动态验证码错误{}'.format(err_msg)
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_OATH_MISMATCH, msg)
            return TPE_OATH_MISMATCH, None, msg

    del user_info['password']
    del user_info['oath_secret']

    if len(user_info['surname']) == 0:
        user_info['surname'] = user_info['username']
    return TPE_OK, user_info, msg
Пример #26
0
def update_user(handler, args):
    """
    更新一个用户账号
    """
    db = get_db()

    # 1. 判断此账号是否已经存在
    sql = 'SELECT `username` FROM {dbtp}user WHERE `id`={dbph};'.format(
        dbtp=db.table_prefix, dbph=db.place_holder)
    db_ret = db.query(sql, (args['id'], ))
    if db_ret is None or len(db_ret) == 0:
        return TPE_NOT_EXISTS

    old_username = db_ret[0][0]
    if old_username != args['username']:
        # 如果要更新用户登录名,则需要判断是否已经存在了
        sql = 'SELECT `id` FROM {dbtp}user WHERE `username`={dbph};'.format(
            dbtp=db.table_prefix, dbph=db.place_holder)
        db_ret = db.query(sql, (args['username'], ))
        if db_ret is not None and len(db_ret) > 0:
            return TPE_EXISTS

    sql = 'UPDATE `{}user` SET ' \
          '`username`="{username}", `surname`="{surname}", `auth_type`={auth_type}, ' \
          '`role_id`={role}, `email`="{email}", `mobile`="{mobile}", `qq`="{qq}", ' \
          '`wechat`="{wechat}", `valid_from`={valid_from}, `valid_to`={valid_to}, '\
          '`desc`="{desc}" WHERE `id`={user_id};' \
          ''.format(db.table_prefix,
                    username=args['username'], surname=args['surname'], auth_type=args['auth_type'], role=args['role'],
                    email=args['email'], mobile=args['mobile'], qq=args['qq'], wechat=args['wechat'],
                    valid_from=args['valid_from'], valid_to=args['valid_to'], desc=args['desc'], user_id=args['id']
                    )
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    # 同步更新授权表和权限映射表
    _uname = args['username']
    if len(args['surname']) > 0:
        _uname += '(' + args['surname'] + ')'
    sql_list = []
    # 运维授权
    sql_s = 'UPDATE `{tp}ops_auz` SET `name`={ph} WHERE (`rtype`={ph} AND `rid`={ph});' \
            ''.format(tp=db.table_prefix, ph=db.place_holder)
    sql_v = (_uname, TP_USER, args['id'])
    sql_list.append({'s': sql_s, 'v': sql_v})

    sql_s = 'UPDATE `{tp}ops_map` SET `u_name`={ph}, `u_surname`={ph} WHERE (u_id={ph});' \
            ''.format(tp=db.table_prefix, ph=db.place_holder)
    sql_v = (args['username'], args['surname'], args['id'])
    sql_list.append({'s': sql_s, 'v': sql_v})

    # 审计授权
    sql_s = 'UPDATE `{tp}audit_auz` SET `name`={ph} WHERE (`rtype`={ph} AND `rid`={ph});' \
            ''.format(tp=db.table_prefix, ph=db.place_holder)
    sql_v = (_uname, TP_USER, args['id'])
    sql_list.append({'s': sql_s, 'v': sql_v})

    sql_s = 'UPDATE `{tp}audit_map` SET `u_name`={ph}, `u_surname`={ph} WHERE (u_id={ph});' \
            ''.format(tp=db.table_prefix, ph=db.place_holder)
    sql_v = (args['username'], args['surname'], args['id'])
    sql_list.append({'s': sql_s, 'v': sql_v})

    if not db.transaction(sql_list):
        return TPE_DATABASE

    operator = handler.get_current_user()
    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK,
                   "更新用户信息:{}".format(args['username']))

    return TPE_OK
Пример #27
0
    def post(self):
        sys_cfg = tp_cfg().sys

        args = self.get_argument('args', None)
        if args is None:
            return self.write_json(TPE_PARAM)

        try:
            args = json.loads(args)
        except:
            return self.write_json(TPE_JSON_FORMAT, '参数错误')

        try:
            login_type = args['type']
            captcha = args['captcha'].strip()
            username = args['username'].strip().lower()
            password = args['password']
            oath = args['oath'].strip()
            remember = args['remember']
        except:
            return self.write_json(TPE_PARAM)

        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                TP_LOGIN_AUTH_USERNAME_OATH
        ]:
            return self.write_json(TPE_PARAM, '未知的认证方式')

        if login_type == TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA:
            oath = None
            code = self.get_session('captcha')
            if code is None:
                return self.write_json(TPE_CAPTCHA_EXPIRED, '验证码已失效')
            if code.lower() != captcha.lower():
                return self.write_json(TPE_CAPTCHA_MISMATCH, '验证码错误')
        elif login_type in [
                TP_LOGIN_AUTH_USERNAME_OATH,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH
        ]:
            if len(oath) == 0:
                return self.write_json(TPE_OATH_MISMATCH, '未提供身份验证器动态验证码')

        self.del_session('captcha')

        if len(username) == 0:
            return self.write_json(TPE_PARAM, '未提供登录用户名')

        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH
        ]:
            password = None
        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                TP_LOGIN_AUTH_USERNAME_OATH
        ]:
            oath = None

        # 检查用户名合法性,防止SQL注入攻击
        if '<' in username or '>' in username:
            username = username.replace('<', '&lt;')
            username = username.replace('>', '&gt;')
            err = TPE_USER_AUTH
            syslog.sys_log({
                'username': '******',
                'surname': '???'
            }, self.request.remote_ip, TPE_NOT_EXISTS,
                           '登录失败,可能是攻击行为。试图使用用户名 {} 进行登录。'.format(username))
            return self.write_json(err)

        err, user_info = user.login(self,
                                    username,
                                    password=password,
                                    oath_code=oath)
        if err != TPE_OK:
            if err == TPE_NOT_EXISTS:
                err = TPE_USER_AUTH
                syslog.sys_log({
                    'username': '******',
                    'surname': '???'
                }, self.request.remote_ip, TPE_NOT_EXISTS,
                               '登录失败,用户`{}`不存在'.format(username))
            return self.write_json(err)

        # 判断此用户是否被允许使用当前登录认证方式
        auth_type = user_info.auth_type
        if auth_type == 0:
            auth_type = sys_cfg.login.auth

        if (auth_type & login_type) != login_type:
            return self.write_json(TPE_USER_AUTH, '不允许使用此身份认证方式')

        self._user = user_info
        self._user['_is_login'] = True
        # del self._user['password']
        # del self._user['oath_secret']

        if remember:
            self.set_session('user', self._user, 12 * 60 * 60)
        else:
            self.set_session('user', self._user)

        user.update_login_info(self, user_info['id'])

        # 记录登录日志
        syslog.sys_log(self._user, self.request.remote_ip, TPE_OK, "登录成功")

        self.set_cookie('username', username)

        return self.write_json(TPE_OK)
Пример #28
0
def update_user(handler, args):
    """
    更新一个用户账号
    """
    db = get_db()

    # 1. 判断此账号是否已经存在
    sql = 'SELECT `username` FROM {dbtp}user WHERE `id`={dbph};'.format(dbtp=db.table_prefix, dbph=db.place_holder)
    db_ret = db.query(sql, (args['id'],))
    if db_ret is None or len(db_ret) == 0:
        return TPE_NOT_EXISTS

    old_username = db_ret[0][0]
    if old_username != args['username']:
        # 如果要更新用户登录名,则需要判断是否已经存在了
        sql = 'SELECT `id` FROM {dbtp}user WHERE `username`={dbph};'.format(dbtp=db.table_prefix, dbph=db.place_holder)
        db_ret = db.query(sql, (args['username'],))
        if db_ret is not None and len(db_ret) > 0:
            return TPE_EXISTS

    sql = 'UPDATE `{}user` SET ' \
          '`username`="{username}", `surname`="{surname}", `auth_type`={auth_type}, ' \
          '`role_id`={role}, `email`="{email}", `mobile`="{mobile}", `qq`="{qq}", ' \
          '`wechat`="{wechat}", `desc`="{desc}" WHERE `id`={user_id};' \
          ''.format(db.table_prefix,
                    username=args['username'], surname=args['surname'], auth_type=args['auth_type'], role=args['role'],
                    email=args['email'],
                    mobile=args['mobile'], qq=args['qq'], wechat=args['wechat'], desc=args['desc'],
                    user_id=args['id']
                    )
    db_ret = db.exec(sql)
    if not db_ret:
        return TPE_DATABASE

    # 同步更新授权表和权限映射表
    _uname = args['username']
    if len(args['surname']) > 0:
        _uname += '(' + args['surname'] + ')'
    sql_list = []
    # 运维授权
    sql = 'UPDATE `{}ops_auz` SET `name`="{uname}" WHERE (`rtype`={rtype} AND `rid`={rid});' \
          ''.format(db.table_prefix, uname=_uname, rtype=TP_USER, rid=args['id'])
    sql_list.append(sql)
    sql = 'UPDATE `{}ops_map` SET `u_name`="{uname}", `u_surname`="{surname}" WHERE (u_id={uid});'.format(
        db.table_prefix, uname=args['username'], surname=args['surname'], uid=args['id'])
    sql_list.append(sql)
    # 审计授权
    sql = 'UPDATE `{}audit_auz` SET `name`="{uname}" WHERE (`rtype`={rtype} AND `rid`={rid});' \
          ''.format(db.table_prefix, uname=_uname, rtype=TP_USER, rid=args['id'])
    sql_list.append(sql)
    sql = 'UPDATE `{}audit_map` SET `u_name`="{uname}", `u_surname`="{surname}" WHERE (u_id={uid});'.format(
        db.table_prefix, uname=args['username'], surname=args['surname'], uid=args['id'])
    sql_list.append(sql)

    if not db.transaction(sql_list):
        return TPE_DATABASE

    operator = handler.get_current_user()
    syslog.sys_log(operator, handler.request.remote_ip, TPE_OK, "更新用户信息:{}".format(args['username']))

    return TPE_OK
Пример #29
0
def login(handler,
          username,
          password=None,
          oath_code=None,
          check_bind_oath=False):
    sys_cfg = tp_cfg().sys

    err, user_info = get_by_username(username)
    if err != TPE_OK:
        # if err == TPE_NOT_EXISTS:
        #     syslog.sys_log({'username': username, 'surname': username}, handler.request.remote_ip, TPE_NOT_EXISTS,
        #                    '用户身份验证失败,用户`{}`不存在'.format(username))
        return err, None

    if user_info.privilege == 0:
        # 尚未为此用户设置角色
        return TPE_PRIVILEGE, None

    if check_bind_oath and len(user_info['oath_secret']) != 0:
        return TPE_OATH_ALREADY_BIND, None

    if user_info['state'] == TP_STATE_LOCKED:
        # 用户已经被锁定,如果系统配置为一定时间后自动解锁,则更新一下用户信息
        if sys_cfg.login.lock_timeout != 0:
            if tp_timestamp_utc_now(
            ) - user_info.lock_time > sys_cfg.login.lock_timeout * 60:
                user_info.fail_count = 0
                user_info.state = TP_STATE_NORMAL
        if user_info['state'] == TP_STATE_LOCKED:
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_USER_LOCKED, '登录失败,用户已被临时锁定')
            return TPE_USER_LOCKED, None
    elif user_info['state'] == TP_STATE_DISABLED:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_DISABLED,
                       '登录失败,用户已被禁用')
        return TPE_USER_DISABLED, None
    elif user_info['state'] != TP_STATE_NORMAL:
        syslog.sys_log(user_info, handler.request.remote_ip, TPE_FAILED,
                       '登录失败,用户状态异常')
        return TPE_FAILED, None

    err_msg = ''
    if password is not None:
        if user_info['type'] == TP_USER_TYPE_LOCAL:
            # 如果系统配置了密码有效期,则检查用户的密码是否失效
            if sys_cfg.password.timeout != 0:
                _time_now = tp_timestamp_utc_now()
                if user_info['last_chpass'] + (sys_cfg.password.timeout * 60 *
                                               60 * 24) < _time_now:
                    syslog.sys_log(user_info, handler.request.remote_ip,
                                   TPE_USER_AUTH, '登录失败,用户密码已过期')
                    return TPE_USER_AUTH, None

            if not tp_password_verify(password, user_info['password']):
                err, is_locked = update_fail_count(handler, user_info)
                if is_locked:
                    err_msg = ',用户已被临时锁定'
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, '登录失败,密码错误{}'.format(err_msg))
                return TPE_USER_AUTH, None
        elif user_info['type'] == TP_USER_TYPE_LDAP:
            try:
                if len(tp_cfg().sys_ldap_password) == 0:
                    syslog.sys_log(user_info, handler.request.remote_ip,
                                   TPE_USER_AUTH, 'LDAP未能正确配置,需要管理员密码')
                    return TPE_USER_AUTH, None
                else:
                    _ldap_password = tp_cfg().sys_ldap_password
                _ldap_server = tp_cfg().sys.ldap.server
                _ldap_port = tp_cfg().sys.ldap.port
                _ldap_base_dn = tp_cfg().sys.ldap.base_dn
            except:
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, 'LDAP未能正确配置')
                return TPE_USER_AUTH, None

            try:
                ldap = Ldap(_ldap_server, _ldap_port, _ldap_base_dn)
                ret, err_msg = ldap.valid_user(user_info['ldap_dn'], password)
                if ret != TPE_OK:
                    if ret == TPE_USER_AUTH:
                        err, is_locked = update_fail_count(handler, user_info)
                        if is_locked:
                            err_msg = ',用户已被临时锁定'
                        syslog.sys_log(user_info, handler.request.remote_ip,
                                       TPE_USER_AUTH,
                                       'LDAP用户登录失败,密码错误{}'.format(err_msg))
                        return TPE_USER_AUTH, None
                    else:
                        syslog.sys_log(user_info, handler.request.remote_ip,
                                       TPE_USER_AUTH,
                                       'LDAP用户登录失败,{}'.format(err_msg))
                        return TPE_USER_AUTH, None
            except:
                syslog.sys_log(user_info, handler.request.remote_ip,
                               TPE_USER_AUTH, 'LDAP用户登录失败,发生内部错误')
                return TPE_USER_AUTH, None

        else:
            syslog.sys_log(user_info, handler.request.remote_ip, TPE_USER_AUTH,
                           '登录失败,系统内部错误')
            return TPE_USER_AUTH, None

    if oath_code is not None:
        # use oath
        if len(user_info['oath_secret']) == 0:
            return TPE_OATH_MISMATCH, None

        if not tp_oath_verify_code(user_info['oath_secret'], oath_code):
            err, is_locked = update_fail_count(handler, user_info)
            if is_locked:
                err_msg = ',用户已被临时锁定!'
            syslog.sys_log(user_info, handler.request.remote_ip,
                           TPE_OATH_MISMATCH,
                           "登录失败,身份验证器动态验证码错误{}".format(err_msg))
            return TPE_OATH_MISMATCH, None

    del user_info['password']
    del user_info['oath_secret']

    if len(user_info['surname']) == 0:
        user_info['surname'] = user_info['username']
    return TPE_OK, user_info
Пример #30
0
def remove(handler, gtype, glist):
    if gtype not in TP_GROUP_TYPES:
        return TPE_PARAM

    group_ids = ','.join([str(i) for i in glist])

    # 1. 获取组的名称,用于记录系统日志
    where = 'g.type={gtype} AND g.id IN ({gids})'.format(gtype=gtype,
                                                         gids=group_ids)

    db = get_db()
    s = SQL(db)
    err = s.select_from('group', ['name'], alt_name='g').where(where).query()
    if err != TPE_OK:
        return err
    if len(s.recorder) == 0:
        return TPE_NOT_EXISTS

    name_list = [n['name'] for n in s.recorder]

    sql_list = []

    # 删除组与成员的映射关系
    sql = 'DELETE FROM `{tpdp}group_map` WHERE `type`={t} AND `gid` IN ({ids});'.format(
        tpdp=db.table_prefix, t=gtype, ids=group_ids)
    sql_list.append(sql)

    # where = 'type={} AND gid IN ({})'.format(gtype, ','.join(group_list))
    # err = s.reset().delete_from('group_map').where(where).exec()
    # if err != TPE_OK:
    #     return err

    # 删除组
    sql = 'DELETE FROM `{tpdp}group` WHERE `type`={t} AND `id` IN ({ids});'.format(
        tpdp=db.table_prefix, t=gtype, ids=group_ids)
    sql_list.append(sql)
    # where = 'type={gtype} AND id IN ({gids})'.format(gtype=gtype, gids=','.join(group_list))
    # err = s.reset().delete_from('group').where(where).exec()
    # if err != TPE_OK:
    #     return err

    if gtype == TP_GROUP_USER:
        gname = 'gu'
    elif gtype == TP_GROUP_HOST:
        gname = 'gh'
    elif gtype == TP_GROUP_ACCOUNT:
        gname = 'ga'
    else:
        return TPE_PARAM

    # 将组从运维授权中移除
    sql = 'DELETE FROM `{}ops_auz` WHERE `rtype`={rtype} AND `rid` IN ({ids});'.format(
        db.table_prefix, rtype=gtype, ids=group_ids)
    sql_list.append(sql)
    sql = 'DELETE FROM `{}ops_map` WHERE `{gname}_id` IN ({ids});'.format(
        db.table_prefix, gname=gname, ids=group_ids)
    sql_list.append(sql)
    # 将组从审计授权中移除
    sql = 'DELETE FROM `{}audit_auz` WHERE `rtype`={rtype} AND `rid` IN ({ids});'.format(
        db.table_prefix, rtype=gtype, ids=group_ids)
    sql_list.append(sql)
    # 注意,审计授权映射表中,没有远程账号相关信息,所以如果是远程账号组,则忽略
    if gtype != TP_GROUP_ACCOUNT:
        sql = 'DELETE FROM `{}audit_map` WHERE `{gname}_id` IN ({ids});'.format(
            db.table_prefix, gname=gname, ids=group_ids)
        sql_list.append(sql)

    if not db.transaction(sql_list):
        return TPE_DATABASE

    # 记录系统日志
    syslog.sys_log(
        handler.get_current_user(), handler.request.remote_ip, TPE_OK,
        "删除{gtype}:{gname}".format(gtype=TP_GROUP_TYPES[gtype],
                                   gname=','.join(name_list)))

    return TPE_OK
Пример #31
0
    def post(self):
        sys_cfg = tp_cfg().sys

        args = self.get_argument('args', None)
        if args is None:
            return self.write_json(TPE_PARAM)

        try:
            args = json.loads(args)
        except:
            return self.write_json(TPE_JSON_FORMAT, '参数错误')

        try:
            login_type = args['type']
            captcha = args['captcha'].strip()
            username = args['username'].strip().lower()
            password = args['password']
            oath = args['oath'].strip()
            remember = args['remember']
        except:
            return self.write_json(TPE_PARAM)

        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                TP_LOGIN_AUTH_USERNAME_OATH
        ]:
            return self.write_json(TPE_PARAM, '未知的认证方式')

        if login_type == TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA:
            oath = None
            code = self.get_session('captcha')
            if code is None:
                return self.write_json(TPE_CAPTCHA_EXPIRED, '验证码已失效')
            if code.lower() != captcha.lower():
                return self.write_json(TPE_CAPTCHA_MISMATCH, '验证码错误')
        elif login_type in [
                TP_LOGIN_AUTH_USERNAME_OATH,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH
        ]:
            if len(oath) == 0:
                return self.write_json(TPE_OATH_MISMATCH, '未提供身份验证器动态验证码')

        self.del_session('captcha')

        if len(username) == 0:
            return self.write_json(TPE_PARAM, '未提供登录用户名')

        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA,
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH
        ]:
            password = None
        if login_type not in [
                TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH,
                TP_LOGIN_AUTH_USERNAME_OATH
        ]:
            oath = None

        err, user_info = user.login(self,
                                    username,
                                    password=password,
                                    oath_code=oath)
        if err != TPE_OK:
            if err == TPE_NOT_EXISTS:
                err = TPE_USER_AUTH
                syslog.sys_log({
                    'username': username,
                    'surname': username
                }, self.request.remote_ip, TPE_NOT_EXISTS,
                               '登录失败,用户`{}`不存在'.format(username))
            return self.write_json(err)

        # 判断此用户是否被允许使用当前登录认证方式
        auth_type = user_info.auth_type
        if auth_type == 0:
            auth_type = sys_cfg.login.auth

        if (auth_type & login_type) != login_type:
            return self.write_json(TPE_USER_AUTH, '不允许使用此身份认证方式')

        # err, user_info = user.get_by_username(username)
        # if err != TPE_OK:
        #     if err == TPE_NOT_EXISTS:
        #         syslog.sys_log({'username': username, 'surname': username}, self.request.remote_ip, TPE_NOT_EXISTS, '登录失败,用户`{}`不存在'.format(username))
        #     return self.write_json(err)
        #
        # if user_info.privilege == 0:
        #     # 尚未为此用户设置角色
        #     return self.write_json(TPE_PRIVILEGE, '用户尚未分配角色')
        #
        # if user_info['state'] == TP_STATE_LOCKED:
        #     # 用户已经被锁定,如果系统配置为一定时间后自动解锁,则更新一下用户信息
        #     if sys_cfg.login.lock_timeout != 0:
        #         if tp_timestamp_utc_now() - user_info.lock_time > sys_cfg.login.lock_timeout * 60:
        #             user_info.fail_count = 0
        #             user_info.state = TP_STATE_NORMAL
        #     if user_info['state'] == TP_STATE_LOCKED:
        #         syslog.sys_log(user_info, self.request.remote_ip, TPE_USER_LOCKED, '登录失败,用户已被锁定')
        #         return self.write_json(TPE_USER_LOCKED)
        # elif user_info['state'] == TP_STATE_DISABLED:
        #     syslog.sys_log(user_info, self.request.remote_ip, TPE_USER_DISABLED, '登录失败,用户已被禁用')
        #     return self.write_json(TPE_USER_DISABLED)
        # elif user_info['state'] != TP_STATE_NORMAL:
        #     syslog.sys_log(user_info, self.request.remote_ip, TPE_FAILED, '登录失败,系统内部错误')
        #     return self.write_json(TPE_FAILED)
        #
        # err_msg = ''
        # if login_type in [TP_LOGIN_AUTH_USERNAME_PASSWORD, TP_LOGIN_AUTH_USERNAME_PASSWORD_CAPTCHA, TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH]:
        #     # 如果系统配置了密码有效期,则检查用户的密码是否失效
        #     if sys_cfg.password.timeout != 0:
        #         pass
        #
        #     if not tp_password_verify(password, user_info['password']):
        #         err, is_locked = user.update_fail_count(self, user_info)
        #         if is_locked:
        #             err_msg = '用户被临时锁定!'
        #         syslog.sys_log(user_info, self.request.remote_ip, TPE_USER_AUTH, '登录失败,密码错误!{}'.format(err_msg))
        #         return self.write_json(TPE_USER_AUTH)
        #
        # if login_type in [TP_LOGIN_AUTH_USERNAME_OATH, TP_LOGIN_AUTH_USERNAME_PASSWORD_OATH]:
        #     # use oath
        #     if not tp_oath_verify_code(user_info['oath_secret'], oath):
        #         err, is_locked = user.update_fail_count(self, user_info)
        #         if is_locked:
        #             err_msg = '用户被临时锁定!'
        #         syslog.sys_log(user_info, self.request.remote_ip, TPE_OATH_MISMATCH, "登录失败,身份验证器动态验证码错误!{}".format(err_msg))
        #         return self.write_json(TPE_OATH_MISMATCH)

        self._user = user_info
        self._user['_is_login'] = True
        # del self._user['password']
        # del self._user['oath_secret']

        if remember:
            self.set_session('user', self._user, 12 * 60 * 60)
        else:
            self.set_session('user', self._user)

        user.update_login_info(self, user_info['id'])

        # 记录登录日志
        syslog.sys_log(self._user, self.request.remote_ip, TPE_OK, "登录成功")

        self.set_cookie('username', username)

        return self.write_json(TPE_OK)