Ejemplo n.º 1
0
 def reset(cls):
     cls.data = JsDict()
     cls.score_board = JsDict()  # k user_name v score
     cls.solved = {}  # k user_name v list of game_id
     cls.solved_all = {}  # k game_id v user_name
     cls.extra = {}  # 附加分值
     cls.last_submit = JsDict()  # 最后提交
     cls.is_end = False  # 是否结束
     cls.last_save_time = 0  # 上次保存进度的时间
     cls.init()
Ejemplo n.º 2
0
Archivo: game.py Proyecto: 5up3rc/myctf
    def init(cls):
        for i in os.listdir('ctf'):
            if i.endswith('.txt'):
                raw_txt = open("ctf/"+i).read()
                txt = raw_txt
                for t in re.findall(r'"(.*?)(?<!\\)"', raw_txt, re.DOTALL):
                    txt = txt.replace(t, t.replace('\r', r'\r').replace('\n', r'\n'))

                data = JsDict(json.loads(txt))
                data.txt = data.txt.strip()
                data.id = int(data.id)
                if not data.id in cls.extra:
                    cls.extra[data.id] = data.extra if 'extra' in data else 5
                cls.data[data.id] = data
Ejemplo n.º 3
0
    def post(self):
        words = self.get_argument('words', '')  # 用户的留言
        dele_by_key = self.get_argument('theKey', '')
        IP = self.request.headers["X-Forwarded-For"]
        user = self.current_user()
        username = None
        word_user = None
        word_username = None
        if user is None:
            user = JsDict()
            user.username = "******"

        if dele_by_key != "":
            word_user = Board.get_one(Board.key == dele_by_key)
        if word_user is not None:
            word_username = word_user.username
        if user is not None:
            username = user.username
        if dele_by_key:
            if user.is_admin() or username == word_username:  # 如果不是admin用户将无法删除
                Board.dele_by_key(dele_by_key)
                self.write("删除成功!")
            else:
                self.write("您没有删除权限!")
        elif words:
            username = user.username
            user_re = re.compile(r"@(\S{3,19}) (.*)")
            try:
                foruser = user_re.search(words).group(1)
                if not User.exist(foruser):
                    foruser = ""
                else:
                    words = user_re.search(words).group(2)
            except Exception as e:
                foruser = ""
            if Board.num_lim(username):
                self.messages.error("留言过多,请联系管理员!")
                self.redirect("/board")
            elif user.username != "游客" and user.level == 0:
                self.messages.error("您暂时无法留言!")
                self.redirect(url_for("board"))
            else:
                Board.new(username, foruser, words, IP)
                self.messages.success("留言成功!")
                self.redirect(url_for("board"))
        else:
            self.redirect(url_for("board"))

        '''
Ejemplo n.º 4
0
    def init(cls):
        for i in os.listdir('ctf'):
            if i.endswith('.txt'):
                try:
                    raw_txt = open("ctf/" + i, encoding='utf-8').read()
                except:
                    raw_txt = open("ctf/" + i).read()
                txt = raw_txt
                for t in re.findall(r'"(.*?)(?<!\\)"', raw_txt, re.DOTALL):
                    txt = txt.replace(t, t.replace('\r', r'\r').replace('\n', r'\n'))

                data = JsDict(json.loads(txt))
                data.txt = data.txt.strip()
                data.id = int(data.id)
                if not data.id in cls.extra:
                    cls.extra[data.id] = data.extra if 'extra' in data else 5
                cls.data[data.id] = data
Ejemplo n.º 5
0
    def post(self):
        ret = self.value_valid(None)

        if self.messages.has_error():
            self.render('admin/question_edit.html', question=JsDict(ret), title=u'添加题目', is_new_question=True)
        else:
            Games.game_add(ret)
            self.messages.success(u'添加题目成功')
            self.redirect(url_for('admin_questions'))
Ejemplo n.º 6
0
    def post(self, qid):
        ret = self.value_valid(qid)

        if self.messages.has_error():
            q = Games.data.get(int(qid))
            self.render('admin/question_edit.html', question=JsDict(ret), title=u'编辑:%s' % q['title'])
        else:
            ret['id'] = int(qid)
            Games.game_edit(ret)
            self.messages.success(u'编辑成功')
            self.redirect(url_for('admin_questions'))
Ejemplo n.º 7
0
Archivo: forum.py Proyecto: fy0/Icarus
 def get(self, topic_id):
     topic = Topic.get_by_pk(topic_id)
     if topic:
         topic.view_count_inc()
         count, user_topics = Topic.get_list_by_user(topic.user)
         user_topics = user_topics.limit(10)
         follow = JsDict()
         if self.current_user():
             follow.topic = Follow.exists(OBJECT_TYPES.TOPIC, topic_id, self.current_user())
             follow.author = Follow.exists(OBJECT_TYPES.USER, topic.user.id, self.current_user())
         self.render(
             "forum/topic.html",
             nav="index",
             page_title=page_title(topic.title, topic.board.title, "社区"),
             topic=topic,
             user_topics=user_topics,
             follow=follow,
         )
     else:
         self.write_error(404)
Ejemplo n.º 8
0
    def get_messages(self):
        msg_lst = self.messages.messages + (self.session['_messages'] or [])
        _messages = []

        for i in msg_lst:
            tag, txt = i
            try: txt = txt.decode('utf-8') # 为py2做个转换
            except: pass
            _messages.append(JsDict(tag=Messages.DEFAULT_TAGS[tag], txt=txt))

        self.messages.messages = []
        return _messages
Ejemplo n.º 9
0
    def get(self, game_id):
        if not self.current_user():
            self.messages.error('请先登录!')
            return self.redirect(url_for('signin'))

        g = Games.data[int(game_id)]
        if g and Games.depend_check(self.current_user(), int(game_id)):
            ret = g.copy()
            del ret['key']
            self.render(game=JsDict(ret))
        else:
            self.write_error(404)
Ejemplo n.º 10
0
class Messages(object):

    MESSAGE_LEVEL = JsDict(
        DEBUG=10,
        INFO=20,
        SUCCESS=25,
        WARNING=30,
        ERROR=40,
    )

    DEFAULT_TAGS = {
        MESSAGE_LEVEL.DEBUG: 'debug',
        MESSAGE_LEVEL.INFO: 'info',
        MESSAGE_LEVEL.SUCCESS: 'success',
        MESSAGE_LEVEL.WARNING: 'warning',
        MESSAGE_LEVEL.ERROR: 'error',
    }

    def __init__(self):
        self.messages = []

    def _add_message(self, level, message):
        self.messages.append([level, message])

    def debug(self, message):
        self._add_message(self.MESSAGE_LEVEL.DEBUG, message)

    def info(self, message):
        self._add_message(self.MESSAGE_LEVEL.INFO, message)

    def success(self, message):
        self._add_message(self.MESSAGE_LEVEL.SUCCESS, message)

    def warning(self, message):
        self._add_message(self.MESSAGE_LEVEL.WARNING, message)

    def error(self, message):
        self._add_message(self.MESSAGE_LEVEL.ERROR, message)

    def has_error(self):
        for i in self.messages:
            if i[0] == self.MESSAGE_LEVEL.ERROR:
                return True
Ejemplo n.º 11
0
class Games(object):
    data = JsDict()
    score_board = JsDict()  # k user_name v score
    solved = {}  # k user_name v list of game_id
    solved_all = {}  # k game_id v user_name
    extra = {}  # 附加分值
    last_submit = JsDict()  # 最后提交
    is_end = False  # 是否结束
    last_save_time = 0  # 上次保存进度的时间

    @classmethod
    def reload_data(cls):
        """ 重新加载题目 """
        cls.init()

    @classmethod
    def save_to_json(cls, fn):
        info = {
            'score_board': cls.score_board,
            'solved': cls.solved,
            'solved_all': cls.solved_all,
            'extra': cls.extra,
            'last_submit': cls.last_submit,
            'is_end': cls.is_end,
        }
        cls.last_save_time = int(time.time())
        open(fn, 'w').write(json.dumps(info))

    @classmethod
    def load_from_json(cls, fn):
        txt = open(fn, 'r').read()
        info = json.loads(txt)
        if 'score_board' in info:
            cls.score_board = info['score_board']
        if 'solved' in info:
            cls.solved = info['solved']
        if 'solved_all' in info:
            cls.solved_all = info['solved_all']
        if 'extra' in info:
            for k, v in info['extra'].items():
                # json 的 key 不能为数字,所以。。
                k = int(k)
                cls.extra[k] = v
        if 'last_submit' in info:
            cls.last_submit = info['last_submit']
        if 'is_end' in info:
            cls.deadline = info['is_end']

    @classmethod
    def depend_check(cls, user, game_id):
        info = cls.data.get(game_id)

        if info:
            for i in info['depend']:
                if user.username not in cls.solved:
                    return False

                if i not in cls.solved[user.username]:
                    return False

            for i in info['depend-g']:
                if i not in cls.solved_all:
                    return False
        else:
            return False

        return True

    @classmethod
    def game_edit(cls, info):
        cls.data[info['id']].update(info)
        open(os.path.join(u'ctf', u'问题%s.txt' % info['id']), 'w').write(json.dumps(info))

    @classmethod
    def game_add(cls, info):
        cls.data[info['id']] = JsDict(info)
        open(os.path.join(u'ctf', u'问题%s.txt' % info['id']), 'w').write(json.dumps(info))

    @classmethod
    def game_rm(cls, game_id):
        del cls.data[game_id]
        os.remove(os.path.join(u'ctf', u'问题%s.txt' % game_id))

    @classmethod
    def solve(cls, user, game_id, key):
        """
        尝试回答问题。答对加分,答错或重答不管。
        :param user: 用户对象
        :param game_id: 题目id
        :param key: 答案
        :return: True 回答成功,False回答失败
        """
        game_id = int(game_id)
        g = cls.get_game(game_id)
        if g:
            # 答案错误直接返回
            if g.key != key:
                return False

            # 初始化回答列表
            if not user.username in cls.solved:
                cls.solved[user.username] = []

            # 已经回答过直接返回
            if game_id in cls.solved[user.username]:
                return False

            # 加分
            if not user.username in cls.score_board:
                cls.score_board[user.username] = 0
            cls.score_board[user.username] += g.score

            # 奖励分数
            if game_id in cls.extra and cls.extra[game_id] > 0:
                cls.score_board[user.username] += cls.extra[game_id]
                cls.extra[game_id] -= 1

            # 加入回答列表
            cls.solved[user.username].append(game_id)

            # 加入总列表
            if not game_id in cls.solved_all:
                cls.solved_all[game_id] = []
            cls.solved_all[game_id].append(user.username)

            # 标记最后提交
            cls.last_submit[user.username] = time.time()

            return True

    @classmethod
    def get_user_solved(cls, user):
        """ 获取用户已经解决的问题列表 """
        if user and user.username in cls.solved:
            return list(map(int, cls.solved[user.username]))
        return []

    @classmethod
    def get_score(cls, user):
        if user:
            if user.username in cls.score_board:
                return cls.score_board[user.username]
        return 0

    @classmethod
    def get_score_board(cls):
        def my_key(x):
            return [x[1], -cls.last_submit[x[0]]]

        return OrderedDict(sorted(cls.score_board.items(), key=my_key, reverse=True))

    @classmethod
    def get_brief_lst(cls):
        ret = []
        for i in cls.data.keys():
            ret.append([cls.data[i].id, cls.data[i].title, cls.data[i].score])
        return ret

    @classmethod
    def get_lst(cls):
        ret = []
        for i in cls.data.values():
            ret.append(JsDict(i))
        return ret

    @classmethod
    def init(cls):
        for i in os.listdir('ctf'):
            if i.endswith('.txt'):
                try:
                    raw_txt = open("ctf/" + i, encoding='utf-8').read()
                except:
                    raw_txt = open("ctf/" + i).read()
                txt = raw_txt
                for t in re.findall(r'"(.*?)(?<!\\)"', raw_txt, re.DOTALL):
                    txt = txt.replace(t, t.replace('\r', r'\r').replace('\n', r'\n'))

                data = JsDict(json.loads(txt))
                data.txt = data.txt.strip()
                data.id = int(data.id)
                if not data.id in cls.extra:
                    cls.extra[data.id] = data.extra if 'extra' in data else 5
                cls.data[data.id] = data

    @classmethod
    def reset(cls):
        cls.data = JsDict()
        cls.score_board = JsDict()  # k user_name v score
        cls.solved = {}  # k user_name v list of game_id
        cls.solved_all = {}  # k game_id v user_name
        cls.extra = {}  # 附加分值
        cls.last_submit = JsDict()  # 最后提交
        cls.is_end = False  # 是否结束
        cls.last_save_time = 0  # 上次保存进度的时间
        cls.init()

    @classmethod
    def get_game(cls, game_id):
        return cls.data[int(game_id)]

    @classmethod
    def get_without_key(cls, game_id):
        ret = cls.data[int(game_id)].copy()
        del ret['key']
        return JsDict(ret)
Ejemplo n.º 12
0
 def get_without_key(cls, game_id):
     ret = cls.data[int(game_id)].copy()
     del ret['key']
     return JsDict(ret)
Ejemplo n.º 13
0
 def get(self):
     self.render('admin/question_edit.html', question=JsDict({}), title=u'添加题目', is_new_question=True)
Ejemplo n.º 14
0
 def game_add(cls, info):
     cls.data[info['id']] = JsDict(info)
     open(os.path.join(u'ctf', u'问题%s.txt' % info['id']), 'w').write(json.dumps(info))
Ejemplo n.º 15
0
 def get(self, qid):
     q = Games.data.get(int(qid))
     if not q:
         self.write_error(404)
     else:
         self.render('admin/question_edit.html', question=JsDict(q), title=u'编辑:%s' % q['title'])
Ejemplo n.º 16
0
import _env

import getpass
import socket
from lib.jsdict import JsDict

import _load
import re

HOSTNAME = socket.gethostname()

_load.load(
    JsDict(locals()),
    'default',
    'host.%s' % HOSTNAME,
    #    'user.%s' % getpass.getuser(),
)
Ejemplo n.º 17
0
 def get_lst(cls):
     ret = []
     for i in cls.data.values():
         ret.append(JsDict(i))
     return ret