Skip to content

Commit

Permalink
Lock for Levels and Corps
Browse files Browse the repository at this point in the history
  • Loading branch information
eljeffeg committed May 29, 2023
1 parent 1857c7b commit 5e58c94
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 15 deletions.
49 changes: 49 additions & 0 deletions alembic/versions/f443eed40161_add_corp_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""add corp lock
Revision ID: f443eed40161
Revises: ffe623ae412
Create Date: 2023-05-27 17:01:22.454528
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.sql.expression import func

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

# revision identifiers, used by Alembic.
revision = "f443eed40161"
down_revision = "ffe623ae412"
branch_labels = None
depends_on = None


def _table_has_column(table, column):
has_column = False
for col in inspector.get_columns(table):
if column not in col["name"]:
continue
has_column = True
return has_column


def _has_table(table_name):
tables = inspector.get_table_names()
return table_name in tables


def upgrade():
if not _table_has_column("corporation", "_locked"):
op.add_column("corporation", sa.Column("_locked", sa.BOOLEAN))
if not _table_has_column("game_level", "_locked"):
op.add_column("game_level", sa.Column("_locked", sa.BOOLEAN))


def downgrade():
if _table_has_column("corporation", "_locked"):
op.drop_column("corporation", "_locked")
if _table_has_column("game_level", "_locked"):
op.drop_column("game_level", "_locked")
48 changes: 43 additions & 5 deletions handlers/AdminHandlers/AdminUserHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from models.Team import Team
from models.Box import Box
from models.Flag import Flag
from models.Corporation import Corporation
from models.User import User, ADMIN_PERMISSION
from models.Permission import Permission
from models.GameLevel import GameLevel
Expand Down Expand Up @@ -337,7 +338,13 @@ class AdminLockHandler(BaseHandler):
@authorized(ADMIN_PERMISSION)
def post(self, *args, **kwargs):
"""Calls an lock based on URL"""
uri = {"user": self.lock_user, "box": self.lock_box, "flag": self.lock_flag}
uri = {
"user": self.lock_user,
"box": self.lock_box,
"flag": self.lock_flag,
"corp": self.lock_corp,
"level": self.lock_level,
}
if len(args) and args[0] in uri:
uri[args[0]]()
else:
Expand All @@ -355,14 +362,45 @@ def lock_user(self):
else:
self.render("public/404.html")

def lock_corp(self):
uuid = self.get_argument("uuid", "")
corp = Corporation.by_uuid(uuid)
if corp is not None:
corp.locked = False if corp.locked else True
self.dbsession.add(corp)
self.dbsession.commit()
self.redirect("/admin/view/game_objects#%s" % corp.uuid)
else:
self.render("public/404.html")

def lock_level(self):
uuid = self.get_argument("uuid", "")
level = GameLevel.by_uuid(uuid)
if level is not None:
level.locked = False if level.locked else True
self.dbsession.add(level)
self.dbsession.commit()
self.redirect("/admin/view/game_levels")
else:
self.render("public/404.html")

def lock_box(self):
uuid = self.get_argument("uuid", "")
box = Box.by_uuid(uuid)
if box is not None:
box.locked = False if box.locked else True
self.dbsession.add(box)
self.dbsession.commit()
self.redirect("/admin/view/game_objects#%s" % box.uuid)
if box.locked_corp():
self.render(
"admin/view/game_objects.html", success=None, errors=["Box Locked by Corporation Lock"]
)
elif box.locked_level():
self.render(
"admin/view/game_objects.html", success=None, errors=["Box Locked by Level Lock"]
)
else:
box.locked = False if box.locked else True
self.dbsession.add(box)
self.dbsession.commit()
self.redirect("/admin/view/game_objects#%s" % box.uuid)
else:
self.render("public/404.html")

Expand Down
2 changes: 1 addition & 1 deletion handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def get_cookie_secret():
(r"/admin/users/edit/teams/scores", AdminEditTeamsHandler),
(r"/admin/users/delete/(.*)", AdminDeleteUsersHandler),
(r"/admin/ajax/(user|team)", AdminAjaxUserHandler),
(r"/admin/lock/(user|box|flag)", AdminLockHandler),
(r"/admin/lock/(level|corp|user|box|flag)", AdminLockHandler),
(r"/admin/configuration", AdminConfigurationHandler),
(r"/admin/gitstatus", AdminGitStatusHandler),
(r"/admin/export/(.*)", AdminExportHandler),
Expand Down
20 changes: 19 additions & 1 deletion models/Box.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,10 +294,26 @@ def value(self, value):
self._value = abs(int(value))
except ValueError:
raise ValidationError("Reward value must be an integer")

def locked_corp(self):
corp = Corporation.by_id(self.corporation_id)
if corp and corp.locked:
return True
return False

def locked_level(self):
level = GameLevel.by_id(self.game_level_id)
if level and level.locked:
return True
return False

@property
def locked(self):
"""Determines if an admin has locked an box."""
if self.locked_corp():
return True
if self.locked_level():
return True
if self._locked == None:
return False
return self._locked
Expand Down Expand Up @@ -401,7 +417,9 @@ def to_xml(self, parent):
).name
ET.SubElement(box_elem, "difficulty").text = self._difficulty
ET.SubElement(box_elem, "garbage").text = str(self.garbage)
ET.SubElement(box_elem, "locked").text = str(self.locked)
ET.SubElement(box_elem, "locked").text = str(
False if self._locked is None else self._locked
)
if self.category_id:
ET.SubElement(box_elem, "category").text = Category.by_id(
self.category_id
Expand Down
23 changes: 22 additions & 1 deletion models/Corporation.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from uuid import uuid4
from sqlalchemy import Column
from sqlalchemy.types import Unicode, String
from sqlalchemy.types import Unicode, String, Boolean
from sqlalchemy.orm import relationship, backref
from libs.ValidationError import ValidationError
from builtins import str
Expand All @@ -39,6 +39,7 @@ class Corporation(DatabaseObject):

_name = Column(Unicode(32), unique=True, nullable=False)
_description = Column(Unicode(512))
_locked = Column(Boolean, default=False, nullable=False)

boxes = relationship(
"Box",
Expand Down Expand Up @@ -92,6 +93,25 @@ def description(self, value):
raise ValidationError("Description cannot be greater than 512 characters")
self._description = str(value)

@property
def locked(self):
"""Determines if an admin has locked an corp."""
if self._locked == None:
return False
return self._locked

@locked.setter
def locked(self, value):
"""Setter method for _lock"""
if value is None:
value = False
elif isinstance(value, int):
value = value == 1
elif isinstance(value, str):
value = value.lower() in ["true", "1"]
assert isinstance(value, bool)
self._locked = value

def to_dict(self):
"""Returns editable data as a dictionary"""
return {
Expand All @@ -106,6 +126,7 @@ def to_xml(self, parent):
corp_elem = ET.SubElement(parent, "corporation")
ET.SubElement(corp_elem, "name").text = self.name
ET.SubElement(corp_elem, "description").text = self.description
ET.SubElement(corp_elem, "locked").text = str(self.locked)
boxes_elem = ET.SubElement(corp_elem, "boxes")
boxes_elem.set("count", "%s" % str(len(self.boxes)))
for box in self.boxes:
Expand Down
28 changes: 27 additions & 1 deletion models/GameLevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from uuid import uuid4
from sqlalchemy import Column, ForeignKey, asc
from sqlalchemy.types import Unicode, Integer, String
from sqlalchemy.types import Unicode, Integer, String, Boolean
from sqlalchemy.orm import relationship, backref
from libs.ValidationError import ValidationError
from models import dbsession
Expand All @@ -46,6 +46,7 @@ class GameLevel(DatabaseObject):
_reward = Column(Integer, nullable=False, default=0)
_name = Column(Unicode(32), nullable=True)
_description = Column(Unicode(512))
_locked = Column(Boolean, default=False, nullable=False)

boxes = relationship(
"Box",
Expand Down Expand Up @@ -174,6 +175,30 @@ def flags(self):
_flags += sorted(box.flags)
return _flags

@property
def locked(self):
"""Determines if an admin has locked an level."""
if self._locked == None:
return False
return self._locked

@locked.setter
def locked(self, value):
"""Setter method for _lock"""
if value is None:
value = False
elif isinstance(value, int):
value = value == 1
elif isinstance(value, str):
value = value.lower() in ["true", "1"]
assert isinstance(value, bool)
self._locked = value

def unlocked_boxes(self):
if self._locked:
return []
return [box for box in self.boxes if not box.locked]

def to_xml(self, parent):
level_elem = ET.SubElement(parent, "gamelevel")
ET.SubElement(level_elem, "number").text = str(self.number)
Expand All @@ -182,6 +207,7 @@ def to_xml(self, parent):
ET.SubElement(level_elem, "reward").text = str(self._reward)
ET.SubElement(level_elem, "name").text = str(self._name)
ET.SubElement(level_elem, "description").text = str(self._description)
ET.SubElement(level_elem, "locked").text = str(self.locked)

def to_dict(self):
"""Return public data as dict"""
Expand Down
5 changes: 5 additions & 0 deletions static/js/pages/admin/view/game_levels.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ $(document).ready(function() {
$("#delete-game-level-form").submit();
});

$("a[id^=lock-level-button]").click(function() {
$("#lock-level-uuid").val($(this).data("uuid"));
$("#lock-level-form").submit();
});

/* Switch Level */
$("a[id^=switch-level-button]").click(function() {
$("#game-level-uuid").val($(this).data("level-uuid"));
Expand Down
5 changes: 5 additions & 0 deletions static/js/pages/admin/view/game_objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ $(document).ready(function() {
$("#lock-box-uuid").val($(this).data("uuid"));
$("#lock-box-form").submit();
});

$("a[id^=lock-corp-button]").click(function() {
$("#lock-corp-uuid").val($(this).data("uuid"));
$("#lock-corp-form").submit();
});

$("a[id^=lock-flag-button]").click(function() {
$("#lock-flag-uuid").val($(this).data("uuid"));
Expand Down
19 changes: 18 additions & 1 deletion templates/admin/view/game_levels.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,18 @@
{% block title %}{{ _("Game Levels") }}{% end %}

{% block header %}
<link rel="stylesheet" href="/static/css/pages/admin/game_objects.css" type="text/css" />
<script src="/static/js/pages/admin/view/game_levels.js"></script>
{% end %}

{% block modals %}
{% from tornado.options import options %}
{% from models.GameLevel import GameLevel %}
<!-- Lock Corp Form -->
<form id="lock-level-form" action="/admin/lock/level" method="post">
{% raw xsrf_form_html() %}
<input id="lock-level-uuid" name="uuid" type="hidden" />
</form>
<!-- Edit Level -->
<div id="edit-game-level-modal" class="modal hide fade" style="display: none; ">
<div class="modal-header">
Expand Down Expand Up @@ -208,7 +214,7 @@ <h1>
</h1>
<br />
{% for index, level in enumerate(GameLevel.all()) %}
<div class="well">
<div class="well{% if level.locked %} locked{% end %}">
<h2 class="levelheader">
{{ level.name }}&nbsp;
</h2>
Expand All @@ -225,6 +231,17 @@ <h2 class="levelheader">
<i class="fa fa-pencil"></i>
{{ _("Edit Access") }}
</button>
{% if level.locked %}
<a id="lock-level-button-{{ level.uuid }}" class="btn btn-small btn-warning" data-uuid="{{ level.uuid }}" style="float: right; margin-top: 5px; margin-right: 10px;">
<i class="fa fa-fw fa-lock"></i>
{{_("Unlock")}}&nbsp;
</a>
{% else %}
<a id="lock-level-button-{{ level.uuid }}" class="btn btn-small btn-success" data-uuid="{{ level.uuid }}" style="float: right; margin-top: 5px; margin-right: 10px;">
<i class="fa fa-fw fa-unlock"></i>
{{_("Lock")}}&nbsp;
</a>
{% end %}
<div style="padding-left: 3px; margin-bottom: -10px;">
{% if level._name and level._name != level.name %}<strong>{{ _("Level") }} #{{ level.number }}</strong>&nbsp;&nbsp;&ndash;&nbsp;{% end %}
{% if level.type == "hidden" %}
Expand Down
19 changes: 17 additions & 2 deletions templates/admin/view/game_objects.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
{% from models.Flag import FLAG_CHOICE %}
{% from models.FlagChoice import FlagChoice %}
{% set avatars = filter_avatars("box") %}
<!-- Lock Corp Form -->
<form id="lock-corp-form" action="/admin/lock/corp" method="post">
{% raw xsrf_form_html() %}
<input id="lock-corp-uuid" name="uuid" type="hidden" />
</form>
<!-- Lock Box Form -->
<form id="lock-box-form" action="/admin/lock/box" method="post">
{% raw xsrf_form_html() %}
Expand Down Expand Up @@ -746,11 +751,22 @@ <h4 class="alert-heading">{{_("ERROR")}}</h4>
{% end %}
{% if len(Corporation.all()) > 0 %}
{% for corp_index, corporation in enumerate(Corporation.all()) %}
<div id="{{ corporation.uuid }}" class="well">
<div id="{{ corporation.uuid }}" class="well{% if corporation.locked %} locked{% end %}">
<h2 style="display:inline;">
<i class="fa fa-fw fa-building-o"></i>
{{ corporation.name }}&nbsp;&nbsp;
</h2>
{% if corporation.locked %}
<a id="lock-corp-button-{{ corporation.uuid }}" class="btn btn-small btn-warning" data-uuid="{{ corporation.uuid }}">
<i class="fa fa-fw fa-lock"></i>
{{_("Unlock")}}&nbsp;
</a>
{% else %}
<a id="lock-corp-button-{{ corporation.uuid }}" class="btn btn-small btn-success" data-uuid="{{ corporation.uuid }}">
<i class="fa fa-fw fa-unlock"></i>
{{_("Lock")}}&nbsp;
</a>
{% end %}
<a id="edit-corporation-button{{ corp_index }}" class="btn btn-small" data-toggle="modal" href="#edit-corporation-modal" data-uuid="{{ corporation.uuid }}">
<i class="fa fa-fw fa-pencil"></i>
{{_("Edit Corporation")}}
Expand Down Expand Up @@ -1047,7 +1063,6 @@ <h4 style="display:inline;">
</div>
<!-- End IPs -->
</div>
<br />
{% end %}
{% else %}
<strong>{{_("No boxes in this corporation yet")}}, <a href="/admin/create/box">{{_("add some")}}</a></strong>
Expand Down
Loading

0 comments on commit 5e58c94

Please sign in to comment.