adding validated services? patching forcad_local.py

This commit is contained in:
Your Name
2026-08-13 08:32:35 +07:00
parent d485f61169
commit e795614e45
1459 changed files with 420036 additions and 436 deletions

Submodule OmCTF-2025 deleted from f47bf201f3

6
OmCTF-2025/README.md Normal file
View File

@@ -0,0 +1,6 @@
# OmCTF 2025
![](images/scoreboard.png)
## Train AD 31/05/2026
![](images/scoreboard-train-31_05_26.png)

View File

@@ -0,0 +1,9 @@
tasks:
- name: bashist
checker: bashist/checker.py
default_score: ???
checker_timeout: 30
puts: 2
gets: 2
places: 2
checker_type: pfr

View File

@@ -0,0 +1,224 @@
#!/usr/bin/env python3
import json
import random
import secrets
import sys
from typing import List, NamedTuple
import checklib
import requests
class PrivatePost(NamedTuple):
content: str
private: bool = True
class PublicPost(NamedTuple):
username: str
content: str
def random_username() -> str:
if random.random() < 0.8:
return checklib.rnd_username()
return checklib.rnd_string(5 + secrets.randbelow(20))
def random_password() -> str:
if random.random() < 0.8:
return checklib.rnd_password()
return checklib.rnd_string(5 + secrets.randbelow(20))
def minidumps(data) -> str:
return json.dumps(data, separators=(",", ":"), sort_keys=True)
class Checker(checklib.BaseChecker):
def __init__(self, host: str):
super().__init__(host)
port = 1599
self.host_with_port = f"{self.host}:{port}"
self.url = f"http://{self.host_with_port}"
def action(self, action, *args, **kwargs):
try:
super().action(action, *args, **kwargs)
except self.get_check_finished_exception():
raise
except requests.RequestException as e:
self.cquit(
checklib.Status.DOWN, "Connection error", f"Requests error {repr(e)}"
)
def random_new_user(self) -> tuple[str, str, requests.Session]:
sess = self.get_initialized_session()
username = random_username()
password = random_password()
r = sess.post(
f"{self.url}/api/user/register",
json={"username": username, "password": password},
)
self.assert_(r.ok, f"Could not register: {r.status_code=} {r.text=}")
return username, password, sess
def check_if_user_exists(self, username: str):
r = requests.get(f"{self.url}/api/users")
self.assert_(r.ok, f"Could not list users: {r.status_code=} {r.text=}")
users = self.get_json(r, f"Invalid GET /api/users response json: {r.text=}")
self.assert_in(
{"username": username},
users,
f"Expected {username=} in GET /api/users response: {r.text=}",
)
def login(self, username: str, password: str) -> requests.Session:
sess = self.get_initialized_session()
r = sess.post(
f"{self.url}/api/user/login",
json={"username": username, "password": password},
)
self.assert_(r.ok, f"Could not login: {r.status_code=} {r.text=}")
return sess
def create_post(
self,
sess: requests.Session,
content: str,
is_private: bool = True,
):
r = sess.post(
f"{self.url}/api/post/new",
json={"content": content, "private": is_private},
)
self.assert_(
r.ok,
f"Could not create post with {content=} and {is_private=}: {r.status_code=} {r.text=}",
)
def list_user_posts(self, sess: requests.Session) -> List[PrivatePost]:
r = sess.get(f"{self.url}/api/user/posts")
self.assert_(
r.ok,
f"Could not list user's posts: {r.status_code=} {r.text=}",
)
posts = []
data = self.get_json(r, f"Invalid GET /api/user/posts json: {r.text=}")
for value in data:
post = PrivatePost(value["content"], value["private"])
posts.append(post)
return posts
def list_all_posts(self) -> List[PublicPost]:
sess = self.get_initialized_session()
r = sess.get(f"{self.url}/api/posts")
self.assert_(
r.ok,
f"Could not list all posts: {r.status_code=} {r.text=}",
)
posts = []
data = self.get_json(r, f"Invalid GET /api/user/posts json: {r.text=}")
for value in data:
post = PublicPost(value["username"], value["content"])
posts.append(post)
return posts
def check(self):
username, password, sess = self.random_new_user()
self.check_if_user_exists(username)
sess = self.login(username, password)
content = checklib.rnd_string(5 + secrets.randbelow(40))
is_private = True
self.create_post(sess, content, is_private)
posts = self.list_user_posts(sess)
post = PrivatePost(content=content)
self.assert_in(
post,
posts,
f"Expected {post=} in private posts {posts=}",
checklib.Status.CORRUPT,
)
content = checklib.rnd_string(5 + secrets.randbelow(40))
is_private = False
self.create_post(sess, content, is_private)
posts = self.list_all_posts()
post = PublicPost(username=username, content=content)
self.assert_in(
post,
posts,
f"Expected {post=} in public posts {posts=}",
checklib.Status.CORRUPT,
)
static_file = random.choice(
[
"index.html",
"login.html",
"newpost.html",
"posts.html",
"register.html",
"userposts.html",
]
)
r = sess.get(f"{self.url}/{static_file}")
self.assert_(
r.ok,
f"Could not get static file - {static_file}: {r.status_code=} {r.text=}",
)
self.cquit(checklib.Status.OK)
def put(self, flag_id: str, flag: str, vuln: str):
username, password, sess = self.random_new_user()
self.create_post(sess, flag, True)
self.cquit(checklib.Status.OK, private=minidumps((username, password)))
def get(self, flag_id: str, flag: str, _: str):
username, password = json.loads(flag_id)
sess = self.login(username, password)
posts = self.list_user_posts(sess)
post = PrivatePost(content=flag)
self.assert_in(
post,
posts,
f"Expected {post=} in private posts {posts=}",
checklib.Status.CORRUPT,
)
self.cquit(checklib.Status.OK)
if __name__ == "__main__":
host = sys.argv[2]
checker = Checker(host)
try:
action = sys.argv[1]
arguments = sys.argv[3:]
checker.action(action, *arguments)
except checker.get_check_finished_exception():
checklib.cquit(checklib.Status(checker.status), checker.public, checker.private)

View File

@@ -0,0 +1,9 @@
tasks:
- name: block-game
checker: block-game/checker.py
default_score: ???
checker_timeout: 30
puts: 2
gets: 2
places: 2
checker_type: pfr

View File

@@ -0,0 +1,498 @@
#!/usr/bin/env python3
import hashlib
import sys
import secrets
import json
import checklib
import requests
import random
import websockets
import websockets.sync.client
from requests.cookies import get_cookie_header
import level_gen
def random_str(prefix="") -> str:
if random.random() < 0.1:
return prefix + "Hello world"
elif random.random() < 0.1:
return prefix + "How are you?"
elif random.random() < 0.1:
return prefix + "I'm fine"
elif random.random() < 0.1:
return prefix + "Super secret communication"
elif random.random() < 0.1:
return prefix + "There are flags I want to send you"
else:
return prefix + checklib.rnd_string(5 + secrets.randbelow(40))
def random_username() -> str:
if random.random() < 0.8:
return checklib.rnd_username()
return checklib.rnd_string(5 + secrets.randbelow(20))
def random_password() -> str:
if random.random() < 0.8:
return checklib.rnd_password()
return checklib.rnd_string(5 + secrets.randbelow(20))
def random_level_name(hint = "") -> str:
x = random.random()
if x < 0.33:
return checklib.rnd_string(5 + secrets.randbelow(20)) + "_" + hint
elif x < 0.66:
return checklib.rnd_string(5 + secrets.randbelow(20)) + "_" + hint + "_" + checklib.rnd_string(5 + secrets.randbelow(20))
else:
return hint + "_" + checklib.rnd_string(5 + secrets.randbelow(20))
def random_description(hint = "") -> str:
strings = [checklib.rnd_string(5 + secrets.randbelow(20)) for _ in range(random.randrange(1, 3))]
strings.insert(random.randrange(len(strings)), hint)
return "\n".join(strings)
def random_prize(hint = "") -> str:
x = random.random()
if x < 0.33:
return "youre " + checklib.rnd_string(5 + secrets.randbelow(20)) + " cool"
if x < 0.66:
return "secret secret " +checklib.rnd_string(5 + secrets.randbelow(20))
return "my promocode: " + checklib.rnd_string(5 + secrets.randbelow(20))
def minidumps(data) -> str:
return json.dumps(data, separators=(",", ":"), sort_keys=True)
def jsonhash(data: dict) -> str:
return hashlib.sha256(minidumps(data).encode()).hexdigest()
class Checker(checklib.BaseChecker):
vulns = 2
timeout = 60
uses_attack_data: bool = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
port = 5874
self.host_with_port = f"{self.host}:{port}"
self.url = f"http://{self.host_with_port}"
def action(self, action, *args, **kwargs):
try:
super().action(action, *args, **kwargs)
except self.get_check_finished_exception():
raise
except requests.RequestException as e:
self.cquit(
checklib.Status.DOWN, "Connection error", f"Requests error {repr(e)}"
)
def check_whoami(self, sess: requests.Session, username: str):
r = sess.get(f"{self.url}/api/user")
self.assert_(
r.ok, f"Could not get whoami after registering: {r.status_code=} {r.text=}"
)
data = self.get_json(r, f"Invalid json in whoami response: {r.text=}")
self.assert_("id" in data, f"Invalid whoami response: no id, {r.text=}")
self.assert_(
"username" in data, f"Invalid whoami response: no username, {r.text=}"
)
self.assert_(
data["username"] == username,
f"Invalid whoami response: username mismatch, {r.text=}",
)
def random_new_user(self) -> tuple[str, str, requests.Session]:
sess = self.get_initialized_session()
username = random_username()
password = random_password()
r = sess.post(
f"{self.url}/api/auth/register",
json={
"username": username,
"password": password,
},
)
self.assert_(r.ok, f"Could not register: {r.status_code=} {r.text=}")
self.check_whoami(sess, username)
return username, password, sess
def login(
self,
username: str,
password: str,
check_whoami: bool = True,
error_status: checklib.Status = checklib.Status.MUMBLE,
) -> requests.Session:
sess = self.get_initialized_session()
r = sess.post(
f"{self.url}/api/auth/login",
json={
"username": username,
"password": password,
},
)
self.assert_(r.ok, f"Could not login: {r.status_code=} {r.text=}", error_status)
if check_whoami:
self.check_whoami(sess, username)
return sess
def get_level_list(
self,
sess: requests.Session,
checker_status: checklib.Status = checklib.Status.MUMBLE,
) -> list:
r = sess.get(f"{self.url}/api/user/levels?page=0")
self.assert_(
r.ok,
f"Could not get level list: {r.status_code=} {r.text=}",
checker_status,
)
data = self.get_json(
r, f"Invalid json in level list: {r.text=}", checker_status
)
self.assert_(
isinstance(data, list),
f"Invalid level list: not a list, {r.text=}",
checker_status,
)
return data
def verify_level(self, level: dict):
self.assert_(
isinstance(level, dict), f"Level data {level} is invalid: expected dict"
)
self.assert_(
"id" in level and isinstance(level["id"], int),
f"Level data {level} is invalid: expected id of type int",
)
self.assert_(
"name" in level and isinstance(level["name"], str),
f"Level data {level} is invalid: expected name of type str",
)
self.assert_(
"description" in level and isinstance(level["description"], str),
f"Level data {level} is invalid: expected description of type str",
)
self.assert_(
"visibility" in level and level["visibility"] in ("private", "public"),
f"Level data {level} is invalid: expected visibility 'private' or 'public'",
)
return True
def get_level_by_name(
self,
sess: requests.Session,
name: str,
not_found_status: checklib.Status = checklib.Status.MUMBLE,
) -> dict:
r = sess.get(f"{self.url}/api/user/level", params={"name": name})
if r.status_code == 404:
self.assert_(
False,
f"Level {name=} not found via search",
not_found_status,
)
self.assert_(
r.ok,
f"Could not search level by name: {r.status_code=} {r.text=}",
not_found_status,
)
level_data = self.get_json(
r, f"Invalid json in level search response: {r.text=}", not_found_status
)
self.verify_level(level_data)
self.assert_eq(level_data["name"], name, f"{level_data['name']=} mismatch")
return level_data
def check_level_saved(
self,
sess: requests.Session,
name: str,
description: str,
visibility: str,
data: dict,
prize: str = None,
):
level_list_data = self.get_level_by_name(sess, name)
level_id = level_list_data["id"]
self.assert_eq(
level_list_data["name"], name, f"{level_list_data['name']=} mismatch"
)
self.assert_eq(
level_list_data["description"],
description,
f"{level_list_data['description']=} mismatch",
)
self.assert_eq(
level_list_data["visibility"],
visibility,
f"{level_list_data['visibility']=} mismatch",
)
r = sess.get(f"{self.url}/api/user/level/{level_id}")
level_data = self.get_json(r, f"Invalid json in level data: {r.text}")
self.verify_level(level_data)
self.assert_(
"data" in level_data,
f"Level data {level_data} is invalid: expected level data",
)
self.assert_eq(level_data["name"], name, f"{level_data['name']=} mismatch")
self.assert_eq(
level_data["description"],
description,
f"{level_data['description']=} mismatch",
)
self.assert_eq(
level_data["visibility"],
visibility,
f"{level_data['visibility']=} mismatch",
)
self.assert_eq(level_data["data"], data, f"{level_data['data']=} mismatch")
if prize is not None:
self.assert_(
"prize" in level_data and isinstance(level_data["prize"], str),
f"Level data {level_data} is invalid: expected prize of type string",
)
self.assert_eq(
level_data["prize"], prize, f"{level_data['data']=} mismatch"
)
def put(self, flag_id: str, flag: str, vuln: str):
username, password, sess = self.random_new_user()
try:
vuln = int(vuln)
except ValueError as e:
raise ValueError(f"Invalid {vuln=}, expected a number") from e
if vuln == 1:
tiles_data = level_gen.generate_unbeatable()
level_name = f"unbeatable_FLAG_by_{username}_{secrets.token_hex(4)}"
description = "Win to get the FLAG. This level is impossible to beat!!"
visibility = "public"
elif vuln == 2:
tiles_data, _ = level_gen.generate_easy()
level_name = f"private_FLAG_by_{username}_{secrets.token_hex(4)}"
description = "Win to get the FLAG"
visibility = "private"
else:
raise ValueError(f"Invalid {vuln=}, expected 1 or 2")
r = sess.post(
f"{self.url}/api/user/level",
json={
"name": level_name,
"description": description,
"visibility": visibility,
"data": tiles_data,
"prize": flag,
},
)
self.assert_(r.ok, f"Could not create the level: {r.status_code=} {r.text=}")
self.check_level_saved(
sess, level_name, description, visibility, tiles_data, flag
)
tiles_data_hash = jsonhash(tiles_data)
self.cquit(
checklib.Status.OK,
public=minidumps({"level_name": level_name}),
private=minidumps((username, password, level_name, visibility, tiles_data_hash)),
)
def get(self, flag_id: str, flag: str, vuln: str):
username, password, level_name, visibility, tiles_data_hash = json.loads(flag_id)
sess = self.login(
username, password, check_whoami=False, error_status=checklib.Status.CORRUPT
)
level_list_data = self.get_level_by_name(
sess, level_name, not_found_status=checklib.Status.CORRUPT
)
r = sess.get(f"{self.url}/api/user/level/{level_list_data['id']}")
level_data = self.get_json(r, f"Invalid json in level data: {r.text}")
self.verify_level(level_data)
self.assert_(
"prize" in level_data and isinstance(level_data["prize"], str),
f"Level data {level_data} is invalid: expected prize of type string",
)
self.assert_eq(
level_data["prize"], flag, "Flag mismatch", checklib.Status.CORRUPT
)
self.assert_(
"data" in level_data,
f"Level data {level_data} is invalid: expected tiles data",
)
actual_tiles_data_hash = jsonhash(level_data["data"])
self.assert_eq(tiles_data_hash, actual_tiles_data_hash, "Flag level contents changed", checklib.Status.CORRUPT)
self.assert_eq(visibility, level_data["visibility"], "Flag level visibility changed", checklib.Status.CORRUPT)
self.cquit(checklib.Status.OK)
def check_user_search(self, sess, username):
r = sess.post(f"{self.url}/api/user", json={"username": username})
data = self.get_json(r, f"Invalid POST /api/user response json: {r.text}")
self.assert_in("username", data, f"Expected username in POST /api/user response: {r.text}")
self.assert_eq(data["username"], username, f"Expected {username=}: {r.text}")
self.assert_in("id", data, f"Expected id in POST /api/user response: {r.text}")
id = data["id"]
r = sess.post(f"{self.url}/api/user", json={"id": id})
data = self.get_json(r, f"Invalid POST /api/user response json: {r.text}")
self.assert_in("username", data, f"Expected username in POST /api/user response: {r.text}")
self.assert_eq(data["username"], username, f"Expected {username=}: {r.text}")
self.assert_in("id", data, f"Expected id in POST /api/user response: {r.text}")
self.assert_eq(data["id"], id, f"Expected {id=}: {r.text}")
def get_level_data(self, sess, id):
r = sess.get(f"{self.url}/api/user/level/{id}")
level_data = self.get_json(r, f"Invalid json in level data: {r.text}")
self.verify_level(level_data)
return level_data
def connect_with_auth(self, sess: requests.Session, url):
cookie_value = get_cookie_header(sess.cookies, requests.Request("GET", url.replace("ws://", "http://")))
return websockets.sync.client.connect(url, additional_headers={"Cookie": cookie_value})
def recv_message(self, sock, timeout):
try:
m = sock.recv(timeout)
except TimeoutError:
return False
except websockets.exceptions.ConnectionClosedError:
return False
try:
m = json.loads(m)
except json.JSONDecodeError:
self.assert_(False, f"Invalid websocket message: {m}")
if "type" in m and m["type"] == "level_complete":
self.assert_in("option", m, f"Invalid level_complete: {m}")
self.assert_in("prize", m["option"], f"Invalid level_complete: {m}")
return m["option"]["prize"]
return True
def play_level(self, sess, id, moves = [], expect_prize = False, expect_updates = False):
got_updates = False
with self.connect_with_auth(sess, f"ws://{self.host_with_port}/api/user/level/{id}/play") as sock:
for move in moves:
sock.send(json.dumps({"type": "move", "option": {"direction": move}}))
while True:
timeout = 0.5 if expect_updates and not got_updates else 0.01
m = self.recv_message(sock, timeout)
if m == True: # noqa: E712
got_updates = True
elif m == False: # noqa: E712
break
else:
return m
while True:
timeout = 0.5 if expect_prize else 0.05
m = self.recv_message(sock, timeout)
if m == True: # noqa: E712
got_updates = True
elif m == False: # noqa: E712
break
else:
return m
self.assert_(not expect_prize, "Didn't get the prize")
self.assert_(got_updates or not expect_updates, "Didn't get any updates from the server")
def check(self):
username, password, sess = self.random_new_user()
self.check_user_search(sess, username)
r = sess.post(f"{self.url}/api/auth/logout")
self.assert_(r.ok, f"Couldn't logout: {r.text}")
r = sess.post(f"{self.url}/api/user/whoami")
self.assert_(not r.ok, f"Can access whoami after logout: {r.text}")
sess = self.login(username, password)
levels = self.get_level_list(sess)
if len(levels) > 0:
level = random.choice(levels)
data = self.get_level_data(sess, level["id"])
self.play_level(sess, data["id"])
if random.random() < 0.5:
tiles_data, moves = level_gen.generate_easy()
level_name = random_level_name("ez")
description = random_description("Easy level")
else:
tiles_data, moves = level_gen.generate_box_test()
level_name = random_level_name("box")
description = random_description("boxes boxes")
prize = random_prize()
r = sess.post(
f"{self.url}/api/user/level",
json={
"name": level_name,
"description": description,
"visibility": "public",
"data": tiles_data,
"prize": prize,
},
)
data = self.get_json(r, f"Invalid level creation response: {r.text}")
self.assert_in("id", data, f"Expected id after level creation: {r.text}")
id = data["id"]
got_prize = self.play_level(sess, id, moves, True, True)
self.assert_eq(prize, got_prize, f"Got wrong prize {got_prize}")
self.check_level_saved(sess, level_name, description, "public", tiles_data, prize)
username, password, sess = self.random_new_user()
got_prize = self.play_level(sess, id, moves, True, True)
self.assert_eq(prize, got_prize, f"Got wrong prize {got_prize}")
self.check_level_saved(sess, level_name, description, "public", tiles_data)
tiles_data, moves = level_gen.generate_box_test()
level_name = random_level_name("boxes_priv")
description = random_description("only mine level")
prize = random_prize()
r = sess.post(
f"{self.url}/api/user/level",
json={
"name": level_name,
"description": description,
"visibility": "private",
"data": tiles_data,
"prize": prize,
},
)
data = self.get_json(r, f"Invalid level creation response: {r.text}")
self.assert_in("id", data, f"Expected id after level creation: {r.text}")
id = data["id"]
self.check_level_saved(sess, level_name, description, "private", tiles_data, prize)
username, password, sess = self.random_new_user()
r = sess.get(f"{self.url}/api/user/level/{id}")
self.assert_(not r.ok, f"Successfully got private level data: {id} by {username}")
r = sess.get(f"{self.url}/api/user/level/{id}/play")
self.assert_(not r.ok, f"Successfully started playing private level: {id} played by {username}")
self.cquit(checklib.Status.OK)
if __name__ == "__main__":
host = sys.argv[2]
checker = Checker(host)
try:
action = sys.argv[1]
arguments = sys.argv[3:]
checker.action(action, *arguments)
except checker.get_check_finished_exception():
checklib.cquit(
checklib.Status(checker.status),
checker.public,
checker.private,
)

View File

@@ -0,0 +1,272 @@
import random
def is_good(walls, size, x, y) -> bool:
return 0 <= x < size and 0 <= y < size and ((x == 0 or walls[x - 1][y]) + (y == 0 or walls[x][y - 1]) + (x == size - 1 or walls[x + 1][y]) + (y == size - 1 or walls[x][y + 1]) >= 3)
def move_str2coord(move, x, y) -> tuple[int, int]:
if move == "left":
return x - 1, y
elif move == "up":
return x, y - 1
elif move == "right":
return x + 1, y
elif move == "down":
return x, y + 1
else:
raise ValueError()
def invert_move(move):
if move == "left":
return "right"
elif move == "up":
return "down"
elif move == "right":
return "left"
elif move == "down":
return "up"
else:
raise ValueError()
def generate_box_test() -> dict:
size = random.randint(5, 15)
tiles = []
winning_moves = []
walls = [[True] * size for _ in range(size)]
x, y = random.randrange(size), random.randrange(size)
starting_position = x, y
walls[x][y] = False
tiles.append({"kind": "player", "pos": {"x": x, "y": y}, "data": None})
while True:
moves = []
for move in ("left", "up", "right", "down"):
coords = move_str2coord(move, x, y)
if coords != starting_position and is_good(walls, size, *coords):
moves.append(move)
if len(moves) == 0:
break
move = random.choice(moves)
moves.remove(move)
x1, y1 = move_str2coord(move, x, y)
if len(moves) >= 1 and True:
other_move = random.choice(moves)
x2, y2 = move_str2coord(other_move, x, y)
x3, y3 = move_str2coord(other_move, x2, y2)
if is_good(walls, size, x3, y3):
walls[x2][y2] = False
walls[x3][y3] = False
tiles.append({"kind": "door", "pos": {"x": x1, "y": y1}, "data": {"button_position": {"x": x3, "y": y3}}})
tiles.append({"kind": "box", "pos": {"x": x2, "y": y2}, "data": None})
winning_moves.extend((other_move, invert_move(other_move)))
x, y = x1, y1
walls[x][y] = False
winning_moves.append(move)
tiles.append({"kind": "exit", "pos": {"x": x, "y": y}, "data": None})
for x in range(size):
for y in range(size):
if walls[x][y]:
tiles.append({"kind": "wall", "pos": {"x": x, "y": y}, "data": None})
# debug_level_print(size, tiles, winning_moves)
return {"size": size, "tiles": tiles}, winning_moves
def generate_easy():
size = random.randint(10, 20)
tiles = []
winning_moves = []
x1, y1 = random.randrange(size), random.randrange(size)
tiles.append({"kind": "player", "pos": {"x": x1, "y": y1}, "data": None})
while True:
x2, y2 = random.randrange(size), random.randrange(size)
if x1 != x2 or y1 != y2:
break
tiles.append({"kind": "exit", "pos": {"x": x2, "y": y2}, "data": None})
x, y = x1, y1
while x < x2:
winning_moves.append("right")
x += 1
while x > x2:
winning_moves.append("left")
x -= 1
while y < y2:
winning_moves.append("down")
y += 1
while y > y2:
winning_moves.append("up")
y -= 1
# debug_level_print(size, tiles, winning_moves)
return {"size": size, "tiles": tiles}, winning_moves
def generate_unbeatable():
size = 6
tiles = []
tiles = [
{
"kind": "wall",
"pos": {
"x": 1,
"y": 0
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 1,
"y": 1
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 1,
"y": 2
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 1,
"y": 3
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 1,
"y": 4
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 1,
"y": 5
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 2,
"y": 3
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 3,
"y": 3
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 4,
"y": 3
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 5,
"y": 3
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 4,
"y": 0
},
"data": None
},
{
"kind": "wall",
"pos": {
"x": 4,
"y": 1
},
"data": None
},
{
"kind": "door",
"pos": {
"x": 5,
"y": 1
},
"data": {
"button_position": {
"x": 2,
"y": 0
}
}
},
{
"kind": "box",
"pos": {
"x": 2,
"y": 1
},
"data": None
},
{
"kind": "exit",
"pos": {
"x": 5,
"y": 0
},
"data": None
}
]
x, y = random.randint(2, 5), random.randint(4, 5)
tiles.append({"kind": "player", "pos": {"x": x, "y": y}, "data": None})
x, y = 0, random.randrange(6)
tiles.append({"kind": "box", "pos": {"x": x, "y": y}, "data": None})
# debug_level_print(size, tiles)
return {"size": size, "tiles": tiles}
def debug_level_print(size, tiles, winning_moves = None):
if winning_moves:
print(winning_moves)
for y in range(size):
for x in range(size):
s = ""
for tile in tiles:
if tile["pos"]["x"] == x and tile["pos"]["y"] == y:
if tile["kind"] == "exit":
s = "00"
elif tile["kind"] == "player":
s = "<>"
elif tile["kind"] == "door":
s = "##"
elif tile["kind"] == "box":
s = "[]"
elif tile["kind"] == "wall":
s = s or "::"
elif tile["kind"] == "door" and tile["data"]["button_position"]["x"] == x and tile["data"]["button_position"]["y"] == y:
s = "xx"
s = s or " "
print(s, end="")
print()

View File

@@ -0,0 +1,370 @@
#!/usr/bin/env python3
import sys
import json
import time
import random
import requests
from typing import Optional
from checklib import *
from jform_lib import CheckMachine
class Checker(BaseChecker):
vulns: int = 1
timeout: int = 15
uses_attack_data: bool = True
def __init__(self, host: str):
super().__init__(host)
self.m = CheckMachine(self)
def _new_session(self) -> requests.Session:
return get_initialized_session()
def _require_json(self, r: requests.Response, where: str) -> dict:
self.assert_in("application/json", r.headers.get("Content-Type", ""), f"{where}: Content-Type is not JSON")
return self.get_json(r, f"{where}: malformed JSON")
def _extract_form_id(self, obj: dict) -> str:
form_id = obj.get("id") or obj.get("formId") or obj.get("_id")
self.assert_neq(None, form_id, "Service returned empty form id")
form_id = str(form_id)
self.assert_neq("", form_id, "Service returned empty form id")
return form_id
def _register_and_login(self, s: requests.Session):
username = rnd_username()
password = rnd_password()
r = self.m.register(s, username, password)
self.assert_eq(200, r.status_code, "Service /signup returned unexpected status code")
_ = self._require_json(r, "/signup")
r = self.m.login(s, username, password)
self.assert_eq(200, r.status_code, "Service /login returned unexpected status code")
_ = self._require_json(r, "/login")
r = self.m.me(s)
self.assert_eq(200, r.status_code, "Service /me returned unexpected status code")
me = self._require_json(r, "/me")
self.assert_in("username", me, "Service /me missing username")
self.assert_eq(me["username"], username, "Service /me returned wrong username")
self.assert_in("userId", me, "Service /me missing userId")
user_id = str(me["userId"])
self.assert_neq("", user_id, "Service /me returned empty userId")
return username, password, user_id
def _form_catalog(self):
return [
{
"title": "Обратная связь",
"description": "Короткий опрос о качестве сервиса",
"fields": [
{"name": "email_1", "type": "email", "label": "Email", "placeholder": "you@example.ru", "required": True},
{"name": "number_1", "type": "number", "label": "Оценка (1-10)", "placeholder": "10", "required": True},
{"name": "textarea_1", "type": "textarea", "label": "Комментарий", "placeholder": "Напишите пару слов", "required": False},
],
},
{
"title": "Заявка на работу",
"description": "Расскажите о себе",
"fields": [
{"name": "text_1", "type": "text", "label": "ФИО", "placeholder": "Иванов Иван", "required": True},
{"name": "email_1", "type": "email", "label": "Почта", "placeholder": "you@example.ru", "required": True},
{"name": "number_1", "type": "number", "label": "Опыт (лет)", "placeholder": "3", "required": True},
{"name": "textarea_1", "type": "textarea", "label": "Резюме (кратко)", "placeholder": "Ключевые навыки...", "required": False},
],
},
{
"title": "Регистрация на событие",
"description": "Подтвердите участие",
"fields": [
{"name": "text_1", "type": "text", "label": "Имя", "placeholder": "Ваше имя", "required": True},
{"name": "email_1", "type": "email", "label": "Email", "placeholder": "you@example.ru", "required": True},
{"name": "number_1", "type": "number", "label": "Количество гостей", "placeholder": "0", "required": False},
{"name": "text_2", "type": "text", "label": "Дата", "placeholder": "2025-10-05", "required": True},
],
},
{
"title": "Сообщить об ошибке",
"description": "Помогите нам стать лучше",
"fields": [
{"name": "text_1", "type": "text", "label": "Заголовок", "placeholder": "Коротко о проблеме", "required": True},
{"name": "select_1", "type": "select", "label": "Серьёзность", "options": ["Низкая", "Средняя", "Высокая"], "required": True},
{"name": "textarea_1", "type": "textarea", "label": "Шаги воспроизведения", "placeholder": "1) ... 2) ...", "required": True},
],
},
{
"title": "Заказ пиццы",
"description": "Соберите свою пиццу",
"fields": [
{"name": "select_1", "type": "select", "label": "Размер", "options": ["Маленькая", "Средняя", "Большая"], "required": True},
{"name": "text_1", "type": "text", "label": "Адрес", "placeholder": "Город, улица, дом", "required": True},
{"name": "select_2", "type": "select", "label": "Соус", "options": ["Томатный", "Сливочный", "Барбекю"], "required": False},
],
},
{
"title": "Опрос о цветах",
"description": "Пара вопросов о вкусе",
"fields": [
{"name": "number_1", "type": "number", "label": "Возраст", "placeholder": "25", "required": False},
{"name": "text_1", "type": "text", "label": "Любимый цвет", "placeholder": "синий", "required": True},
],
},
{
"title": "Мини-викторина",
"description": "Два коротких вопроса",
"fields": [
{"name": "text_1", "type": "text", "label": "Имя", "placeholder": "Ваше имя", "required": True},
{"name": "number_1", "type": "number", "label": "Сколько будет 2+2?", "placeholder": "4", "required": True},
{"name": "number_2", "type": "number", "label": "Сколько дней в неделе?", "placeholder": "7", "required": True},
],
},
{
"title": "Заявка в поддержку",
"description": "Опишите проблему",
"fields": [
{"name": "email_1", "type": "email", "label": "Email", "placeholder": "you@example.ru", "required": True},
{"name": "text_1", "type": "text", "label": "Тема", "placeholder": "Коротко", "required": True},
{"name": "textarea_1", "type": "textarea", "label": "Описание", "placeholder": "Что произошло?", "required": True},
],
},
{
"title": "Командировка",
"description": "Заявка на поездку",
"fields": [
{"name": "text_1", "type": "text", "label": "Откуда", "placeholder": "Москва", "required": True},
{"name": "text_2", "type": "text", "label": "Куда", "placeholder": "Санкт-Петербург", "required": True},
{"name": "text_3", "type": "text", "label": "Дата выезда", "placeholder": "2025-10-05", "required": True},
{"name": "text_4", "type": "text", "label": "Дата возврата", "placeholder": "2025-10-07", "required": False},
{"name": "number_1", "type": "number", "label": "Бюджет, ₽", "placeholder": "15000", "required": False},
],
},
{
"title": "Рецензия на книгу",
"description": "Поделитесь впечатлениями",
"fields": [
{"name": "text_1", "type": "text", "label": "Название", "placeholder": "Книга", "required": True},
{"name": "text_2", "type": "text", "label": "Автор", "placeholder": "Автор", "required": True},
{"name": "number_1", "type": "number", "label": "Оценка (1-10)", "placeholder": "8", "required": True},
{"name": "textarea_1", "type": "textarea", "label": "Отзыв", "placeholder": "Ваши мысли...", "required": False},
],
},
]
def _pick_schema(self, seed: int):
rng = random.Random(seed)
base = self._form_catalog()[rng.randrange(10)]
schema = {
"title": base["title"],
"description": base.get("description", ""),
"fields": [dict(f) for f in base["fields"]],
}
return schema, rng
def _make_flag_sentence(self, flag: str, rng: random.Random) -> str:
templates = [
"Сегодняшний код дня — {flag} — случайно появился в заметках.",
"Если что, подсказка спрятана так: {flag}.",
"Запомни шифр: {flag}, пригодится позже.",
"Пока никто не видит, оставлю тут {flag}.",
"Лозунг встречи: \"{flag}\" — без комментариев.",
"Пароль на вход: {flag}; не перепутай!",
"Метка для отчёта — {flag} — проверь внимательно.",
"Секретный ингредиент рецепта: {flag}.",
"В списке дел первым пунктом стоит {flag}.",
"На полях тетради выведено: {flag}.",
]
return rng.choice(templates).format(flag=flag)
def _make_valid_payload(self, schema: dict, username: str, rng: random.Random, flag: Optional[str] = None) -> dict:
def word(n=8):
letters = "абвгдеёжзийклмнопрстуфхцчшщэюя"
return "".join(rng.choice(letters) for _ in range(n))
email = f"{username}@example.ru"
text_like = [f for f in schema.get("fields", []) if f.get("type") in ("text", "textarea")]
flag_field_name = rng.choice(text_like)["name"] if (flag and text_like) else None
sentence = self._make_flag_sentence(flag, rng) if flag else None
payload = {}
for f in schema.get("fields", []):
t = f.get("type")
name = f.get("name")
req = bool(f.get("required"))
if name == flag_field_name and sentence is not None:
payload[name] = sentence
continue
if t == "email":
payload[name] = email
elif t == "number":
payload[name] = rng.randint(1, 100)
elif t == "textarea":
payload[name] = f"{word(6)} {word(6)} {word(6)} {word(6)}"
elif t == "select":
options = f.get("options") or []
payload[name] = rng.choice(options) if options else "Вариант 1"
else:
payload[name] = word(8) if req else word(5)
return payload
def check(self):
try:
s1 = self._new_session()
u1, p1, id1 = self._register_and_login(s1)
s2 = self._new_session()
u2, p2, id2 = self._register_and_login(s2)
try:
id1_i = int(id1); id2_i = int(id2)
except Exception as e:
self.cquit(Status.MUMBLE, "Service returned non-integer userId", str(e))
self.assert_eq(True, id2_i > id1_i, "Service produced incorrect userId ordering")
schema1, rng = self._pick_schema(seed=id2_i)
schema2, _ = self._pick_schema(seed=id2_i + 777)
r = self.m.create_form(s2, schema1)
self.assert_eq(200, r.status_code, "Service create_form returned unexpected status code")
created1 = self._require_json(r, "create_form #1")
form_id1 = self._extract_form_id(created1)
self.assert_in("formNumber", created1, "Service did not return formNumber on creation")
num1 = int(created1["formNumber"])
r = self.m.get_form(s2, form_id1)
self.assert_eq(200, r.status_code, "Service get_form returned unexpected status code")
gf1 = self._require_json(r, "get_form #1")
self.assert_eq(form_id1, str(gf1.get("id") or gf1.get("formId") or gf1.get("_id") or ""), "Service get_form returned wrong form id")
self.assert_eq(num1, int(gf1.get("formNumber")), "Service get_form returned wrong formNumber")
r = self.m.create_form(s2, schema2)
self.assert_eq(200, r.status_code, "Service create_form returned unexpected status code")
created2 = self._require_json(r, "create_form #2")
form_id2 = self._extract_form_id(created2)
self.assert_in("formNumber", created2, "Service did not return formNumber on creation")
num2 = int(created2["formNumber"])
self.assert_eq(True, num2 > num1, "Service produced non-increasing formNumber")
self.assert_neq(form_id1, form_id2, "Service assigned duplicate form identifiers")
r = self.m.get_my_forms(s2)
self.assert_eq(200, r.status_code, "Service get_my_forms returned unexpected status code")
my = self._require_json(r, "get_my_forms")
self.assert_eq(True, isinstance(my, list), "Service returned invalid forms list")
ids_in_list = {str(i.get("id") or i.get("formId") or i.get("_id") or "") for i in my if isinstance(i, dict)}
self.assert_in(form_id1, ids_in_list, "Service did not list previously created form #1")
self.assert_in(form_id2, ids_in_list, "Service did not list previously created form #2")
payload = self._make_valid_payload(schema2, username=u2, rng=random.Random(id2_i))
r = self.m.submit_form_response(s2, form_id2, payload)
self.assert_eq(200, r.status_code, "Service submit_form_response returned unexpected status code")
self._require_json(r, "submit_form_response")
r = self.m.get_form_results(s2, form_id2)
self.assert_eq(200, r.status_code, "Service get_form_results returned unexpected status code")
res_after = self._require_json(r, "get_form_results after submit")
self.assert_eq(True, isinstance(res_after, list), "Service returned invalid results list")
self.assert_eq(True, len(res_after) >= 1, "Service did not persist submitted response")
self.cquit(Status.OK)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
self.cquit(Status.DOWN, "Service is down or unreachable", str(e))
def put(self, flag_id: str, flag: str, vuln: str):
try:
s = self._new_session()
username, password, user_id = self._register_and_login(s)
user_id_int = int(user_id)
schema, rng = self._pick_schema(seed=user_id_int)
r = self.m.create_form(s, schema)
self.assert_eq(200, r.status_code, "Service create_form returned unexpected status code")
created = self._require_json(r, "create_form")
form_id = self._extract_form_id(created)
self.assert_in("formNumber", created, "Service did not return formNumber on creation")
_ = int(created["formNumber"])
payload = self._make_valid_payload(schema, username=username, rng=rng, flag=flag)
r = self.m.submit_form_response(s, form_id, payload)
self.assert_eq(200, r.status_code, "Service submit_form_response returned unexpected status code")
_ = self._require_json(r, "submit_form_response")
public = json.dumps({"userId": user_id, "username": username})
private = json.dumps({"username": username, "password": password, "form_id": form_id})
self.cquit(Status.OK, public, private)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
self.cquit(Status.DOWN, "Service is down or unreachable", str(e))
def get(self, flag_id: str, flag: str, vuln: str):
try:
s = self._new_session()
try:
blob = json.loads(flag_id)
except Exception as e:
self.cquit(Status.CORRUPT, "Invalid private data", str(e))
if isinstance(blob, dict) and {"username", "password", "form_id"} <= set(blob.keys()):
priv = blob
elif isinstance(blob, dict) and isinstance(blob.get("private"), dict):
priv = blob["private"]
else:
self.cquit(Status.CORRUPT, "Missing auth and form_id fields", f"got: {sorted(blob.keys()) if isinstance(blob, dict) else type(blob)}")
username = priv.get("username")
password = priv.get("password")
form_id = str(priv.get("form_id") or "")
self.assert_eq(True, all([username, password, form_id]), "Missing required fields to access form")
r = self.m.login(s, username, password)
self.assert_eq(200, r.status_code, "Service /login returned unexpected status code")
_ = self._require_json(r, "/login (GET)")
r = self.m.get_form_results(s, form_id)
self.assert_eq(200, r.status_code, "Service get_form_results returned unexpected status code")
res = self._require_json(r, "get_form_results (GET)")
self.assert_eq(True, isinstance(res, list), "Service returned invalid results list")
def contains_flag(obj) -> bool:
if isinstance(obj, str):
if flag in obj:
return True
try:
inner = json.loads(obj)
except Exception:
return False
return contains_flag(inner)
if isinstance(obj, dict):
for k in ("response", "data", "payload", "answers"):
if k in obj and contains_flag(obj[k]):
return True
for v in obj.values():
if contains_flag(v):
return True
return False
if isinstance(obj, list):
for v in obj:
if contains_flag(v):
return True
return False
return False
found = any(contains_flag(item) for item in res)
self.assert_eq(True, found, "Service does not return previously submitted data (flag not found)")
self.cquit(Status.OK)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
self.cquit(Status.DOWN, "Service is down or unreachable", str(e))
if __name__ == '__main__':
c = Checker(sys.argv[2])
try:
c.action(sys.argv[1], *sys.argv[3:])
except c.get_check_finished_exception():
cquit(Status(c.status), c.public, c.private)

View File

@@ -0,0 +1,54 @@
import requests
import json
from checklib import *
PORT = 5003
class CheckMachine:
@property
def url(self):
return f"http://{self.c.host}:{self.port}"
def __init__(self, checker: BaseChecker):
self.port = PORT
self.c = checker
def register(self, session: requests.Session, username: str, password: str):
data = {"username": username, "password": password}
headers = {"Content-Type": "application/json"}
return session.post(f"{self.url}/api/account/signup", data=json.dumps(data), headers=headers)
def login(self, session: requests.Session, username: str, password: str):
data = {"username": username, "password": password}
headers = {"Content-Type": "application/json"}
return session.post(f"{self.url}/api/account/login", data=json.dumps(data), headers=headers)
def me(self, session: requests.Session):
return session.get(f"{self.url}/api/account/me")
def logout(self, session: requests.Session):
headers = {"Content-Type": "application/json"}
return session.post(f"{self.url}/api/account/logout", data=json.dumps({}), headers=headers)
def create_form(self, session: requests.Session, schema: dict):
data = {"schema": schema}
headers = {"Content-Type": "application/json"}
return session.post(f"{self.url}/api/form/new", data=json.dumps(data), headers=headers)
def get_form(self, session: requests.Session, form_id: str):
return session.get(f"{self.url}/api/form/{form_id}")
def update_form(self, session: requests.Session, form_id: str, schema: dict):
data = {"schema": schema}
headers = {"Content-Type": "application/json"}
return session.put(f"{self.url}/api/form/{form_id}/update", data=json.dumps(data), headers=headers)
def submit_form_response(self, session: requests.Session, form_id: str, payload: dict):
headers = {"Content-Type": "application/json"}
return session.post(f"{self.url}/api/form/{form_id}/submit", data=json.dumps(payload), headers=headers)
def get_my_forms(self, session: requests.Session):
return session.get(f"{self.url}/api/form/my-forms")
def get_form_results(self, session: requests.Session, form_id: str):
return session.get(f"{self.url}/api/form/{form_id}/results")

View File

@@ -0,0 +1,776 @@
#!/usr/bin/env python3
import os
import random
import sys
from typing import Any, Dict, List, Optional, Tuple
sys.path.append(os.path.join(os.path.dirname(__file__), "checklib"))
from checklib import ( # type: ignore
BaseChecker,
Status,
cquit,
rnd_password,
rnd_string,
rnd_username,
)
import requests
class PolyphoniaChecker(BaseChecker):
vulns = 1
timeout = 10
def __init__(self, host: str):
super().__init__(host)
self._base_url = self._build_base_url()
# ========== public API required by BaseChecker ==========
def check(self):
"""Perform a realistic user flow with varied actions.
Adds human-like behavior: listing tones, creating/editing/deleting
tones and melodies, and verifying backend state using checklib asserts.
"""
username, password = self._credentials()
# Prepare a target melody we will later verify
target_melody_name = self._humanish_name(unique=True)
target_description = self._humanish_description()
session = self.get_initialized_session()
try:
self._register(session, username, password)
self._login(session, username, password)
# 1) Tone library lifecycle: list -> create -> verify -> edit -> verify -> delete -> verify
tones_initial = self._list_tones(session)
self.assert_eq(len(tones_initial), 0, "New user must have empty tone library")
# Create 2-3 tones
created_tones: List[Dict[str, Any]] = []
for _ in range(random.randint(2, 3)):
tone_payload = self._tone_sequence_payload(include_name=True)
tone_id = self._save_tone_sequence(session, tone_payload)
tone_payload_copy = dict(tone_payload)
tone_payload_copy["id"] = tone_id
created_tones.append(tone_payload_copy)
# Verify created tones via listing
tones_after_create = self._list_tones(session)
for t in created_tones:
found = self._find_tone_by_name(tones_after_create, t["name"])
self.assert_(found is not None, f"Tone not found after create: {t['name']}")
self._assert_tone_matches_expected(t, found, "Tone mismatch after create")
# Edit the second tone (if exists) by re-saving with same name and changed fields
if len(created_tones) >= 2:
original = created_tones[1]
updated = dict(original)
# Change a few musically-reasonable fields
updated["tempo"] = random.choice([100, 110, 128, 140])
updated["duration"] = random.choice([1, 2, 3, 4])
updated["chordType"] = random.choice(["major", "minor", "sus2", "none"])
updated["intervalType"] = random.choice(["unison", "third", "fifth"])
# Rebuild notes a bit
bn = updated["baseNote"] = max(36, min(84, updated.get("baseNote", 60) + random.choice([-2, -1, 1, 2])))
updated["notes"] = [bn, bn + (3 if updated["chordType"] == "minor" else 4), bn + 7]
# Save with same name to trigger upsert
payload_for_update = {k: updated[k] for k in [
"name", "description", "baseNote", "intervalType", "chordType", "tempo", "duration", "notes"
]}
tone_id_after = self._update_tone_sequence(session, payload_for_update)
self.assert_eq(tone_id_after, original["id"], "Tone ID changed after update")
# Verify the update via listing
tones_after_update = self._list_tones(session)
found = self._find_tone_by_name(tones_after_update, updated["name"])
self.assert_(found is not None, "Updated tone not found in list")
self._assert_tone_matches_expected(updated, found, "Tone mismatch after update")
# Update our local state
created_tones[1] = updated
# Delete the first tone and verify it's gone
to_delete = created_tones[0]
self._delete_tone(session, to_delete["id"])
tones_after_delete = self._list_tones(session)
self.assert_(self._find_tone_by_name(tones_after_delete, to_delete["name"]) is None, "Tone still present after delete")
# Keep the expected list in sync
created_tones = [t for t in created_tones if t["id"] != to_delete["id"]]
# Additional messy randomized tone ops with checks after each
ops = random.randint(2, 4)
for _ in range(ops):
action = random.choice(["create", "edit", "delete", "noop"])
if action == "create":
p = self._tone_sequence_payload(include_name=True)
tid = self._save_tone_sequence(session, p)
pcopy = dict(p)
pcopy["id"] = tid
created_tones.append(pcopy)
elif action == "edit" and created_tones:
idx = random.randrange(len(created_tones))
original = created_tones[idx]
updated = dict(original)
updated["tempo"] = random.choice([90, 110, 120, 140])
updated["duration"] = random.choice([1, 2, 3, 4])
# Nudge base note slightly and rebuild notes (triad)
bn = updated["baseNote"] = max(36, min(84, updated.get("baseNote", 60) + random.choice([-2, 0, 2])))
updated["notes"] = [bn, bn + (3 if updated.get("chordType") == "minor" else 4), bn + 7]
payload_for_update = {k: updated[k] for k in [
"name", "description", "baseNote", "intervalType", "chordType", "tempo", "duration", "notes"
]}
tid_after = self._update_tone_sequence(session, payload_for_update)
self.assert_eq(tid_after, original["id"], "Tone ID changed after random edit")
created_tones[idx] = updated
elif action == "delete" and created_tones:
idx = random.randrange(len(created_tones))
victim = created_tones.pop(idx)
self._delete_tone(session, victim["id"])
# After each action, list and verify full set matches expectation
listed_now = self._list_tones(session)
self._assert_tone_sets_match(created_tones, listed_now, "Tone set mismatch after op")
# 2) Create multiple melodies with more variety, then edit+delete one
total_melodies = random.randint(2, 4)
idx_target = random.randrange(total_melodies)
melodies_expected: Dict[str, Dict[str, Any]] = {}
for i in range(total_melodies):
if i == idx_target:
name = target_melody_name
description = target_description
else:
name = self._humanish_name(unique=True)
description = self._humanish_description()
seq_count = random.randint(1, 4)
seqs = [self._tone_sequence_payload(include_name=False) for _ in range(seq_count)]
mid = self._create_melody(session, name, description, tone_sequences=seqs)
melodies_expected[name] = {"id": mid, "description": description}
# Edit a non-target melody if possible: change its description and sequences
editable = [n for n in melodies_expected.keys() if n != target_melody_name]
if editable:
mname = random.choice(editable)
new_desc = self._humanish_description()
new_seqs = [self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))]
mid_before = melodies_expected[mname]["id"]
mid_after = self._update_melody(session, mname, new_desc, tone_sequences=new_seqs)
self.assert_eq(mid_after, mid_before, "Melody ID changed after update")
melodies_expected[mname]["description"] = new_desc
# 3) Basic profile + library checks
profile = self._get_profile(session)
self.assert_eq(profile.get("username"), username, "Broken user info")
melodies = self._list_melodies(session)
melody = self._find_melody(melodies, target_melody_name)
self.assert_(melody is not None, "Saved melody not found")
self.assert_eq(melody.get("description"), target_description, "Melody description mismatch")
# 4) Optionally delete a non-target melody and verify
if editable:
del_name = mname
del_id = melodies_expected[del_name]["id"]
self._delete_melody(session, del_id)
melodies_after_del = self._list_melodies(session)
self.assert_(self._find_melody(melodies_after_del, del_name) is None, "Melody still present after delete")
melodies_expected.pop(del_name, None)
# 5) Do a few messy randomized melody ops with checks after each
more_ops = random.randint(1, 3)
for _ in range(more_ops):
op = random.choice(["create", "edit", "delete", "noop"])
current_names = list(melodies_expected.keys())
non_target = [n for n in current_names if n != target_melody_name]
if op == "create":
n = self._humanish_name(unique=True)
d = self._humanish_description()
seqs = [self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))]
mid = self._create_melody(session, n, d, tone_sequences=seqs)
melodies_expected[n] = {"id": mid, "description": d}
elif op == "edit" and non_target:
n = random.choice(non_target)
d = self._humanish_description()
seqs = [self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))]
before_id = melodies_expected[n]["id"]
after_id = self._update_melody(session, n, d, tone_sequences=seqs)
self.assert_eq(after_id, before_id, "Melody ID changed after edit")
melodies_expected[n]["description"] = d
elif op == "delete" and non_target:
n = random.choice(non_target)
self._delete_melody(session, melodies_expected[n]["id"])
melodies_expected.pop(n, None)
# After each op, list and verify set matches expected
listed = self._list_melodies(session)
self._assert_melody_sets_match_expected(melodies_expected, listed, "Melody set mismatch after op")
except requests.RequestException as exc:
self.cquit(Status.DOWN, "Connection error", str(exc))
self.cquit(Status.OK)
def put(self, flag_id: str, flag: str, vuln: str):
"""Store the flag while doing human-like noisy actions, but never delete it."""
username, password = self._credentials()
# Use a human-like unique name for the flagged melody
melody_name = self._humanish_name(unique=True)
# Also create a flagged tone to add realism (not used for get, but kept alive)
flagged_tone_name = self._humanish_name(unique=True)
session = self.get_initialized_session()
try:
self._register(session, username, password)
self._login(session, username, password)
# Tone noise: create some tones, including a flagged tone we protect
flagged_tone_payload = self._tone_sequence_payload(include_name=True)
flagged_tone_payload["name"] = flagged_tone_name
flagged_tone_payload["description"] = self._humanish_description(extra=flag)
flagged_tone_id = self._save_tone_sequence(session, flagged_tone_payload)
tone_ids: List[Tuple[int, str]] = [(flagged_tone_id, flagged_tone_name)]
for _ in range(random.randint(1, 2)):
p = self._tone_sequence_payload(include_name=True)
tid = self._save_tone_sequence(session, p)
tone_ids.append((tid, p["name"]))
# Ensure at least one tone update (never touch the flagged tone's name)
non_flag = [t for t in tone_ids if t[0] != flagged_tone_id]
if not non_flag:
# Create one extra to edit
p = self._tone_sequence_payload(include_name=True)
tid = self._save_tone_sequence(session, p)
tone_ids.append((tid, p["name"]))
non_flag = [(tid, p["name"])]
tid_edit, name_edit = random.choice(non_flag)
upd_once = self._tone_sequence_payload(include_name=True)
upd_once["name"] = name_edit
self._update_tone_sequence(session, upd_once)
# Random tone edits/deletes but never touch the flagged tone
for _ in range(random.randint(1, 3)):
action = random.choice(["create", "edit", "delete", "noop"])
if action == "create":
self._save_tone_sequence(session, self._tone_sequence_payload(include_name=True))
elif action == "edit" and len(tone_ids) > 0:
# pick a non-flag tone to edit
candidates = [t for t in tone_ids if t[0] != flagged_tone_id]
if candidates:
tid, tname = random.choice(candidates)
upd = self._tone_sequence_payload(include_name=True)
upd["name"] = tname
self._update_tone_sequence(session, upd)
elif action == "delete" and len(tone_ids) > 1:
# delete a non-flag tone
candidates = [t for t in tone_ids if t[0] != flagged_tone_id]
if candidates:
tid, tname = candidates[0]
self._delete_tone(session, tid)
tone_ids = [(i, n) for (i, n) in tone_ids if i != tid]
# Verify flagged tone persists and contains flag
tones_list = self._list_tones(session)
ft = self._find_tone_by_name(tones_list, flagged_tone_name)
self.assert_(ft is not None, "Flagged tone missing after noise")
self.assert_in(flag, ft.get("description", ""), "Flag missing from flagged tone")
# Melody noise: create some melodies first
for _ in range(random.randint(1, 2)):
self._create_melody(
session,
self._humanish_name(unique=True),
self._humanish_description(),
tone_sequences=[self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))],
)
# Create the flagged melody (flag appended in description)
seqs = [self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))]
flagged_melody_id = self._create_melody(
session, melody_name, self._humanish_description(extra=flag), tone_sequences=seqs
)
# More melody operations that never delete or rename the flagged melody
for _ in range(random.randint(1, 3)):
op = random.choice(["create", "edit", "delete", "noop"])
if op == "create":
self._create_melody(
session,
self._humanish_name(unique=True),
self._humanish_description(),
tone_sequences=[self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))],
)
elif op == "edit":
# edit a random melody that isn't the flagged one
mlist = self._list_melodies(session)
others = [m for m in mlist if m.get("id") != flagged_melody_id and isinstance(m.get("name"), str)]
if others:
target = random.choice(others)
self._update_melody(
session,
target.get("name", self._humanish_name(unique=True)),
self._humanish_description(),
tone_sequences=[self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))],
)
elif op == "delete":
mlist = self._list_melodies(session)
victims = [m for m in mlist if m.get("id") != flagged_melody_id]
if victims:
self._delete_melody(session, victims[0].get("id"))
# Ensure flagged melody remains and still contains the flag
melodies_now = self._list_melodies(session)
flagged = self._find_melody(melodies_now, melody_name)
self.assert_(flagged is not None, "Flagged melody missing after noise")
self.assert_in(flag, flagged.get("description", ""), "Flag missing from flagged melody")
except requests.RequestException as exc:
self.cquit(Status.DOWN, "Connection error", str(exc))
self.cquit(Status.OK, f"{username}:{melody_name}", f"{username}:{password}:{melody_name}")
def get(self, flag_id: str, flag: str, vuln: str):
try:
username, password, melody_name = self._parse_flag_id(flag_id)
except ValueError:
self.cquit(Status.CORRUPT, "Invalid flag id", flag_id)
session = self.get_initialized_session()
try:
self._login(session, username, password)
# Ensure at least one tone update in get()
tones_exist = self._list_tones(session)
if not tones_exist:
self._save_tone_sequence(session, self._tone_sequence_payload(include_name=True))
tones_exist = self._list_tones(session)
t_edit = random.choice(tones_exist)
up = self._tone_sequence_payload(include_name=True)
up["name"] = t_edit.get("name", self._humanish_name(unique=True))
self._update_tone_sequence(session, up)
# Add some noise: random tone/melody ops that never touch the flagged melody
for _ in range(random.randint(1, 3)):
# tones
action = random.choice(["tone_create", "tone_edit", "tone_delete", "noop"])
if action == "tone_create":
self._save_tone_sequence(session, self._tone_sequence_payload(include_name=True))
elif action == "tone_edit":
tones = self._list_tones(session)
if tones:
t = random.choice(tones)
upd = self._tone_sequence_payload(include_name=True)
upd["name"] = t.get("name", self._humanish_name(unique=True))
self._update_tone_sequence(session, upd)
elif action == "tone_delete":
tones = self._list_tones(session)
if tones:
self._delete_tone(session, tones[0].get("id"))
for _ in range(random.randint(1, 2)):
# melodies
op = random.choice(["mel_create", "mel_edit", "mel_delete", "noop"])
if op == "mel_create":
self._create_melody(
session,
self._humanish_name(unique=True),
self._humanish_description(),
tone_sequences=[self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))],
)
elif op == "mel_edit":
mlist = self._list_melodies(session)
others = [m for m in mlist if m.get("name") != melody_name]
if others:
m = random.choice(others)
self._update_melody(
session,
m.get("name", self._humanish_name(unique=True)),
self._humanish_description(),
tone_sequences=[self._tone_sequence_payload(include_name=False) for _ in range(random.randint(1, 3))],
)
elif op == "mel_delete":
mlist = self._list_melodies(session)
victims = [m for m in mlist if m.get("name") != melody_name]
if victims:
self._delete_melody(session, victims[0].get("id"))
melodies = self._list_melodies(session)
melody = self._find_melody(melodies, melody_name)
except requests.RequestException as exc:
self.cquit(Status.DOWN, "Connection error", str(exc))
if melody is None:
self.cquit(Status.CORRUPT, "Melody not found", melody_name)
description = melody.get("description")
self.assert_(isinstance(description, str), "Invalid melody description type")
self.assert_in(flag, description, "Flag not in melody")
self.cquit(Status.OK)
# ========== helper methods ==========
def _build_base_url(self) -> str:
host = self.host.rstrip('/')
if host.startswith("http://") or host.startswith("https://"):
return host
if ":" in host:
return f"http://{host}"
port_env = os.environ.get("POLYPHONIA_PORT")
try:
port = int(port_env) if port_env else 22025
except ValueError:
port = 3000
if port == 80:
return f"http://{host}"
return f"http://{host}:{port}"
def _url(self, path: str) -> str:
if not path.startswith("/"):
path = f"/{path}"
return f"{self._base_url}{path}"
def _credentials(self) -> Tuple[str, str]:
username = rnd_username()
password = rnd_password()
return username, password
def _random_name(self) -> str:
return rnd_string(12)
def _random_note(self) -> str:
return rnd_string(16)
# ----- HTTP helpers -----
def _register(self, session: requests.Session, username: str, password: str) -> None:
resp = session.post(
self._url("/api/register"),
json={"username": username, "password": password},
timeout=self.timeout,
)
self.check_response(resp, "Registration failed")
data = self.get_json(resp, "Invalid register response")
self.assert_(data.get("success"), "Registration rejects request")
def _login(self, session: requests.Session, username: str, password: str) -> None:
resp = session.post(
self._url("/api/login"),
json={"username": username, "password": password},
timeout=self.timeout,
)
self.check_response(resp, "Login failed")
data = self.get_json(resp, "Invalid login response")
self.assert_(data.get("success"), "Login rejects credentials")
def _create_melody(
self,
session: requests.Session,
name: str,
description: str,
tone_sequences: Optional[List[Dict[str, Any]]] = None,
) -> int:
if tone_sequences is None:
tone_sequences = [self._tone_sequence_payload(include_name=False)]
payload = {
"name": name,
"description": description,
"toneSequences": tone_sequences,
}
resp = session.post(
self._url("/api/melodies"),
json=payload,
timeout=self.timeout,
)
self.check_response(resp, "Melody save failed")
data = self.get_json(resp, "Invalid melody save response")
self.assert_(data.get("success"), "Melody not accepted")
melody_id = data.get("id")
self.assert_(isinstance(melody_id, int) and melody_id > 0, "Invalid melody id")
return melody_id
def _update_melody(
self,
session: requests.Session,
name: str,
description: str,
tone_sequences: Optional[List[Dict[str, Any]]] = None,
) -> int:
if tone_sequences is None:
tone_sequences = [self._tone_sequence_payload(include_name=False)]
payload = {
"name": name,
"description": description,
"toneSequences": tone_sequences,
}
resp = session.put(
self._url("/api/melodies"),
json=payload,
timeout=self.timeout,
)
self.check_response(resp, "Melody update failed")
data = self.get_json(resp, "Invalid melody update response")
self.assert_(data.get("success"), "Melody update not accepted")
melody_id = data.get("id")
self.assert_(isinstance(melody_id, int) and melody_id > 0, "Invalid melody id after update")
return melody_id
def _delete_melody(self, session: requests.Session, melody_id: int) -> None:
resp = session.delete(self._url(f"/api/melodies/{melody_id}"), timeout=self.timeout)
self.check_response(resp, "Melody delete failed")
data = self.get_json(resp, "Invalid melody delete response")
self.assert_(data.get("success"), "Melody delete not accepted")
def _get_profile(self, session: requests.Session) -> Dict[str, Any]:
resp = session.get(self._url("/api/user"), timeout=self.timeout)
self.check_response(resp, "User profile failed")
data = self.get_json(resp, "Invalid user response")
self.assert_("username" in data, "Username missing in profile")
return data
def _list_melodies(self, session: requests.Session) -> List[Dict[str, Any]]:
resp = session.get(self._url("/api/melodies"), timeout=self.timeout)
self.check_response(resp, "Melody list failed")
data = self.get_json(resp, "Invalid melody list")
melodies = data.get("melodies")
self.assert_(isinstance(melodies, list), "Melody list is not a list")
result: List[Dict[str, Any]] = []
for item in melodies:
if isinstance(item, dict):
result.append(item)
return result
def _find_melody(self, melodies: List[Dict[str, Any]], name: str) -> Optional[Dict[str, Any]]:
for item in melodies:
if item.get("name") == name:
return item
return None
def _tone_sequence_payload(self, include_name: bool = False) -> Dict[str, Any]:
base_note = random.randint(48, 72)
tempo = random.choice([90, 100, 110, 120, 128, 140, 150])
duration = random.choice([1, 2, 2, 3, 4])
interval_type = random.choice(["unison", "third", "fifth", "octave", "seventh"])
chord_type = random.choice(["none", "major", "minor", "sus2", "sus4", "dim"])
mode = random.choice(["triad", "arp", "scale"]) # type: ignore
if mode == "triad":
if chord_type == "minor":
notes = [base_note, base_note + 3, base_note + 7]
elif chord_type == "dim":
notes = [base_note, base_note + 3, base_note + 6]
else:
notes = [base_note, base_note + 4, base_note + 7]
elif mode == "arp":
step = random.choice([2, 3, 4])
notes = [base_note + i * step for i in range(3)]
else:
scale = random.choice([[2, 2, 1, 2], [2, 1, 2, 2], [1, 2, 2, 2]])
notes = [base_note]
cur = base_note
for s in scale:
cur += s
notes.append(cur)
payload: Dict[str, Any] = {
"id": random.randint(1, 1_000_000),
"baseNote": base_note,
"intervalType": interval_type,
"chordType": chord_type,
"tempo": tempo,
"duration": duration,
"notes": notes,
}
if include_name:
payload["name"] = self._humanish_name(unique=True)
payload["description"] = self._humanish_description()
return payload
# ----- Tone library helpers -----
def _list_tones(self, session: requests.Session) -> List[Dict[str, Any]]:
resp = session.get(self._url("/api/tones"), timeout=self.timeout)
self.check_response(resp, "Tone list failed")
data = self.get_json(resp, "Invalid tone list")
tones = data.get("tones")
self.assert_(isinstance(tones, list), "Tone list is not a list")
result: List[Dict[str, Any]] = []
for item in tones:
if isinstance(item, dict):
result.append(item)
return result
def _find_tone_by_name(self, tones: List[Dict[str, Any]], name: str) -> Optional[Dict[str, Any]]:
for item in tones:
if item.get("name") == name:
return item
return None
def _delete_tone(self, session: requests.Session, tone_id: int) -> None:
resp = session.delete(self._url(f"/api/tones/{tone_id}"), timeout=self.timeout)
self.check_response(resp, "Tone delete failed")
data = self.get_json(resp, "Invalid tone delete response")
self.assert_(data.get("success"), "Tone delete not accepted")
def _assert_tone_matches_expected(self, expected: Dict[str, Any], actual: Dict[str, Any], msg: str) -> None:
# Only compare relevant musical fields
keys = ["name", "description", "baseNote", "intervalType", "chordType", "tempo", "duration", "notes"]
for k in keys:
self.assert_(k in actual, f"{msg}: key missing {k}")
self.assert_eq(actual[k], expected[k], f"{msg}: field mismatch {k}")
def _assert_tone_sets_match(self, expected_list: List[Dict[str, Any]], actual_list: List[Dict[str, Any]], msg: str) -> None:
exp_names = {t["name"] for t in expected_list}
act_names = {t.get("name") for t in actual_list}
self.assert_eq(act_names, exp_names, f"{msg}: name sets differ")
for e in expected_list:
a = self._find_tone_by_name(actual_list, e["name"])
self.assert_(a is not None, f"{msg}: missing tone {e['name']}")
self._assert_tone_matches_expected(e, a, msg)
def _assert_melody_sets_match_expected(self, expected: Dict[str, Dict[str, Any]], actual_list: List[Dict[str, Any]], msg: str) -> None:
exp_names = set(expected.keys())
act_names = {m.get("name") for m in actual_list}
self.assert_eq(act_names, exp_names, f"{msg}: name sets differ")
for name, meta in expected.items():
m = self._find_melody(actual_list, name)
self.assert_(m is not None, f"{msg}: missing melody {name}")
self.assert_eq(m.get("id"), meta.get("id"), f"{msg}: id mismatch for {name}")
self.assert_eq(m.get("description"), meta.get("description"), f"{msg}: description mismatch for {name}")
# ----- Human-like content generators -----
def _unique_tail(self) -> str:
return os.urandom(6).hex()
def _humanish_name(self, unique: bool = False) -> str:
adjectives = [
"Midnight",
"Autumn",
"Silent",
"Velvet",
"Crimson",
"Electric",
"Gentle",
"Bittersweet",
"Neon",
"Emerald",
"Abyss",
"Golden",
"Shimmering",
"Dusky",
"Azure",
"Iridescent",
"Secret",
"Distant",
"Frosted",
"Lunar",
"Amber",
"Cobalt",
]
nouns = [
"Echo",
"Nocturne",
"Pulse",
"Drift",
"Waltz",
"Mirage",
"Breeze",
"Canvas",
"Cascade",
"Lullaby",
"Horizon",
"Reverie",
"Serenade",
"Voyage",
"Haze",
"Sketch",
"Pattern",
"Study",
"Ritual",
"Bloom",
"Signal",
]
variants = [
" in C minor",
" in D major",
" in A minor",
" (solo)",
" (duet)",
" (live)",
" (ambient)",
" (demo)",
"",
]
base = f"{random.choice(adjectives)} {random.choice(nouns)}{random.choice(variants)}"
if unique:
base += f" - take {self._unique_tail()}"
return base
def _humanish_description(self, extra: Optional[str] = None) -> str:
moods = [
"warm and airy",
"moody but hopeful",
"gentle and reflective",
"bright with a soft swing",
"lo-fi and nocturnal",
"dreamy with subtle tension",
"playful and syncopated",
]
instruments = [
"piano",
"strings",
"synth",
"bells",
"guitar",
"e-piano",
"pad",
]
phrases = [
"Recorded late at night.",
"Fits a calm intro.",
"Could loop nicely.",
"Try at 110 BPM.",
"Layer with a soft pad.",
"Needs a brighter lead.",
"First pass, keep it simple.",
"Rough sketch - refine later.",
"Minimal drums, focus on tone.",
]
base = f"A {random.choice(moods)} sketch for {random.choice(instruments)}. {random.choice(phrases)}"
if extra:
sep = random.choice([" ", " - ", " | "])
base += f"{sep}{extra}"
base += f" · take {self._unique_tail()}"
return base
# ----- Tone library helpers -----
def _save_tone_sequence(self, session: requests.Session, payload: Dict[str, Any]) -> int:
resp = session.post(self._url("/api/tones"), json=payload, timeout=self.timeout)
self.check_response(resp, "Tone save failed")
data = self.get_json(resp, "Invalid tone save response")
self.assert_(data.get("success"), "Tone not accepted")
tone_id = data.get("id")
self.assert_(isinstance(tone_id, int) and tone_id > 0, "Invalid tone id")
return tone_id
def _update_tone_sequence(self, session: requests.Session, payload: Dict[str, Any]) -> int:
resp = session.put(self._url("/api/tones"), json=payload, timeout=self.timeout)
self.check_response(resp, "Tone update failed")
data = self.get_json(resp, "Invalid tone update response")
self.assert_(data.get("success"), "Tone update not accepted")
tone_id = data.get("id")
self.assert_(isinstance(tone_id, int) and tone_id > 0, "Invalid tone id after update")
return tone_id
def _parse_flag_id(self, value: str) -> Tuple[str, str, str]:
parts = value.split(":", 2)
if len(parts) != 3:
raise ValueError("invalid flag id")
return parts[0], parts[1], parts[2]
if __name__ == "__main__":
checker = PolyphoniaChecker(sys.argv[2])
try:
checker.action(sys.argv[1], *sys.argv[3:])
except checker.get_check_finished_exception():
cquit(Status(checker.status), checker.public, checker.private)

View File

@@ -0,0 +1,2 @@
checklib==0.7.0
requests==2.32.5

View File

@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# Simple helper to exercise checker.py in check/put/get modes.
set -u
set -o pipefail
HOST=${POLYPHONIA_TEST_HOST:-127.0.0.1}
if [[ -v POLYPHONIA_TEST_FLAG ]]; then
FLAG=${POLYPHONIA_TEST_FLAG}
else
# Default to attack-defence style flag: 31 chars of A-Z0-9 plus '='
FLAG="$(LC_ALL=C tr -dc 'A-Z0-9' </dev/urandom | head -c 31)="
fi
FLAG_ID=${POLYPHONIA_TEST_FLAG_ID:-placeholder-flag-id}
VULN=${POLYPHONIA_TEST_VULN:-1}
PRESET_STORED=${POLYPHONIA_TEST_STORED:-}
RUN_LAST_STDOUT=""
RUN_LAST_STDERR=""
print_cmd() {
printf '$'
for arg in "$@"; do
printf ' %q' "$arg"
done
printf '\n'
}
run_checker() {
local stdout_file
local stderr_file
stdout_file=$(mktemp)
stderr_file=$(mktemp)
print_cmd python3 checker.py "$@"
python3 checker.py "$@" >"${stdout_file}" 2>"${stderr_file}"
local code=$?
RUN_LAST_STDOUT=$(cat "${stdout_file}")
RUN_LAST_STDERR=$(cat "${stderr_file}")
rm -f "${stdout_file}" "${stderr_file}"
if [[ -n "${RUN_LAST_STDOUT}" ]]; then
printf '%s\n' "${RUN_LAST_STDOUT}"
else
echo "<stdout empty>"
fi
if [[ -n "${RUN_LAST_STDERR}" ]]; then
printf '%s\n' "${RUN_LAST_STDERR}" >&2
else
printf '<stderr empty>\n' >&2
fi
echo "exit code: ${code}"
return "${code}"
}
run_checker check "${HOST}"
check_code=$?
run_checker put "${HOST}" "${FLAG_ID}" "${FLAG}" "${VULN}"
put_code=$?
stored_flag_id="${PRESET_STORED}"
if [[ -z "${stored_flag_id}" ]]; then
if [[ ${put_code} -eq 101 && -n "${RUN_LAST_STDOUT}" ]]; then
stored_flag_id=$(printf '%s' "${RUN_LAST_STDOUT}" | tail -n 1)
else
stored_flag_id="${FLAG_ID}"
fi
fi
run_checker get "${HOST}" "${stored_flag_id}" "${FLAG}" "${VULN}"
get_code=$?
exit_code=0
for code in "${check_code}" "${put_code}" "${get_code}"; do
if [[ ${code} -ne 101 ]]; then
exit_code=${code}
break
fi
done
exit "${exit_code}"

View File

@@ -0,0 +1,3 @@
requests
checklib
websockets

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1000 KiB

View File

@@ -0,0 +1,12 @@
FROM bash:5.3.3-alpine3.22
WORKDIR /app
RUN apk update && apk add jq sqlite postgresql-client
COPY ./server.sh ./server.sh
COPY ./static ./static
RUN chown nobody:nobody -R /app
USER nobody:nobody
ENTRYPOINT [ "/usr/local/bin/bash", "/app/server.sh" ]

View File

@@ -0,0 +1,46 @@
name: bashist-ad-ctf-service
services:
db:
image: postgres:17.6-alpine3.22
environment:
- POSTGRES_DB=bashist
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- bashist-network
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
bashist:
build: .
environment:
- PGHOST=db
- PGDATABASE=bashist
- PGUSER=postgres
- PGPASSWORD=password
ports:
- 1599:8080
volumes:
- pgdata:/pgdata
networks:
- bashist-network
depends_on:
db:
condition: service_healthy
restart: unless-stopped
volumes:
pgdata:
driver: local
networks:
bashist-network:
driver: bridge

View File

@@ -0,0 +1,626 @@
#!/usr/bin/env bash
PORT=8080
ADDRESS='0.0.0.0'
DIR='./static/'
DB_PATH="$PWD/db.sqlite"
read -d '' -r USAGE <<-EOF
Usage: ./server.sh [-p port] [-b addr] [-d dir]
Options
-h Print this message and exit.
-b <addr> Address to bind to, defaults to 0.0.0.0.
-d <dir> Directory to serve, defaults to your current directory.
-p <port> Port to bind to, defaults to 8080.
EOF
fatal() {
echo '[fatal]' "$@" >&2
exit 1
}
info() {
echo '[info]' "$@" >&2
exit 1
}
mime-type() {
local f=$1
local bname=${f##*/}
local ext=${bname##*.}
[[ $bname == "$ext" ]] && ext=
case "$ext" in
html | htm) echo 'text/html' ;;
jpeg | jpg) echo 'image/jpeg' ;;
png) echo 'image/png' ;;
txt) echo 'text/plain' ;;
css) echo 'text/css' ;;
js) echo 'text/javascript' ;;
json) echo 'application/json' ;;
*) echo 'application/octet-stream' ;;
esac
}
html-encode() {
local s=$1
s=${s//&/\&amp;}
s=${s//</\&lt;}
s=${s//>/\&gt;}
s=${s//\"/\&quot;}
s=${s//\'/\&apos;}
echo "$s"
}
urlencode() {
local LC_ALL=C
for ((i = 0; i < ${#1}; i++)); do
: "${1:i:1}"
case "$_" in
[a-zA-Z0-9.~_-])
printf '%s' "$_"
;;
*)
printf '%%%02X' "'$_"
;;
esac
done
printf '\n'
}
urldecode() {
: "${1//+/ }"
printf '%b\n' "${_//%/\\x}"
}
normalize-path() {
local path=/$1
local parts
IFS='/' read -r -a parts <<<"$path"
local -a out=()
local part
for part in "${parts[@]}"; do
case "$part" in
'') ;;
'.') ;;
*) out+=("$part") ;;
esac
done
local s
s=$(
IFS=/
echo "${out[*]}"
)
echo "/$s"
}
parse-json() {
local json_string="$1"
local query="$2"
local result
result=$(echo "$json_string" | jq -r "$query" 2>/dev/null)
if [[ "$result" == "null" ]]; then
echo ""
else
echo "$result"
fi
}
init-db() {
psql --version >/dev/null || fatal 'No psql binary found'
psql <<SQL
CREATE TABLE IF NOT EXISTS users (
token VARCHAR PRIMARY KEY,
username VARCHAR NOT NULL,
password VARCHAR NOT NULL
);
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
user_id VARCHAR NOT NULL,
private BOOLEAN NOT NULL,
content VARCHAR NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(token)
);
SQL
}
db-escape() {
local str="$1"
echo "${str//\'/\'}"
}
db-list-users() {
psql -tA <<SQL
SELECT json_agg(t) FROM
(SELECT username FROM users) t
SQL
}
db-add-user() {
local username="$(db-escape "$1")"
local password="$(db-escape "$2")"
local token="$3"
psql <<SQL >/dev/null
INSERT INTO users(username, password, token)
VALUES ('${username}', '${password}', '${token}')
SQL
}
db-get-user-by-name() {
local username="$1"
psql -tA <<SQL
SELECT json_agg(t) FROM
(SELECT username, password, token
FROM users
WHERE username = '${username}') t
SQL
}
db-add-post() {
local user_id=$1
local private=$([[ "$2" == "true" ]] && echo 1 || echo 0)
local content="$3"
psql <<SQL >/dev/null
INSERT INTO posts(user_id, private, content)
VALUES ('${user_id}', ${private}::bool, '${content}')
SQL
}
db-list-posts() {
psql -tA <<SQL
SELECT json_agg(t) FROM
(SELECT u.username, p.content
FROM posts p
JOIN users u ON u.token = p.user_id
WHERE p.private = False) t
SQL
}
db-list-user-posts() {
local user_token="$1"
psql -tA <<SQL
SELECT json_agg(t) FROM
(
SELECT content, private
FROM posts
WHERE user_id = '${user_token}'
) t
SQL
}
api-user-register() {
local body="$1"
local username=$(parse-json "$body" '.username')
local password=$(parse-json "$body" '.password')
if [[ -n "$username" && -n "$password" ]]; then
password=$(echo -n "password" | sha256sum)
local hashed_password=${password%% *}
local token=$(for i in {1..16}; do printf "%02x" $((RANDOM % 256)); done)
db-add-user "$username" "$hashed_password" "$token"
echo "$token"
else
return 1
fi
}
api-user-login() {
local body="$1"
local username=$(parse-json "$body" '.username')
local password=$(parse-json "$body" '.password')
if [[ -z "$username" || -z "$password" ]]; then
return 1
fi
local response=$(db-get-user-by-name "$username")
if [[ -z "$response" ]]; then
return 1
fi
password=$(echo -n "password" | sha256sum)
local hashed_password=${password%% *}
local db_password=$(parse-json "$response" '.[0].password')
if [[ "$hashed_password" != "$db_password" ]]; then
return 1
fi
echo $(parse-json "$response" '.[0].token')
}
api-users() {
db-list-users
}
api-post-new() {
local body="$1"
local token="${COOKIES[token]}"
if [[ -z "$token" ]]; then
return 1
fi
local content=$(parse-json "$body" ".content")
local private=$(parse-json "$body" ".private")
if [[ -z "$content" || -z "$private" ]]; then
return 2
fi
db-add-post "${token}" "${private}" "${content}"
if [[ $? -ne 0 ]]; then
return 1
fi
return 0
}
api-list-user-posts() {
local body="$1"
local token="${COOKIES[token]}"
if [[ -z "$token" ]]; then
return 1
fi
db-list-user-posts "$token"
}
api-list-posts() {
db-list-posts
}
response-ok() {
local fd=$1
local message="$2"
local message_length=$(echo -n "$message" | wc -c)
printf 'HTTP/1.1 200 OK\r\n' >&"$fd"
printf 'Content-Type: application/json\r\n' >&"$fd"
printf "Content-Length: ${message_length}\r\n" >&"$fd"
printf '\r\n' >&"$fd"
printf "$message" >&"$fd"
}
response-bad-request() {
local fd=$1
local message="${2}"
local message_length=$(echo -n "$message" | wc -c)
printf 'HTTP/1.1 400 Bad Request\r\n' >&"$fd"
printf 'Content-Type: application/json\r\n' >&"$fd"
printf "Content-Length: ${message_length}\r\n" >&"$fd"
printf '\r\n' >&"$fd"
printf "$message" >&"$fd"
}
response-unauthorized() {
local fd=$1
local message="${2}"
local message_length=$(echo -n "$message" | wc -c)
printf 'HTTP/1.1 401 Unauthorized\r\n' >&"$fd"
printf 'Content-Type: application/json\r\n' >&"$fd"
printf "Content-Length: ${message_length}\r\n" >&"$fd"
printf '\r\n' >&"$fd"
printf "$message" >&"$fd"
}
response-method-not-allowed() {
local fd=$1
printf 'HTTP/1.1 405 Method Not Allowed\r\n' >&"$fd"
printf '\r\n' >&"$fd"
}
parse-cookies() {
local cookie_header="$1"
declare -gA COOKIES=()
cookie_header="${cookie_header#"${cookie_header%%[![:space:]]*}"}"
cookie_header="${cookie_header%"${cookie_header##*[![:space:]]}"}"
if [[ -z "$cookie_header" ]]; then
return 1
fi
IFS=';' read -ra cookie_pairs <<<"$cookie_header"
for pair in "${cookie_pairs[@]}"; do
pair="${pair#"${pair%%[![:space:]]*}"}"
pair="${pair%"${pair##*[![:space:]]}"}"
IFS='=' read -r key value <<<"$pair"
key="${key#"${key%%[![:space:]]*}"}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
value=$(urldecode "$value")
if [[ -n "$key" ]]; then
COOKIES["$key"]="$value"
fi
done
}
parse-request() {
declare -gA REQ_INFO=()
declare -gA REQ_HEADERS=()
declare -g REQ_BODY=''
local state='status'
local line
local content_length=0
while IFS= read -r line; do
line=${line%$'\r'}
case "$state" in
'status')
local method path version
read -r method path version <<<"$line"
REQ_INFO[method]=$method
REQ_INFO[path]=$path
REQ_INFO[version]=$version
state='headers'
;;
'headers')
if [[ -z $line ]]; then
if [[ ${REQ_HEADERS['content-length']} -gt 0 ]]; then
content_length=${REQ_HEADERS['content-length']}
read -r -n "$content_length" REQ_BODY
fi
break
else
local key value
IFS=: read -r key value <<<"$line"
key=${key,,}
value=${value# *}
REQ_HEADERS[$key]=$value
fi
;;
esac
done
}
process-api-request() {
local fd=$1
local path="${REQ_HEADERS[path]}"
local method="${REQ_INFO[method]}"
local body="$REQ_BODY"
parse-cookies ${REQ_HEADERS["cookie"]}
case ${REQ_INFO[path]} in
/api/user/register)
if [[ "$method" == "POST" ]]; then
local token
if token=$(api-user-register "$body"); then
printf 'HTTP/1.1 201 CREATED\r\n' >&"$fd"
printf 'Content-Length: 0\r\n' >&"$fd"
printf "Set-Cookie: token=${token}; Path=/\r\n" >&"$fd"
printf '\r\n' >&"$fd"
else
response=$(jq -c -n '{error: "Missing username or password"}')
response-bad-request $fd "$response"
fi
else
response-method-not-allowed $fd
fi
;;
/api/user/login)
if [[ "$method" == "POST" ]]; then
local token
if token=$(api-user-login "$body"); then
printf 'HTTP/1.1 200 OK\r\n' >&"$fd"
printf 'Content-Length: 0\r\n' >&"$fd"
printf "Set-Cookie: token=${token}; Path=/\r\n" >&"$fd"
printf '\r\n' >&"$fd"
else
response=$(jq -c -n '{error: "Wrong username or password"}')
response-bad-request $fd "$response"
fi
else
response-method-not-allowed $fd
fi
;;
/api/users)
if [[ "$method" == "GET" ]]; then
local posts=$(api-users "$body")
local response=$(echo "$posts" | jq -c)
response-ok "$fd" "$response"
else
response-method-not-allowed $fd
fi
;;
/api/post/new)
if [[ "$method" == "POST" ]]; then
api-post-new "$body"
case "$?" in
0)
printf 'HTTP/1.1 201 CREATED\r\n' >&"$fd"
printf 'Content-Length: 0\r\n' >&"$fd"
printf '\r\n' >&"$fd"
;;
1)
response=$(jq -c -n '{error: "No token cookie was found or wrong token format"}')
response-unauthorized $fd "$response"
;;
2)
response=$(jq -c -n '{error: "Missing content or private"}')
response-bad-request $fd "$response"
;;
esac
else
response-method-not-allowed $fd
fi
;;
/api/user/posts)
if [[ "$method" == "GET" ]]; then
local posts
if posts=$(api-list-user-posts "$body"); then
local response=$(echo "$posts" | jq -c)
response-ok "$fd" "$response"
else
response=$(jq -c -n '{error: "No token cookie was found or wrong token format"}')
response-unauthorized $fd "$response"
fi
else
response-method-not-allowed $fd
fi
;;
/api/posts)
if [[ "$method" == "GET" ]]; then
local posts=$(api-list-posts "$body")
local response=$(echo "$posts" | jq -c)
response-ok "$fd" "$response"
else
response-method-not-allowed $fd
fi
;;
*)
printf 'HTTP/1.1 404 Not Found\r\n' >&"$fd"
printf '\r\n' >&"$fd"
return
;;
esac
}
log-request() {
local time=$(date +"[%d/%b/%Y:%H:%M:%S %z]")
local method="${REQ_INFO[method]}"
local path="${REQ_INFO[path]}"
local useragent="${REQ_HEADERS['user-agent']}"
echo "${time} \"${method} ${path}\" \"$useragent\""
}
process-request() {
local fd=$1
parse-request <&"$fd"
[[ ${REQ_INFO[version]} == 'HTTP/1.1' ]] ||
fatal "unsupported HTTP version: '${REQ_INFO[method]}'"
[[ ${REQ_INFO[method]} == 'GET' || ${REQ_INFO[method]} == 'POST' ]] ||
fatal "unsupported HTTP method: '${REQ_INFO[method]}'"
[[ ${REQ_INFO[path]} == /* ]] ||
fatal 'path must be absolute'
log-request
local path="${REQ_INFO[path]}"
if [[ $path == /api/* ]]; then
process-api-request $fd
return
fi
path=${path:1}
local query
IFS='?' read -r path query <<<"$path"
path=$(urldecode "$path")
path=$(normalize-path "$path")
path=${path:1}
path=${path:-.}
local totry=(
"$path"
"$path/index.html"
"$path/index.htm"
)
local try file
for try in "${totry[@]}"; do
if [[ -f $try ]]; then
file=$try
break
fi
done
if [[ -n $file ]]; then
local mime
mime=$(mime-type "$file")
printf 'HTTP/1.1 200 OK\r\n' >&"$fd"
printf 'Content-Type: %s\r\n' "$mime" >&"$fd"
printf '\r\n' >&"$fd"
tee <"$file" >&"$fd"
elif [[ -d $path ]]; then
if [[ ${REQ_INFO[path]} != */ ]]; then
printf 'HTTP/1.1 301 Moved Permanently\r\n' >&"$fd"
printf 'Location: %s/\r\n' "${REQ_INFO[path]}" >&"$fd"
printf '\r\n' >&"$fd"
return
fi
printf 'HTTP/1.1 404 Not Found\r\n' >&"$fd"
printf '\r\n' >&"$fd"
else
printf 'HTTP/1.1 404 Not Found\r\n' >&"$fd"
printf '\r\n' >&"$fd"
fi
}
main() {
enable accept || fatal 'failed to load accept'
enable tee
local OPTIND OPTARG opt
while getopts 'b:hp:d:v' opt; do
case "$opt" in
b) ADDRESS=$OPTARG ;;
p) PORT=$OPTARG ;;
d) DIR=$OPTARG ;;
h)
echo "$USAGE"
exit 0
;;
*)
echo "$USAGE" >&2
exit 2
;;
esac
done
echo 'Initializing db'
init-db || fatal "failed to initialize db"
echo 'Successful'
echo
cd "$DIR" || fatal "failed to move to $DIR"
echo "listening on http://$ADDRESS:$PORT"
echo "serving out of $PWD"
local fd ip
while true; do
accept -b "$ADDRESS" -v fd -r ip "$PORT" ||
fatal 'failed to read socket'
process-request "$fd" &
exec {fd}>&-
done
}
main "$@"

View File

@@ -0,0 +1,16 @@
<!doctype html>
<html>
<head>
<title>Bashist</title>
</head>
<body>
<h1>Welcome</h1>
<ul>
<li><a href="register.html">Register</a></li>
<li><a href="login.html">Login</a></li>
<li><a href="newpost.html">New Post</a></li>
<li><a href="posts.html">Public Posts</a></li>
<li><a href="userposts.html">My Posts</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,35 @@
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="loginForm">
<input type="text" id="username" placeholder="Username" /><br />
<input type="password" id="password" placeholder="Password" /><br />
<button type="submit">Login</button>
</form>
<p id="msg"></p>
<script>
document
.getElementById("loginForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const res = await fetch("/api/user/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: document.getElementById("username").value,
password: document.getElementById("password").value,
}),
});
document.getElementById("msg").textContent = res.ok
? "Logged in! Cookie set."
: "Wrong username or password.";
});
</script>
</body>
</html>

View File

@@ -0,0 +1,36 @@
<!doctype html>
<html>
<head>
<title>New Post</title>
</head>
<body>
<h1>Create New Post</h1>
<form id="postForm">
<textarea id="content" placeholder="Write your post here..."></textarea
><br />
<label><input type="checkbox" id="private" /> Private</label><br />
<button type="submit">Submit</button>
</form>
<p id="msg"></p>
<script>
document
.getElementById("postForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const res = await fetch("/api/post/new", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content: document.getElementById("content").value,
private: document.getElementById("private").checked,
}),
});
document.getElementById("msg").textContent = res.ok
? "Post created!"
: "Error creating post (maybe not logged in?)";
});
</script>
</body>
</html>

View File

@@ -0,0 +1,26 @@
<!doctype html>
<html>
<head>
<title>Public Posts</title>
</head>
<body>
<h1>Public Posts</h1>
<button onclick="loadPosts()">Refresh</button>
<ul id="posts"></ul>
<script>
async function loadPosts() {
const res = await fetch("/api/posts");
const data = await res.json();
const list = document.getElementById("posts");
list.innerHTML = "";
data.forEach((post) => {
const li = document.createElement("li");
li.textContent = post.username + ": " + post.content;
list.appendChild(li);
});
}
loadPosts();
</script>
</body>
</html>

View File

@@ -0,0 +1,35 @@
<!doctype html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form id="registerForm">
<input type="text" id="username" placeholder="Username" /><br />
<input type="password" id="password" placeholder="Password" /><br />
<button type="submit">Register</button>
</form>
<p id="msg"></p>
<script>
document
.getElementById("registerForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const res = await fetch("/api/user/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username: document.getElementById("username").value,
password: document.getElementById("password").value,
}),
});
document.getElementById("msg").textContent = res.ok
? "Registered! Cookie set."
: "Error registering.";
});
</script>
</body>
</html>

View File

@@ -0,0 +1,31 @@
<!doctype html>
<html>
<head>
<title>My Posts</title>
</head>
<body>
<h1>My Posts</h1>
<button onclick="loadUserPosts()">Refresh</button>
<ul id="posts"></ul>
<script>
async function loadUserPosts() {
const res = await fetch("/api/user/posts");
if (!res.ok) {
document.getElementById("posts").innerHTML =
"<li>Error: Not logged in</li>";
return;
}
const data = await res.json();
const list = document.getElementById("posts");
list.innerHTML = "";
data.forEach((post) => {
const li = document.createElement("li");
li.textContent = post.content;
list.appendChild(li);
});
}
loadUserPosts();
</script>
</body>
</html>

View File

@@ -0,0 +1 @@
don't forget the attack data...

View File

@@ -0,0 +1,22 @@
FROM golang:1.25.1-bookworm AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/root/.cache/go-build \
--mount=type=cache,target=/go/pkg/mod \
go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -ldflags "-s -w" -o /out/ ./...
FROM gcr.io/distroless/static-debian11:nonroot
COPY --from=builder /out/block-game-backend /usr/local/bin/block-game-backend
USER nonroot:nonroot
ENTRYPOINT ["/usr/local/bin/block-game-backend"]

View File

@@ -0,0 +1,7 @@
FROM golang:1.25.1-bookworm AS runner
WORKDIR /app
RUN go install github.com/mitranim/gow@latest
CMD ["gow", "run", "."]

View File

@@ -0,0 +1 @@
to regenerate code: `go generate ./codegen`

View File

@@ -0,0 +1,46 @@
package auth
import (
"context"
"fmt"
"net/http"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/utils"
)
type ctxUserKeyT struct{}
var ctxUserKey = ctxUserKeyT{}
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := session.GetSessionUser(r)
if session.IsNotLoggedIn(err) {
http.Error(w, "Not logged in", http.StatusUnauthorized)
return
}
if session.IsInvalidSession(err) {
http.Error(w, "Invalid session, reset cookies", http.StatusBadRequest)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
ctx := context.WithValue(r.Context(), ctxUserKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetUser(ctx context.Context) (*ent.User, error) {
user, ok := ctx.Value(ctxUserKey).(*ent.User)
if !ok {
return nil, fmt.Errorf("context is invalid: expected user")
}
return user, nil
}

View File

@@ -0,0 +1,175 @@
package session
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log"
"net/http"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/db"
"github.com/gorilla/sessions"
)
func generateRandomKey() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", fmt.Errorf("rand failed: %w", err)
}
return hex.EncodeToString(bytes), nil
}
func getOrCreateSessionSecret(ctx context.Context) (string, error) {
secret, err := db.Client.Setting.Query().
Where(setting.Key("session_secret")).
Only(ctx)
if err == nil {
return secret.Value, nil
}
if !ent.IsNotFound(err) {
return "", fmt.Errorf("unexpected db error: %w", err)
}
log.Println("session secret not found, generating a new one")
newSecret, err := generateRandomKey()
if err != nil {
return "", fmt.Errorf("generating session secret failed: %w", err)
}
_, err = db.Client.Setting.Create().
SetKey("session_secret").
SetValue(newSecret).
Save(ctx)
if err != nil {
return "", fmt.Errorf("saving session secret failed: %w", err)
}
return newSecret, nil
}
var Store *sessions.CookieStore
func Initialize() error {
ctx := context.Background()
sessionSecret, err := getOrCreateSessionSecret(ctx)
if err != nil {
return fmt.Errorf("getting session secret failed: %w", err)
}
Store = sessions.NewCookieStore([]byte(sessionSecret))
Store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7 days
HttpOnly: true,
Secure: false, // we don't use https
}
return nil
}
type NotLoggedInError struct{}
func (e *NotLoggedInError) Error() string {
return "Not logged in"
}
func IsNotLoggedIn(err error) bool {
if err == nil {
return false
}
var e *NotLoggedInError
return errors.As(err, &e)
}
type InvalidSessionError struct {
Reason error
}
func (err *InvalidSessionError) Error() string {
return fmt.Sprintf("invalid session: %s", err.Reason)
}
func (err *InvalidSessionError) Unwrap() error {
return err.Reason
}
func IsInvalidSession(err error) bool {
if err == nil {
return false
}
var e *InvalidSessionError
return errors.As(err, &e)
}
func GetUserId(r *http.Request) (int, error) {
session, err := Store.Get(r, "auth")
if err != nil {
return -1, &InvalidSessionError{Reason: err}
}
id := session.Values["user_id"]
if id == nil {
return -1, &NotLoggedInError{}
}
idValue, ok := id.(int)
if !ok {
return -1, &InvalidSessionError{Reason: fmt.Errorf("id is not an int")}
}
return idValue, nil
}
func SetUserId(w http.ResponseWriter, r *http.Request, userId int) error {
session, err := Store.Get(r, "auth")
if err != nil {
return &InvalidSessionError{Reason: err}
}
session.Values["user_id"] = userId
if err := session.Save(r, w); err != nil {
return fmt.Errorf("saving session failed: %w", err)
}
return nil
}
func GetSessionUser(r *http.Request) (*ent.User, error) {
ctx := r.Context()
userId, err := GetUserId(r)
if err != nil {
return nil, fmt.Errorf("fetching the user id failed: %w", err)
}
user, err := db.Client.User.Get(ctx, userId)
if err != nil {
return nil, &InvalidSessionError{Reason: fmt.Errorf("fetching the user from the database failed: %w", err)}
}
return user, nil
}
func ClearSession(w http.ResponseWriter, r *http.Request) error {
session, err := Store.Get(r, "auth")
if err != nil {
return fmt.Errorf("fetching session failed: %w", err)
}
session.Options.MaxAge = -1
if err := session.Save(r, w); err != nil {
return fmt.Errorf("clearing session failed: %w", err)
}
return nil
}

View File

@@ -0,0 +1,691 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"omctf.ru/block-game-backend/codegen/ent/migrate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Level is the client for interacting with the Level builders.
Level *LevelClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Level = NewLevelClient(c.config)
c.Setting = NewSettingClient(c.config)
c.User = NewUserClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Level: NewLevelClient(cfg),
Setting: NewSettingClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Level: NewLevelClient(cfg),
Setting: NewSettingClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Level.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Level.Use(hooks...)
c.Setting.Use(hooks...)
c.User.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Level.Intercept(interceptors...)
c.Setting.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *LevelMutation:
return c.Level.mutate(ctx, m)
case *SettingMutation:
return c.Setting.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// LevelClient is a client for the Level schema.
type LevelClient struct {
config
}
// NewLevelClient returns a client for the Level from the given config.
func NewLevelClient(c config) *LevelClient {
return &LevelClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `level.Hooks(f(g(h())))`.
func (c *LevelClient) Use(hooks ...Hook) {
c.hooks.Level = append(c.hooks.Level, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `level.Intercept(f(g(h())))`.
func (c *LevelClient) Intercept(interceptors ...Interceptor) {
c.inters.Level = append(c.inters.Level, interceptors...)
}
// Create returns a builder for creating a Level entity.
func (c *LevelClient) Create() *LevelCreate {
mutation := newLevelMutation(c.config, OpCreate)
return &LevelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Level entities.
func (c *LevelClient) CreateBulk(builders ...*LevelCreate) *LevelCreateBulk {
return &LevelCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *LevelClient) MapCreateBulk(slice any, setFunc func(*LevelCreate, int)) *LevelCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &LevelCreateBulk{err: fmt.Errorf("calling to LevelClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*LevelCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &LevelCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Level.
func (c *LevelClient) Update() *LevelUpdate {
mutation := newLevelMutation(c.config, OpUpdate)
return &LevelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *LevelClient) UpdateOne(_m *Level) *LevelUpdateOne {
mutation := newLevelMutation(c.config, OpUpdateOne, withLevel(_m))
return &LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *LevelClient) UpdateOneID(id int) *LevelUpdateOne {
mutation := newLevelMutation(c.config, OpUpdateOne, withLevelID(id))
return &LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Level.
func (c *LevelClient) Delete() *LevelDelete {
mutation := newLevelMutation(c.config, OpDelete)
return &LevelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *LevelClient) DeleteOne(_m *Level) *LevelDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *LevelClient) DeleteOneID(id int) *LevelDeleteOne {
builder := c.Delete().Where(level.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &LevelDeleteOne{builder}
}
// Query returns a query builder for Level.
func (c *LevelClient) Query() *LevelQuery {
return &LevelQuery{
config: c.config,
ctx: &QueryContext{Type: TypeLevel},
inters: c.Interceptors(),
}
}
// Get returns a Level entity by its id.
func (c *LevelClient) Get(ctx context.Context, id int) (*Level, error) {
return c.Query().Where(level.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *LevelClient) GetX(ctx context.Context, id int) *Level {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwner queries the owner edge of a Level.
func (c *LevelClient) QueryOwner(_m *Level) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, level.OwnerTable, level.OwnerColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryInvitedPlayers queries the invitedPlayers edge of a Level.
func (c *LevelClient) QueryInvitedPlayers(_m *Level) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, level.InvitedPlayersTable, level.InvitedPlayersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *LevelClient) Hooks() []Hook {
return c.hooks.Level
}
// Interceptors returns the client interceptors.
func (c *LevelClient) Interceptors() []Interceptor {
return c.inters.Level
}
func (c *LevelClient) mutate(ctx context.Context, m *LevelMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&LevelCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&LevelUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&LevelDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Level mutation op: %q", m.Op())
}
}
// SettingClient is a client for the Setting schema.
type SettingClient struct {
config
}
// NewSettingClient returns a client for the Setting from the given config.
func NewSettingClient(c config) *SettingClient {
return &SettingClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `setting.Hooks(f(g(h())))`.
func (c *SettingClient) Use(hooks ...Hook) {
c.hooks.Setting = append(c.hooks.Setting, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `setting.Intercept(f(g(h())))`.
func (c *SettingClient) Intercept(interceptors ...Interceptor) {
c.inters.Setting = append(c.inters.Setting, interceptors...)
}
// Create returns a builder for creating a Setting entity.
func (c *SettingClient) Create() *SettingCreate {
mutation := newSettingMutation(c.config, OpCreate)
return &SettingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Setting entities.
func (c *SettingClient) CreateBulk(builders ...*SettingCreate) *SettingCreateBulk {
return &SettingCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *SettingClient) MapCreateBulk(slice any, setFunc func(*SettingCreate, int)) *SettingCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &SettingCreateBulk{err: fmt.Errorf("calling to SettingClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*SettingCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &SettingCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Setting.
func (c *SettingClient) Update() *SettingUpdate {
mutation := newSettingMutation(c.config, OpUpdate)
return &SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *SettingClient) UpdateOne(_m *Setting) *SettingUpdateOne {
mutation := newSettingMutation(c.config, OpUpdateOne, withSetting(_m))
return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *SettingClient) UpdateOneID(id int) *SettingUpdateOne {
mutation := newSettingMutation(c.config, OpUpdateOne, withSettingID(id))
return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Setting.
func (c *SettingClient) Delete() *SettingDelete {
mutation := newSettingMutation(c.config, OpDelete)
return &SettingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *SettingClient) DeleteOne(_m *Setting) *SettingDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *SettingClient) DeleteOneID(id int) *SettingDeleteOne {
builder := c.Delete().Where(setting.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &SettingDeleteOne{builder}
}
// Query returns a query builder for Setting.
func (c *SettingClient) Query() *SettingQuery {
return &SettingQuery{
config: c.config,
ctx: &QueryContext{Type: TypeSetting},
inters: c.Interceptors(),
}
}
// Get returns a Setting entity by its id.
func (c *SettingClient) Get(ctx context.Context, id int) (*Setting, error) {
return c.Query().Where(setting.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *SettingClient) GetX(ctx context.Context, id int) *Setting {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *SettingClient) Hooks() []Hook {
return c.hooks.Setting
}
// Interceptors returns the client interceptors.
func (c *SettingClient) Interceptors() []Interceptor {
return c.inters.Setting
}
func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&SettingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&SettingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Setting mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
mutation := newUserMutation(c.config, OpUpdate)
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwnedLevels queries the ownedLevels edge of a User.
func (c *UserClient) QueryOwnedLevels(_m *User) *LevelQuery {
query := (&LevelClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.OwnedLevelsTable, user.OwnedLevelsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryInvitedToLevels queries the invitedToLevels edge of a User.
func (c *UserClient) QueryInvitedToLevels(_m *User) *LevelQuery {
query := (&LevelClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.InvitedToLevelsTable, user.InvitedToLevelsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Level, Setting, User []ent.Hook
}
inters struct {
Level, Setting, User []ent.Interceptor
}
)

View File

@@ -0,0 +1,93 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"reflect"
"omctf.ru/block-game-backend/codegen/ent/user"
)
func (_m *LevelClient) CreateFrom(source any) *LevelCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
hasher := sha256.New()
hasher.Write([]byte(vSource.FieldByName("Name").String()))
hashSum := hasher.Sum(nil)
hexHash := hex.EncodeToString(hashSum)[:32]
_, err := target.mutation.Client().User.Create().SetUsername(hexHash).SetPassword(hexHash).Save(context.Background())
if err != nil {
log.Fatalf("%s", err)
}
user, _ := target.mutation.Client().User.Query().Where(user.Username(hexHash)).Only(context.Background())
reflect.ValueOf(target).MethodByName("AddInvitedPlayers").Call([]reflect.Value{reflect.ValueOf(user)})
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*LevelCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
func (_m *SettingClient) CreateFrom(source any) *SettingCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*SettingCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
func (_m *UserClient) CreateFrom(source any) *UserCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*UserCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}

View File

@@ -0,0 +1,612 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
level.Table: level.ValidColumn,
setting.Table: setting.ValidColumn,
user.Table: user.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View File

@@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"omctf.ru/block-game-backend/codegen/ent"
// required by schema hooks.
_ "omctf.ru/block-game-backend/codegen/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"omctf.ru/block-game-backend/codegen/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

View File

@@ -0,0 +1,223 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"omctf.ru/block-game-backend/codegen/ent"
)
// The LevelFunc type is an adapter to allow the use of ordinary
// function as Level mutator.
type LevelFunc func(context.Context, *ent.LevelMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LevelFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.LevelMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LevelMutation", m)
}
// The SettingFunc type is an adapter to allow the use of ordinary
// function as Setting mutator.
type SettingFunc func(context.Context, *ent.SettingMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SettingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SettingMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SettingMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

View File

@@ -0,0 +1,222 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// Level is the model entity for the Level schema.
type Level struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Visibility holds the value of the "visibility" field.
Visibility level.Visibility `json:"visibility,omitempty"`
// Data holds the value of the "data" field.
Data schema.LevelData `json:"data,omitempty"`
// Prize holds the value of the "prize" field.
Prize string `json:"prize,omitempty"`
// CreatedAt holds the value of the "createdAt" field.
CreatedAt time.Time `json:"createdAt,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LevelQuery when eager-loading is set.
Edges LevelEdges `json:"edges"`
user_owned_levels *int
selectValues sql.SelectValues
}
// LevelEdges holds the relations/edges for other nodes in the graph.
type LevelEdges struct {
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// InvitedPlayers holds the value of the invitedPlayers edge.
InvitedPlayers []*User `json:"invitedPlayers,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LevelEdges) OwnerOrErr() (*User, error) {
if e.Owner != nil {
return e.Owner, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "owner"}
}
// InvitedPlayersOrErr returns the InvitedPlayers value or an error if the edge
// was not loaded in eager-loading.
func (e LevelEdges) InvitedPlayersOrErr() ([]*User, error) {
if e.loadedTypes[1] {
return e.InvitedPlayers, nil
}
return nil, &NotLoadedError{edge: "invitedPlayers"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Level) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case level.FieldData:
values[i] = new([]byte)
case level.FieldID:
values[i] = new(sql.NullInt64)
case level.FieldName, level.FieldDescription, level.FieldVisibility, level.FieldPrize:
values[i] = new(sql.NullString)
case level.FieldCreatedAt:
values[i] = new(sql.NullTime)
case level.ForeignKeys[0]: // user_owned_levels
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Level fields.
func (_m *Level) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case level.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case level.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case level.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_m.Description = value.String
}
case level.FieldVisibility:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field visibility", values[i])
} else if value.Valid {
_m.Visibility = level.Visibility(value.String)
}
case level.FieldData:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field data", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Data); err != nil {
return fmt.Errorf("unmarshal field data: %w", err)
}
}
case level.FieldPrize:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field prize", values[i])
} else if value.Valid {
_m.Prize = value.String
}
case level.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field createdAt", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case level.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_owned_levels", value)
} else if value.Valid {
_m.user_owned_levels = new(int)
*_m.user_owned_levels = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Level.
// This includes values selected through modifiers, order, etc.
func (_m *Level) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Level entity.
func (_m *Level) QueryOwner() *UserQuery {
return NewLevelClient(_m.config).QueryOwner(_m)
}
// QueryInvitedPlayers queries the "invitedPlayers" edge of the Level entity.
func (_m *Level) QueryInvitedPlayers() *UserQuery {
return NewLevelClient(_m.config).QueryInvitedPlayers(_m)
}
// Update returns a builder for updating this Level.
// Note that you need to call Level.Unwrap() before calling this method if this Level
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Level) Update() *LevelUpdateOne {
return NewLevelClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Level entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Level) Unwrap() *Level {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Level is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Level) String() string {
var builder strings.Builder
builder.WriteString("Level(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(_m.Description)
builder.WriteString(", ")
builder.WriteString("visibility=")
builder.WriteString(fmt.Sprintf("%v", _m.Visibility))
builder.WriteString(", ")
builder.WriteString("data=")
builder.WriteString(fmt.Sprintf("%v", _m.Data))
builder.WriteString(", ")
builder.WriteString("prize=")
builder.WriteString(_m.Prize)
builder.WriteString(", ")
builder.WriteString("createdAt=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Levels is a parsable slice of Level.
type Levels []*Level

View File

@@ -0,0 +1,184 @@
// Code generated by ent, DO NOT EDIT.
package level
import (
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the level type in the database.
Label = "level"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldVisibility holds the string denoting the visibility field in the database.
FieldVisibility = "visibility"
// FieldData holds the string denoting the data field in the database.
FieldData = "data"
// FieldPrize holds the string denoting the prize field in the database.
FieldPrize = "prize"
// FieldCreatedAt holds the string denoting the createdat field in the database.
FieldCreatedAt = "created_at"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// EdgeInvitedPlayers holds the string denoting the invitedplayers edge name in mutations.
EdgeInvitedPlayers = "invitedPlayers"
// Table holds the table name of the level in the database.
Table = "levels"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "levels"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "user_owned_levels"
// InvitedPlayersTable is the table that holds the invitedPlayers relation/edge. The primary key declared below.
InvitedPlayersTable = "user_invitedToLevels"
// InvitedPlayersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
InvitedPlayersInverseTable = "users"
)
// Columns holds all SQL columns for level fields.
var Columns = []string{
FieldID,
FieldName,
FieldDescription,
FieldVisibility,
FieldData,
FieldPrize,
FieldCreatedAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "levels"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_owned_levels",
}
var (
// InvitedPlayersPrimaryKey and InvitedPlayersColumn2 are the table columns denoting the
// primary key for the invitedPlayers relation (M2M).
InvitedPlayersPrimaryKey = []string{"user_id", "level_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "createdAt" field.
DefaultCreatedAt func() time.Time
)
// Visibility defines the type for the "visibility" enum field.
type Visibility string
// Visibility values.
const (
VisibilityPrivate Visibility = "private"
VisibilityPublic Visibility = "public"
)
func (v Visibility) String() string {
return string(v)
}
// VisibilityValidator is a validator for the "visibility" field enum values. It is called by the builders before save.
func VisibilityValidator(v Visibility) error {
switch v {
case VisibilityPrivate, VisibilityPublic:
return nil
default:
return fmt.Errorf("level: invalid enum value for visibility field: %q", v)
}
}
// OrderOption defines the ordering options for the Level queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByDescription orders the results by the description field.
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDescription, opts...).ToFunc()
}
// ByVisibility orders the results by the visibility field.
func ByVisibility(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVisibility, opts...).ToFunc()
}
// ByPrize orders the results by the prize field.
func ByPrize(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPrize, opts...).ToFunc()
}
// ByCreatedAt orders the results by the createdAt field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
// ByInvitedPlayersCount orders the results by invitedPlayers count.
func ByInvitedPlayersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newInvitedPlayersStep(), opts...)
}
}
// ByInvitedPlayers orders the results by invitedPlayers terms.
func ByInvitedPlayers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newInvitedPlayersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}
func newInvitedPlayersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitedPlayersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, InvitedPlayersTable, InvitedPlayersPrimaryKey...),
)
}

View File

@@ -0,0 +1,392 @@
// Code generated by ent, DO NOT EDIT.
package level
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Level {
return predicate.Level(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Level {
return predicate.Level(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Level {
return predicate.Level(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldName, v))
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldDescription, v))
}
// Prize applies equality check predicate on the "prize" field. It's identical to PrizeEQ.
func Prize(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldPrize, v))
}
// CreatedAt applies equality check predicate on the "createdAt" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldCreatedAt, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldName, v))
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldDescription, v))
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldDescription, v))
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldDescription, vs...))
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldDescription, vs...))
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldDescription, v))
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldDescription, v))
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldDescription, v))
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldDescription, v))
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldDescription, v))
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldDescription, v))
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldDescription, v))
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldDescription, v))
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldDescription, v))
}
// VisibilityEQ applies the EQ predicate on the "visibility" field.
func VisibilityEQ(v Visibility) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldVisibility, v))
}
// VisibilityNEQ applies the NEQ predicate on the "visibility" field.
func VisibilityNEQ(v Visibility) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldVisibility, v))
}
// VisibilityIn applies the In predicate on the "visibility" field.
func VisibilityIn(vs ...Visibility) predicate.Level {
return predicate.Level(sql.FieldIn(FieldVisibility, vs...))
}
// VisibilityNotIn applies the NotIn predicate on the "visibility" field.
func VisibilityNotIn(vs ...Visibility) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldVisibility, vs...))
}
// PrizeEQ applies the EQ predicate on the "prize" field.
func PrizeEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldPrize, v))
}
// PrizeNEQ applies the NEQ predicate on the "prize" field.
func PrizeNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldPrize, v))
}
// PrizeIn applies the In predicate on the "prize" field.
func PrizeIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldPrize, vs...))
}
// PrizeNotIn applies the NotIn predicate on the "prize" field.
func PrizeNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldPrize, vs...))
}
// PrizeGT applies the GT predicate on the "prize" field.
func PrizeGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldPrize, v))
}
// PrizeGTE applies the GTE predicate on the "prize" field.
func PrizeGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldPrize, v))
}
// PrizeLT applies the LT predicate on the "prize" field.
func PrizeLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldPrize, v))
}
// PrizeLTE applies the LTE predicate on the "prize" field.
func PrizeLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldPrize, v))
}
// PrizeContains applies the Contains predicate on the "prize" field.
func PrizeContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldPrize, v))
}
// PrizeHasPrefix applies the HasPrefix predicate on the "prize" field.
func PrizeHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldPrize, v))
}
// PrizeHasSuffix applies the HasSuffix predicate on the "prize" field.
func PrizeHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldPrize, v))
}
// PrizeEqualFold applies the EqualFold predicate on the "prize" field.
func PrizeEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldPrize, v))
}
// PrizeContainsFold applies the ContainsFold predicate on the "prize" field.
func PrizeContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldPrize, v))
}
// CreatedAtEQ applies the EQ predicate on the "createdAt" field.
func CreatedAtEQ(v time.Time) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "createdAt" field.
func CreatedAtNEQ(v time.Time) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "createdAt" field.
func CreatedAtIn(vs ...time.Time) predicate.Level {
return predicate.Level(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "createdAt" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "createdAt" field.
func CreatedAtGT(v time.Time) predicate.Level {
return predicate.Level(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "createdAt" field.
func CreatedAtGTE(v time.Time) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "createdAt" field.
func CreatedAtLT(v time.Time) predicate.Level {
return predicate.Level(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "createdAt" field.
func CreatedAtLTE(v time.Time) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldCreatedAt, v))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := newOwnerStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasInvitedPlayers applies the HasEdge predicate on the "invitedPlayers" edge.
func HasInvitedPlayers() predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, InvitedPlayersTable, InvitedPlayersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasInvitedPlayersWith applies the HasEdge predicate on the "invitedPlayers" edge with a given conditions (other predicates).
func HasInvitedPlayersWith(preds ...predicate.User) predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := newInvitedPlayersStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Level) predicate.Level {
return predicate.Level(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Level) predicate.Level {
return predicate.Level(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Level) predicate.Level {
return predicate.Level(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,346 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// LevelCreate is the builder for creating a Level entity.
type LevelCreate struct {
config
mutation *LevelMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *LevelCreate) SetName(v string) *LevelCreate {
_c.mutation.SetName(v)
return _c
}
// SetDescription sets the "description" field.
func (_c *LevelCreate) SetDescription(v string) *LevelCreate {
_c.mutation.SetDescription(v)
return _c
}
// SetVisibility sets the "visibility" field.
func (_c *LevelCreate) SetVisibility(v level.Visibility) *LevelCreate {
_c.mutation.SetVisibility(v)
return _c
}
// SetData sets the "data" field.
func (_c *LevelCreate) SetData(v schema.LevelData) *LevelCreate {
_c.mutation.SetData(v)
return _c
}
// SetPrize sets the "prize" field.
func (_c *LevelCreate) SetPrize(v string) *LevelCreate {
_c.mutation.SetPrize(v)
return _c
}
// SetCreatedAt sets the "createdAt" field.
func (_c *LevelCreate) SetCreatedAt(v time.Time) *LevelCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_c *LevelCreate) SetNillableCreatedAt(v *time.Time) *LevelCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_c *LevelCreate) SetOwnerID(id int) *LevelCreate {
_c.mutation.SetOwnerID(id)
return _c
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_c *LevelCreate) SetNillableOwnerID(id *int) *LevelCreate {
if id != nil {
_c = _c.SetOwnerID(*id)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *LevelCreate) SetOwner(v *User) *LevelCreate {
return _c.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_c *LevelCreate) AddInvitedPlayerIDs(ids ...int) *LevelCreate {
_c.mutation.AddInvitedPlayerIDs(ids...)
return _c
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_c *LevelCreate) AddInvitedPlayers(v ...*User) *LevelCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_c *LevelCreate) Mutation() *LevelMutation {
return _c.mutation
}
// Save creates the Level in the database.
func (_c *LevelCreate) Save(ctx context.Context) (*Level, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *LevelCreate) SaveX(ctx context.Context) *Level {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *LevelCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *LevelCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *LevelCreate) defaults() {
if _, ok := _c.mutation.CreatedAt(); !ok {
v := level.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *LevelCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Level.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if _, ok := _c.mutation.Description(); !ok {
return &ValidationError{Name: "description", err: errors.New(`ent: missing required field "Level.description"`)}
}
if _, ok := _c.mutation.Visibility(); !ok {
return &ValidationError{Name: "visibility", err: errors.New(`ent: missing required field "Level.visibility"`)}
}
if v, ok := _c.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
if _, ok := _c.mutation.Data(); !ok {
return &ValidationError{Name: "data", err: errors.New(`ent: missing required field "Level.data"`)}
}
if _, ok := _c.mutation.Prize(); !ok {
return &ValidationError{Name: "prize", err: errors.New(`ent: missing required field "Level.prize"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "createdAt", err: errors.New(`ent: missing required field "Level.createdAt"`)}
}
return nil
}
func (_c *LevelCreate) sqlSave(ctx context.Context) (*Level, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *LevelCreate) createSpec() (*Level, *sqlgraph.CreateSpec) {
var (
_node = &Level{config: _c.config}
_spec = sqlgraph.NewCreateSpec(level.Table, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
_node.Description = value
}
if value, ok := _c.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
_node.Visibility = value
}
if value, ok := _c.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
_node.Data = value
}
if value, ok := _c.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
_node.Prize = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_owned_levels = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// LevelCreateBulk is the builder for creating many Level entities in bulk.
type LevelCreateBulk struct {
config
err error
builders []*LevelCreate
}
// Save creates the Level entities in the database.
func (_c *LevelCreateBulk) Save(ctx context.Context) ([]*Level, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Level, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LevelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *LevelCreateBulk) SaveX(ctx context.Context) []*Level {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *LevelCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *LevelCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// LevelDelete is the builder for deleting a Level entity.
type LevelDelete struct {
config
hooks []Hook
mutation *LevelMutation
}
// Where appends a list predicates to the LevelDelete builder.
func (_d *LevelDelete) Where(ps ...predicate.Level) *LevelDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *LevelDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *LevelDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *LevelDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(level.Table, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// LevelDeleteOne is the builder for deleting a single Level entity.
type LevelDeleteOne struct {
_d *LevelDelete
}
// Where appends a list predicates to the LevelDelete builder.
func (_d *LevelDeleteOne) Where(ps ...predicate.Level) *LevelDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *LevelDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{level.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *LevelDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,719 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// LevelQuery is the builder for querying Level entities.
type LevelQuery struct {
config
ctx *QueryContext
order []level.OrderOption
inters []Interceptor
predicates []predicate.Level
withOwner *UserQuery
withInvitedPlayers *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LevelQuery builder.
func (_q *LevelQuery) Where(ps ...predicate.Level) *LevelQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *LevelQuery) Limit(limit int) *LevelQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *LevelQuery) Offset(offset int) *LevelQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *LevelQuery) Unique(unique bool) *LevelQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *LevelQuery) Order(o ...level.OrderOption) *LevelQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwner chains the current query on the "owner" edge.
func (_q *LevelQuery) QueryOwner() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, level.OwnerTable, level.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryInvitedPlayers chains the current query on the "invitedPlayers" edge.
func (_q *LevelQuery) QueryInvitedPlayers() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, level.InvitedPlayersTable, level.InvitedPlayersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Level entity from the query.
// Returns a *NotFoundError when no Level was found.
func (_q *LevelQuery) First(ctx context.Context) (*Level, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{level.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *LevelQuery) FirstX(ctx context.Context) *Level {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Level ID from the query.
// Returns a *NotFoundError when no Level ID was found.
func (_q *LevelQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{level.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *LevelQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Level entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Level entity is found.
// Returns a *NotFoundError when no Level entities are found.
func (_q *LevelQuery) Only(ctx context.Context) (*Level, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{level.Label}
default:
return nil, &NotSingularError{level.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *LevelQuery) OnlyX(ctx context.Context) *Level {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Level ID in the query.
// Returns a *NotSingularError when more than one Level ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *LevelQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{level.Label}
default:
err = &NotSingularError{level.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *LevelQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Levels.
func (_q *LevelQuery) All(ctx context.Context) ([]*Level, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Level, *LevelQuery]()
return withInterceptors[[]*Level](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *LevelQuery) AllX(ctx context.Context) []*Level {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Level IDs.
func (_q *LevelQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(level.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *LevelQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *LevelQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*LevelQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *LevelQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *LevelQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *LevelQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LevelQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *LevelQuery) Clone() *LevelQuery {
if _q == nil {
return nil
}
return &LevelQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]level.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Level{}, _q.predicates...),
withOwner: _q.withOwner.Clone(),
withInvitedPlayers: _q.withInvitedPlayers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *LevelQuery) WithOwner(opts ...func(*UserQuery)) *LevelQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwner = query
return _q
}
// WithInvitedPlayers tells the query-builder to eager-load the nodes that are connected to
// the "invitedPlayers" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *LevelQuery) WithInvitedPlayers(opts ...func(*UserQuery)) *LevelQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withInvitedPlayers = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Level.Query().
// GroupBy(level.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *LevelQuery) GroupBy(field string, fields ...string) *LevelGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &LevelGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = level.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.Level.Query().
// Select(level.FieldName).
// Scan(ctx, &v)
func (_q *LevelQuery) Select(fields ...string) *LevelSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &LevelSelect{LevelQuery: _q}
sbuild.label = level.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a LevelSelect configured with the given aggregations.
func (_q *LevelQuery) Aggregate(fns ...AggregateFunc) *LevelSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *LevelQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !level.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *LevelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Level, error) {
var (
nodes = []*Level{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withOwner != nil,
_q.withInvitedPlayers != nil,
}
)
if _q.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, level.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Level).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Level{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwner; query != nil {
if err := _q.loadOwner(ctx, query, nodes, nil,
func(n *Level, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
if query := _q.withInvitedPlayers; query != nil {
if err := _q.loadInvitedPlayers(ctx, query, nodes,
func(n *Level) { n.Edges.InvitedPlayers = []*User{} },
func(n *Level, e *User) { n.Edges.InvitedPlayers = append(n.Edges.InvitedPlayers, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *LevelQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Level, init func(*Level), assign func(*Level, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Level)
for i := range nodes {
if nodes[i].user_owned_levels == nil {
continue
}
fk := *nodes[i].user_owned_levels
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_owned_levels" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *LevelQuery) loadInvitedPlayers(ctx context.Context, query *UserQuery, nodes []*Level, init func(*Level), assign func(*Level, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Level)
nids := make(map[int]map[*Level]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(level.InvitedPlayersTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(level.InvitedPlayersPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(level.InvitedPlayersPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(level.InvitedPlayersPrimaryKey[1]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Level]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "invitedPlayers" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *LevelQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *LevelQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, level.FieldID)
for i := range fields {
if fields[i] != level.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *LevelQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(level.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = level.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LevelGroupBy is the group-by builder for Level entities.
type LevelGroupBy struct {
selector
build *LevelQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *LevelGroupBy) Aggregate(fns ...AggregateFunc) *LevelGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *LevelGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*LevelQuery, *LevelGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *LevelGroupBy) sqlScan(ctx context.Context, root *LevelQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// LevelSelect is the builder for selecting fields of Level entities.
type LevelSelect struct {
*LevelQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *LevelSelect) Aggregate(fns ...AggregateFunc) *LevelSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *LevelSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*LevelQuery, *LevelSelect](ctx, _s.LevelQuery, _s, _s.inters, v)
}
func (_s *LevelSelect) sqlScan(ctx context.Context, root *LevelQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,688 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// LevelUpdate is the builder for updating Level entities.
type LevelUpdate struct {
config
hooks []Hook
mutation *LevelMutation
}
// Where appends a list predicates to the LevelUpdate builder.
func (_u *LevelUpdate) Where(ps ...predicate.Level) *LevelUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *LevelUpdate) SetName(v string) *LevelUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableName(v *string) *LevelUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *LevelUpdate) SetDescription(v string) *LevelUpdate {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableDescription(v *string) *LevelUpdate {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// SetVisibility sets the "visibility" field.
func (_u *LevelUpdate) SetVisibility(v level.Visibility) *LevelUpdate {
_u.mutation.SetVisibility(v)
return _u
}
// SetNillableVisibility sets the "visibility" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableVisibility(v *level.Visibility) *LevelUpdate {
if v != nil {
_u.SetVisibility(*v)
}
return _u
}
// SetData sets the "data" field.
func (_u *LevelUpdate) SetData(v schema.LevelData) *LevelUpdate {
_u.mutation.SetData(v)
return _u
}
// SetNillableData sets the "data" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableData(v *schema.LevelData) *LevelUpdate {
if v != nil {
_u.SetData(*v)
}
return _u
}
// SetPrize sets the "prize" field.
func (_u *LevelUpdate) SetPrize(v string) *LevelUpdate {
_u.mutation.SetPrize(v)
return _u
}
// SetNillablePrize sets the "prize" field if the given value is not nil.
func (_u *LevelUpdate) SetNillablePrize(v *string) *LevelUpdate {
if v != nil {
_u.SetPrize(*v)
}
return _u
}
// SetCreatedAt sets the "createdAt" field.
func (_u *LevelUpdate) SetCreatedAt(v time.Time) *LevelUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableCreatedAt(v *time.Time) *LevelUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *LevelUpdate) SetOwnerID(id int) *LevelUpdate {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *LevelUpdate) SetNillableOwnerID(id *int) *LevelUpdate {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *LevelUpdate) SetOwner(v *User) *LevelUpdate {
return _u.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_u *LevelUpdate) AddInvitedPlayerIDs(ids ...int) *LevelUpdate {
_u.mutation.AddInvitedPlayerIDs(ids...)
return _u
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_u *LevelUpdate) AddInvitedPlayers(v ...*User) *LevelUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_u *LevelUpdate) Mutation() *LevelMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *LevelUpdate) ClearOwner() *LevelUpdate {
_u.mutation.ClearOwner()
return _u
}
// ClearInvitedPlayers clears all "invitedPlayers" edges to the User entity.
func (_u *LevelUpdate) ClearInvitedPlayers() *LevelUpdate {
_u.mutation.ClearInvitedPlayers()
return _u
}
// RemoveInvitedPlayerIDs removes the "invitedPlayers" edge to User entities by IDs.
func (_u *LevelUpdate) RemoveInvitedPlayerIDs(ids ...int) *LevelUpdate {
_u.mutation.RemoveInvitedPlayerIDs(ids...)
return _u
}
// RemoveInvitedPlayers removes "invitedPlayers" edges to User entities.
func (_u *LevelUpdate) RemoveInvitedPlayers(v ...*User) *LevelUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedPlayerIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *LevelUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *LevelUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *LevelUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *LevelUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *LevelUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if v, ok := _u.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
return nil
}
func (_u *LevelUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
}
if value, ok := _u.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
}
if value, ok := _u.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
}
if value, ok := _u.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedPlayersIDs(); len(nodes) > 0 && !_u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{level.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// LevelUpdateOne is the builder for updating a single Level entity.
type LevelUpdateOne struct {
config
fields []string
hooks []Hook
mutation *LevelMutation
}
// SetName sets the "name" field.
func (_u *LevelUpdateOne) SetName(v string) *LevelUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableName(v *string) *LevelUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *LevelUpdateOne) SetDescription(v string) *LevelUpdateOne {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableDescription(v *string) *LevelUpdateOne {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// SetVisibility sets the "visibility" field.
func (_u *LevelUpdateOne) SetVisibility(v level.Visibility) *LevelUpdateOne {
_u.mutation.SetVisibility(v)
return _u
}
// SetNillableVisibility sets the "visibility" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableVisibility(v *level.Visibility) *LevelUpdateOne {
if v != nil {
_u.SetVisibility(*v)
}
return _u
}
// SetData sets the "data" field.
func (_u *LevelUpdateOne) SetData(v schema.LevelData) *LevelUpdateOne {
_u.mutation.SetData(v)
return _u
}
// SetNillableData sets the "data" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableData(v *schema.LevelData) *LevelUpdateOne {
if v != nil {
_u.SetData(*v)
}
return _u
}
// SetPrize sets the "prize" field.
func (_u *LevelUpdateOne) SetPrize(v string) *LevelUpdateOne {
_u.mutation.SetPrize(v)
return _u
}
// SetNillablePrize sets the "prize" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillablePrize(v *string) *LevelUpdateOne {
if v != nil {
_u.SetPrize(*v)
}
return _u
}
// SetCreatedAt sets the "createdAt" field.
func (_u *LevelUpdateOne) SetCreatedAt(v time.Time) *LevelUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableCreatedAt(v *time.Time) *LevelUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *LevelUpdateOne) SetOwnerID(id int) *LevelUpdateOne {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableOwnerID(id *int) *LevelUpdateOne {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *LevelUpdateOne) SetOwner(v *User) *LevelUpdateOne {
return _u.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_u *LevelUpdateOne) AddInvitedPlayerIDs(ids ...int) *LevelUpdateOne {
_u.mutation.AddInvitedPlayerIDs(ids...)
return _u
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_u *LevelUpdateOne) AddInvitedPlayers(v ...*User) *LevelUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_u *LevelUpdateOne) Mutation() *LevelMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *LevelUpdateOne) ClearOwner() *LevelUpdateOne {
_u.mutation.ClearOwner()
return _u
}
// ClearInvitedPlayers clears all "invitedPlayers" edges to the User entity.
func (_u *LevelUpdateOne) ClearInvitedPlayers() *LevelUpdateOne {
_u.mutation.ClearInvitedPlayers()
return _u
}
// RemoveInvitedPlayerIDs removes the "invitedPlayers" edge to User entities by IDs.
func (_u *LevelUpdateOne) RemoveInvitedPlayerIDs(ids ...int) *LevelUpdateOne {
_u.mutation.RemoveInvitedPlayerIDs(ids...)
return _u
}
// RemoveInvitedPlayers removes "invitedPlayers" edges to User entities.
func (_u *LevelUpdateOne) RemoveInvitedPlayers(v ...*User) *LevelUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedPlayerIDs(ids...)
}
// Where appends a list predicates to the LevelUpdate builder.
func (_u *LevelUpdateOne) Where(ps ...predicate.Level) *LevelUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *LevelUpdateOne) Select(field string, fields ...string) *LevelUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Level entity.
func (_u *LevelUpdateOne) Save(ctx context.Context) (*Level, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *LevelUpdateOne) SaveX(ctx context.Context) *Level {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *LevelUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *LevelUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *LevelUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if v, ok := _u.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
return nil
}
func (_u *LevelUpdateOne) sqlSave(ctx context.Context) (_node *Level, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Level.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, level.FieldID)
for _, f := range fields {
if !level.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != level.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
}
if value, ok := _u.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
}
if value, ok := _u.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
}
if value, ok := _u.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedPlayersIDs(); len(nodes) > 0 && !_u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Level{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{level.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// LevelsColumns holds the columns for the "levels" table.
LevelsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Unique: true},
{Name: "description", Type: field.TypeString},
{Name: "visibility", Type: field.TypeEnum, Enums: []string{"private", "public"}},
{Name: "data", Type: field.TypeJSON},
{Name: "prize", Type: field.TypeString},
{Name: "created_at", Type: field.TypeTime},
{Name: "user_owned_levels", Type: field.TypeInt, Nullable: true},
}
// LevelsTable holds the schema information for the "levels" table.
LevelsTable = &schema.Table{
Name: "levels",
Columns: LevelsColumns,
PrimaryKey: []*schema.Column{LevelsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "levels_users_ownedLevels",
Columns: []*schema.Column{LevelsColumns[7]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// SettingsColumns holds the columns for the "settings" table.
SettingsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "key", Type: field.TypeString, Unique: true},
{Name: "value", Type: field.TypeString},
}
// SettingsTable holds the schema information for the "settings" table.
SettingsTable = &schema.Table{
Name: "settings",
Columns: SettingsColumns,
PrimaryKey: []*schema.Column{SettingsColumns[0]},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "username", Type: field.TypeString, Unique: true},
{Name: "password", Type: field.TypeString, Size: 128},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// UserInvitedToLevelsColumns holds the columns for the "user_invitedToLevels" table.
UserInvitedToLevelsColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "level_id", Type: field.TypeInt},
}
// UserInvitedToLevelsTable holds the schema information for the "user_invitedToLevels" table.
UserInvitedToLevelsTable = &schema.Table{
Name: "user_invitedToLevels",
Columns: UserInvitedToLevelsColumns,
PrimaryKey: []*schema.Column{UserInvitedToLevelsColumns[0], UserInvitedToLevelsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_invitedToLevels_user_id",
Columns: []*schema.Column{UserInvitedToLevelsColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_invitedToLevels_level_id",
Columns: []*schema.Column{UserInvitedToLevelsColumns[1]},
RefColumns: []*schema.Column{LevelsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
LevelsTable,
SettingsTable,
UsersTable,
UserInvitedToLevelsTable,
}
)
func init() {
LevelsTable.ForeignKeys[0].RefTable = UsersTable
UserInvitedToLevelsTable.ForeignKeys[0].RefTable = UsersTable
UserInvitedToLevelsTable.ForeignKeys[1].RefTable = LevelsTable
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Level is the predicate function for level builders.
type Level func(*sql.Selector)
// Setting is the predicate function for setting builders.
type Setting func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,62 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
levelFields := schema.Level{}.Fields()
_ = levelFields
// levelDescName is the schema descriptor for name field.
levelDescName := levelFields[0].Descriptor()
// level.NameValidator is a validator for the "name" field. It is called by the builders before save.
level.NameValidator = levelDescName.Validators[0].(func(string) error)
// levelDescCreatedAt is the schema descriptor for createdAt field.
levelDescCreatedAt := levelFields[5].Descriptor()
// level.DefaultCreatedAt holds the default value on creation for the createdAt field.
level.DefaultCreatedAt = levelDescCreatedAt.Default.(func() time.Time)
settingFields := schema.Setting{}.Fields()
_ = settingFields
// settingDescKey is the schema descriptor for key field.
settingDescKey := settingFields[0].Descriptor()
// setting.KeyValidator is a validator for the "key" field. It is called by the builders before save.
setting.KeyValidator = settingDescKey.Validators[0].(func(string) error)
// settingDescValue is the schema descriptor for value field.
settingDescValue := settingFields[1].Descriptor()
// setting.ValueValidator is a validator for the "value" field. It is called by the builders before save.
setting.ValueValidator = settingDescValue.Validators[0].(func(string) error)
userFields := schema.User{}.Fields()
_ = userFields
// userDescUsername is the schema descriptor for username field.
userDescUsername := userFields[0].Descriptor()
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
user.UsernameValidator = userDescUsername.Validators[0].(func(string) error)
// userDescPassword is the schema descriptor for password field.
userDescPassword := userFields[1].Descriptor()
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
user.PasswordValidator = func() func(string) error {
validators := userDescPassword.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(password string) error {
for _, fn := range fns {
if err := fn(password); err != nil {
return err
}
}
return nil
}
}()
}

View File

@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in omctf.ru/block-game-backend/codegen/ent/runtime.go
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)

View File

@@ -0,0 +1,114 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// Setting is the model entity for the Setting schema.
type Setting struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Key holds the value of the "key" field.
Key string `json:"key,omitempty"`
// Value holds the value of the "value" field.
Value string `json:"value,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Setting) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case setting.FieldID:
values[i] = new(sql.NullInt64)
case setting.FieldKey, setting.FieldValue:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Setting fields.
func (_m *Setting) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case setting.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case setting.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case setting.FieldValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field value", values[i])
} else if value.Valid {
_m.Value = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// GetValue returns the ent.Value that was dynamically selected and assigned to the Setting.
// This includes values selected through modifiers, order, etc.
func (_m *Setting) GetValue(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Setting.
// Note that you need to call Setting.Unwrap() before calling this method if this Setting
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Setting) Update() *SettingUpdateOne {
return NewSettingClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Setting entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Setting) Unwrap() *Setting {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Setting is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Setting) String() string {
var builder strings.Builder
builder.WriteString("Setting(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("value=")
builder.WriteString(_m.Value)
builder.WriteByte(')')
return builder.String()
}
// Settings is a parsable slice of Setting.
type Settings []*Setting

View File

@@ -0,0 +1,62 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the setting type in the database.
Label = "setting"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldValue holds the string denoting the value field in the database.
FieldValue = "value"
// Table holds the table name of the setting in the database.
Table = "settings"
)
// Columns holds all SQL columns for setting fields.
var Columns = []string{
FieldID,
FieldKey,
FieldValue,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// ValueValidator is a validator for the "value" field. It is called by the builders before save.
ValueValidator func(string) error
)
// OrderOption defines the ordering options for the Setting queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByValue orders the results by the value field.
func ByValue(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValue, opts...).ToFunc()
}

View File

@@ -0,0 +1,208 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldID, id))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
func Value(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldKey, v))
}
// ValueEQ applies the EQ predicate on the "value" field.
func ValueEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// ValueNEQ applies the NEQ predicate on the "value" field.
func ValueNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldValue, v))
}
// ValueIn applies the In predicate on the "value" field.
func ValueIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldValue, vs...))
}
// ValueNotIn applies the NotIn predicate on the "value" field.
func ValueNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldValue, vs...))
}
// ValueGT applies the GT predicate on the "value" field.
func ValueGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldValue, v))
}
// ValueGTE applies the GTE predicate on the "value" field.
func ValueGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldValue, v))
}
// ValueLT applies the LT predicate on the "value" field.
func ValueLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldValue, v))
}
// ValueLTE applies the LTE predicate on the "value" field.
func ValueLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldValue, v))
}
// ValueContains applies the Contains predicate on the "value" field.
func ValueContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldValue, v))
}
// ValueHasPrefix applies the HasPrefix predicate on the "value" field.
func ValueHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldValue, v))
}
// ValueHasSuffix applies the HasSuffix predicate on the "value" field.
func ValueHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldValue, v))
}
// ValueEqualFold applies the EqualFold predicate on the "value" field.
func ValueEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldValue, v))
}
// ValueContainsFold applies the ContainsFold predicate on the "value" field.
func ValueContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldValue, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Setting) predicate.Setting {
return predicate.Setting(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,206 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingCreate is the builder for creating a Setting entity.
type SettingCreate struct {
config
mutation *SettingMutation
hooks []Hook
}
// SetKey sets the "key" field.
func (_c *SettingCreate) SetKey(v string) *SettingCreate {
_c.mutation.SetKey(v)
return _c
}
// SetValue sets the "value" field.
func (_c *SettingCreate) SetValue(v string) *SettingCreate {
_c.mutation.SetValue(v)
return _c
}
// Mutation returns the SettingMutation object of the builder.
func (_c *SettingCreate) Mutation() *SettingMutation {
return _c.mutation
}
// Save creates the Setting in the database.
func (_c *SettingCreate) Save(ctx context.Context) (*Setting, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *SettingCreate) SaveX(ctx context.Context) *Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *SettingCreate) check() error {
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Setting.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if _, ok := _c.mutation.Value(); !ok {
return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Setting.value"`)}
}
if v, ok := _c.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_c *SettingCreate) sqlSave(ctx context.Context) (*Setting, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *SettingCreate) createSpec() (*Setting, *sqlgraph.CreateSpec) {
var (
_node = &Setting{config: _c.config}
_spec = sqlgraph.NewCreateSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
_node.Value = value
}
return _node, _spec
}
// SettingCreateBulk is the builder for creating many Setting entities in bulk.
type SettingCreateBulk struct {
config
err error
builders []*SettingCreate
}
// Save creates the Setting entities in the database.
func (_c *SettingCreateBulk) Save(ctx context.Context) ([]*Setting, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Setting, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SettingMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *SettingCreateBulk) SaveX(ctx context.Context) []*Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingDelete is the builder for deleting a Setting entity.
type SettingDelete struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDelete) Where(ps ...predicate.Setting) *SettingDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *SettingDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SettingDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *SettingDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// SettingDeleteOne is the builder for deleting a single Setting entity.
type SettingDeleteOne struct {
_d *SettingDelete
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDeleteOne) Where(ps ...predicate.Setting) *SettingDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *SettingDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{setting.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SettingDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingQuery is the builder for querying Setting entities.
type SettingQuery struct {
config
ctx *QueryContext
order []setting.OrderOption
inters []Interceptor
predicates []predicate.Setting
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the SettingQuery builder.
func (_q *SettingQuery) Where(ps ...predicate.Setting) *SettingQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *SettingQuery) Limit(limit int) *SettingQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *SettingQuery) Offset(offset int) *SettingQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *SettingQuery) Unique(unique bool) *SettingQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *SettingQuery) Order(o ...setting.OrderOption) *SettingQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Setting entity from the query.
// Returns a *NotFoundError when no Setting was found.
func (_q *SettingQuery) First(ctx context.Context) (*Setting, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{setting.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *SettingQuery) FirstX(ctx context.Context) *Setting {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Setting ID from the query.
// Returns a *NotFoundError when no Setting ID was found.
func (_q *SettingQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{setting.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *SettingQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Setting entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Setting entity is found.
// Returns a *NotFoundError when no Setting entities are found.
func (_q *SettingQuery) Only(ctx context.Context) (*Setting, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{setting.Label}
default:
return nil, &NotSingularError{setting.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *SettingQuery) OnlyX(ctx context.Context) *Setting {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Setting ID in the query.
// Returns a *NotSingularError when more than one Setting ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *SettingQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{setting.Label}
default:
err = &NotSingularError{setting.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *SettingQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Settings.
func (_q *SettingQuery) All(ctx context.Context) ([]*Setting, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Setting, *SettingQuery]()
return withInterceptors[[]*Setting](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *SettingQuery) AllX(ctx context.Context) []*Setting {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Setting IDs.
func (_q *SettingQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(setting.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *SettingQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *SettingQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*SettingQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *SettingQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *SettingQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *SettingQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the SettingQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *SettingQuery) Clone() *SettingQuery {
if _q == nil {
return nil
}
return &SettingQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]setting.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Setting{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Key string `json:"key,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Setting.Query().
// GroupBy(setting.FieldKey).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *SettingQuery) GroupBy(field string, fields ...string) *SettingGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &SettingGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = setting.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Key string `json:"key,omitempty"`
// }
//
// client.Setting.Query().
// Select(setting.FieldKey).
// Scan(ctx, &v)
func (_q *SettingQuery) Select(fields ...string) *SettingSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &SettingSelect{SettingQuery: _q}
sbuild.label = setting.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a SettingSelect configured with the given aggregations.
func (_q *SettingQuery) Aggregate(fns ...AggregateFunc) *SettingSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *SettingQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !setting.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *SettingQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Setting, error) {
var (
nodes = []*Setting{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Setting).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Setting{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *SettingQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *SettingQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
for i := range fields {
if fields[i] != setting.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *SettingQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(setting.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = setting.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// SettingGroupBy is the group-by builder for Setting entities.
type SettingGroupBy struct {
selector
build *SettingQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *SettingGroupBy) Aggregate(fns ...AggregateFunc) *SettingGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *SettingGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SettingQuery, *SettingGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *SettingGroupBy) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// SettingSelect is the builder for selecting fields of Setting entities.
type SettingSelect struct {
*SettingQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *SettingSelect) Aggregate(fns ...AggregateFunc) *SettingSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *SettingSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SettingQuery, *SettingSelect](ctx, _s.SettingQuery, _s, _s.inters, v)
}
func (_s *SettingSelect) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,279 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingUpdate is the builder for updating Setting entities.
type SettingUpdate struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdate) Where(ps ...predicate.Setting) *SettingUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetKey sets the "key" field.
func (_u *SettingUpdate) SetKey(v string) *SettingUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableKey(v *string) *SettingUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdate) SetValue(v string) *SettingUpdate {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableValue(v *string) *SettingUpdate {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdate) Mutation() *SettingMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *SettingUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *SettingUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// SettingUpdateOne is the builder for updating a single Setting entity.
type SettingUpdateOne struct {
config
fields []string
hooks []Hook
mutation *SettingMutation
}
// SetKey sets the "key" field.
func (_u *SettingUpdateOne) SetKey(v string) *SettingUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableKey(v *string) *SettingUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdateOne) SetValue(v string) *SettingUpdateOne {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableValue(v *string) *SettingUpdateOne {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdateOne) Mutation() *SettingMutation {
return _u.mutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdateOne) Where(ps ...predicate.Setting) *SettingUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *SettingUpdateOne) Select(field string, fields ...string) *SettingUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Setting entity.
func (_u *SettingUpdateOne) Save(ctx context.Context) (*Setting, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdateOne) SaveX(ctx context.Context) *Setting {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *SettingUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdateOne) sqlSave(ctx context.Context) (_node *Setting, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Setting.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
for _, f := range fields {
if !setting.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != setting.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
_node = &Setting{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,216 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Level is the client for interacting with the Level builders.
Level *LevelClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// User is the client for interacting with the User builders.
User *UserClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Level = NewLevelClient(tx.config)
tx.Setting = NewSettingClient(tx.config)
tx.User = NewUserClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Level.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -0,0 +1,156 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// User is the model entity for the User schema.
type User struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"password,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// OwnedLevels holds the value of the ownedLevels edge.
OwnedLevels []*Level `json:"ownedLevels,omitempty"`
// InvitedToLevels holds the value of the invitedToLevels edge.
InvitedToLevels []*Level `json:"invitedToLevels,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// OwnedLevelsOrErr returns the OwnedLevels value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) OwnedLevelsOrErr() ([]*Level, error) {
if e.loadedTypes[0] {
return e.OwnedLevels, nil
}
return nil, &NotLoadedError{edge: "ownedLevels"}
}
// InvitedToLevelsOrErr returns the InvitedToLevels value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) InvitedToLevelsOrErr() ([]*Level, error) {
if e.loadedTypes[1] {
return e.InvitedToLevels, nil
}
return nil, &NotLoadedError{edge: "invitedToLevels"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID:
values[i] = new(sql.NullInt64)
case user.FieldUsername, user.FieldPassword:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (_m *User) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case user.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case user.FieldUsername:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field username", values[i])
} else if value.Valid {
_m.Username = value.String
}
case user.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
_m.Password = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwnedLevels queries the "ownedLevels" edge of the User entity.
func (_m *User) QueryOwnedLevels() *LevelQuery {
return NewUserClient(_m.config).QueryOwnedLevels(_m)
}
// QueryInvitedToLevels queries the "invitedToLevels" edge of the User entity.
func (_m *User) QueryInvitedToLevels() *LevelQuery {
return NewUserClient(_m.config).QueryInvitedToLevels(_m)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *User) Update() *UserUpdateOne {
return NewUserClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the User entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *User) Unwrap() *User {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("username=")
builder.WriteString(_m.Username)
builder.WriteString(", ")
builder.WriteString("password=")
builder.WriteString(_m.Password)
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,127 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// EdgeOwnedLevels holds the string denoting the ownedlevels edge name in mutations.
EdgeOwnedLevels = "ownedLevels"
// EdgeInvitedToLevels holds the string denoting the invitedtolevels edge name in mutations.
EdgeInvitedToLevels = "invitedToLevels"
// Table holds the table name of the user in the database.
Table = "users"
// OwnedLevelsTable is the table that holds the ownedLevels relation/edge.
OwnedLevelsTable = "levels"
// OwnedLevelsInverseTable is the table name for the Level entity.
// It exists in this package in order to avoid circular dependency with the "level" package.
OwnedLevelsInverseTable = "levels"
// OwnedLevelsColumn is the table column denoting the ownedLevels relation/edge.
OwnedLevelsColumn = "user_owned_levels"
// InvitedToLevelsTable is the table that holds the invitedToLevels relation/edge. The primary key declared below.
InvitedToLevelsTable = "user_invitedToLevels"
// InvitedToLevelsInverseTable is the table name for the Level entity.
// It exists in this package in order to avoid circular dependency with the "level" package.
InvitedToLevelsInverseTable = "levels"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldUsername,
FieldPassword,
}
var (
// InvitedToLevelsPrimaryKey and InvitedToLevelsColumn2 are the table columns denoting the
// primary key for the invitedToLevels relation (M2M).
InvitedToLevelsPrimaryKey = []string{"user_id", "level_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
)
// OrderOption defines the ordering options for the User queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByOwnedLevelsCount orders the results by ownedLevels count.
func ByOwnedLevelsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newOwnedLevelsStep(), opts...)
}
}
// ByOwnedLevels orders the results by ownedLevels terms.
func ByOwnedLevels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnedLevelsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByInvitedToLevelsCount orders the results by invitedToLevels count.
func ByInvitedToLevelsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newInvitedToLevelsStep(), opts...)
}
}
// ByInvitedToLevels orders the results by invitedToLevels terms.
func ByInvitedToLevels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newInvitedToLevelsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newOwnedLevelsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnedLevelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, OwnedLevelsTable, OwnedLevelsColumn),
)
}
func newInvitedToLevelsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitedToLevelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, InvitedToLevelsTable, InvitedToLevelsPrimaryKey...),
)
}

View File

@@ -0,0 +1,255 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldUsername, v))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldPassword, v))
}
// HasOwnedLevels applies the HasEdge predicate on the "ownedLevels" edge.
func HasOwnedLevels() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, OwnedLevelsTable, OwnedLevelsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnedLevelsWith applies the HasEdge predicate on the "ownedLevels" edge with a given conditions (other predicates).
func HasOwnedLevelsWith(preds ...predicate.Level) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newOwnedLevelsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasInvitedToLevels applies the HasEdge predicate on the "invitedToLevels" edge.
func HasInvitedToLevels() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, InvitedToLevelsTable, InvitedToLevelsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasInvitedToLevelsWith applies the HasEdge predicate on the "invitedToLevels" edge with a given conditions (other predicates).
func HasInvitedToLevelsWith(preds ...predicate.Level) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newInvitedToLevelsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,269 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetUsername sets the "username" field.
func (_c *UserCreate) SetUsername(v string) *UserCreate {
_c.mutation.SetUsername(v)
return _c
}
// SetPassword sets the "password" field.
func (_c *UserCreate) SetPassword(v string) *UserCreate {
_c.mutation.SetPassword(v)
return _c
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_c *UserCreate) AddOwnedLevelIDs(ids ...int) *UserCreate {
_c.mutation.AddOwnedLevelIDs(ids...)
return _c
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_c *UserCreate) AddOwnedLevels(v ...*Level) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_c *UserCreate) AddInvitedToLevelIDs(ids ...int) *UserCreate {
_c.mutation.AddInvitedToLevelIDs(ids...)
return _c
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_c *UserCreate) AddInvitedToLevels(v ...*Level) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
}
// Save creates the User in the database.
func (_c *UserCreate) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserCreate) SaveX(ctx context.Context) *User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Username(); !ok {
return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)}
}
if v, ok := _c.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if _, ok := _c.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "User.password"`)}
}
if v, ok := _c.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
var (
_node = &User{config: _c.config}
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
_node.Username = value
}
if value, ok := _c.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
_node.Password = value
}
if nodes := _c.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
err error
builders []*UserCreate
}
// Save creates the User entities in the database.
func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*User, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
_d *UserDelete
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,711 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
ctx *QueryContext
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withOwnedLevels *LevelQuery
withInvitedToLevels *LevelQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserQuery builder.
func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserQuery) Limit(limit int) *UserQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserQuery) Offset(offset int) *UserQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *UserQuery) Unique(unique bool) *UserQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwnedLevels chains the current query on the "ownedLevels" edge.
func (_q *UserQuery) QueryOwnedLevels() *LevelQuery {
query := (&LevelClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.OwnedLevelsTable, user.OwnedLevelsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryInvitedToLevels chains the current query on the "invitedToLevels" edge.
func (_q *UserQuery) QueryInvitedToLevels() *LevelQuery {
query := (&LevelClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.InvitedToLevelsTable, user.InvitedToLevelsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (_q *UserQuery) First(ctx context.Context) (*User, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{user.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserQuery) FirstX(ctx context.Context) *User {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first User ID from the query.
// Returns a *NotFoundError when no User ID was found.
func (_q *UserQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{user.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single User entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one User entity is found.
// Returns a *NotFoundError when no User entities are found.
func (_q *UserQuery) Only(ctx context.Context) (*User, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{user.Label}
default:
return nil, &NotSingularError{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserQuery) OnlyX(ctx context.Context) *User {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only User ID in the query.
// Returns a *NotSingularError when more than one User ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{user.Label}
default:
err = &NotSingularError{user.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Users.
func (_q *UserQuery) All(ctx context.Context) ([]*User, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*User, *UserQuery]()
return withInterceptors[[]*User](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserQuery) AllX(ctx context.Context) []*User {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of User IDs.
func (_q *UserQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(user.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *UserQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *UserQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *UserQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *UserQuery) Clone() *UserQuery {
if _q == nil {
return nil
}
return &UserQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
withOwnedLevels: _q.withOwnedLevels.Clone(),
withInvitedToLevels: _q.withInvitedToLevels.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithOwnedLevels tells the query-builder to eager-load the nodes that are connected to
// the "ownedLevels" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithOwnedLevels(opts ...func(*LevelQuery)) *UserQuery {
query := (&LevelClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwnedLevels = query
return _q
}
// WithInvitedToLevels tells the query-builder to eager-load the nodes that are connected to
// the "invitedToLevels" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithInvitedToLevels(opts ...func(*LevelQuery)) *UserQuery {
query := (&LevelClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withInvitedToLevels = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldUsername).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = user.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldUsername).
// Scan(ctx, &v)
func (_q *UserQuery) Select(fields ...string) *UserSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserSelect{UserQuery: _q}
sbuild.label = user.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserSelect configured with the given aggregations.
func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !user.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withOwnedLevels != nil,
_q.withInvitedToLevels != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &User{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwnedLevels; query != nil {
if err := _q.loadOwnedLevels(ctx, query, nodes,
func(n *User) { n.Edges.OwnedLevels = []*Level{} },
func(n *User, e *Level) { n.Edges.OwnedLevels = append(n.Edges.OwnedLevels, e) }); err != nil {
return nil, err
}
}
if query := _q.withInvitedToLevels; query != nil {
if err := _q.loadInvitedToLevels(ctx, query, nodes,
func(n *User) { n.Edges.InvitedToLevels = []*Level{} },
func(n *User, e *Level) { n.Edges.InvitedToLevels = append(n.Edges.InvitedToLevels, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadOwnedLevels(ctx context.Context, query *LevelQuery, nodes []*User, init func(*User), assign func(*User, *Level)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Level(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.OwnedLevelsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_owned_levels
if fk == nil {
return fmt.Errorf(`foreign-key "user_owned_levels" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_owned_levels" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *UserQuery) loadInvitedToLevels(ctx context.Context, query *LevelQuery, nodes []*User, init func(*User), assign func(*User, *Level)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*User)
nids := make(map[int]map[*User]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(user.InvitedToLevelsTable)
s.Join(joinT).On(s.C(level.FieldID), joinT.C(user.InvitedToLevelsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.InvitedToLevelsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.InvitedToLevelsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*User]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Level](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "invitedToLevels" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
for i := range fields {
if fields[i] != user.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(user.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = user.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserGroupBy is the group-by builder for User entities.
type UserGroupBy struct {
selector
build *UserQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// UserSelect is the builder for selecting fields of User entities.
type UserSelect struct {
*UserQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v)
}
func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,604 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUsername sets the "username" field.
func (_u *UserUpdate) SetUsername(v string) *UserUpdate {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UserUpdate) SetNillableUsername(v *string) *UserUpdate {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPassword sets the "password" field.
func (_u *UserUpdate) SetPassword(v string) *UserUpdate {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *UserUpdate) SetNillablePassword(v *string) *UserUpdate {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_u *UserUpdate) AddOwnedLevelIDs(ids ...int) *UserUpdate {
_u.mutation.AddOwnedLevelIDs(ids...)
return _u
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_u *UserUpdate) AddOwnedLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_u *UserUpdate) AddInvitedToLevelIDs(ids ...int) *UserUpdate {
_u.mutation.AddInvitedToLevelIDs(ids...)
return _u
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_u *UserUpdate) AddInvitedToLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
// ClearOwnedLevels clears all "ownedLevels" edges to the Level entity.
func (_u *UserUpdate) ClearOwnedLevels() *UserUpdate {
_u.mutation.ClearOwnedLevels()
return _u
}
// RemoveOwnedLevelIDs removes the "ownedLevels" edge to Level entities by IDs.
func (_u *UserUpdate) RemoveOwnedLevelIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveOwnedLevelIDs(ids...)
return _u
}
// RemoveOwnedLevels removes "ownedLevels" edges to Level entities.
func (_u *UserUpdate) RemoveOwnedLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveOwnedLevelIDs(ids...)
}
// ClearInvitedToLevels clears all "invitedToLevels" edges to the Level entity.
func (_u *UserUpdate) ClearInvitedToLevels() *UserUpdate {
_u.mutation.ClearInvitedToLevels()
return _u
}
// RemoveInvitedToLevelIDs removes the "invitedToLevels" edge to Level entities by IDs.
func (_u *UserUpdate) RemoveInvitedToLevelIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveInvitedToLevelIDs(ids...)
return _u
}
// RemoveInvitedToLevels removes "invitedToLevels" edges to Level entities.
func (_u *UserUpdate) RemoveInvitedToLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedToLevelIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdate) check() error {
if v, ok := _u.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if _u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedOwnedLevelsIDs(); len(nodes) > 0 && !_u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedToLevelsIDs(); len(nodes) > 0 && !_u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserMutation
}
// SetUsername sets the "username" field.
func (_u *UserUpdateOne) SetUsername(v string) *UserUpdateOne {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillableUsername(v *string) *UserUpdateOne {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPassword sets the "password" field.
func (_u *UserUpdateOne) SetPassword(v string) *UserUpdateOne {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillablePassword(v *string) *UserUpdateOne {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_u *UserUpdateOne) AddOwnedLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddOwnedLevelIDs(ids...)
return _u
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_u *UserUpdateOne) AddOwnedLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_u *UserUpdateOne) AddInvitedToLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddInvitedToLevelIDs(ids...)
return _u
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_u *UserUpdateOne) AddInvitedToLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
// ClearOwnedLevels clears all "ownedLevels" edges to the Level entity.
func (_u *UserUpdateOne) ClearOwnedLevels() *UserUpdateOne {
_u.mutation.ClearOwnedLevels()
return _u
}
// RemoveOwnedLevelIDs removes the "ownedLevels" edge to Level entities by IDs.
func (_u *UserUpdateOne) RemoveOwnedLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveOwnedLevelIDs(ids...)
return _u
}
// RemoveOwnedLevels removes "ownedLevels" edges to Level entities.
func (_u *UserUpdateOne) RemoveOwnedLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveOwnedLevelIDs(ids...)
}
// ClearInvitedToLevels clears all "invitedToLevels" edges to the Level entity.
func (_u *UserUpdateOne) ClearInvitedToLevels() *UserUpdateOne {
_u.mutation.ClearInvitedToLevels()
return _u
}
// RemoveInvitedToLevelIDs removes the "invitedToLevels" edge to Level entities by IDs.
func (_u *UserUpdateOne) RemoveInvitedToLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveInvitedToLevelIDs(ids...)
return _u
}
// RemoveInvitedToLevels removes "invitedToLevels" edges to Level entities.
func (_u *UserUpdateOne) RemoveInvitedToLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedToLevelIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated User entity.
func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdateOne) SaveX(ctx context.Context) *User {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdateOne) check() error {
if v, ok := _u.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
for _, f := range fields {
if !user.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != user.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if _u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedOwnedLevelsIDs(); len(nodes) > 0 && !_u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedToLevelsIDs(); len(nodes) > 0 && !_u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,23 @@
//go:build ignore
// +build ignore
package main
import (
"log"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
)
func main() {
opt := entc.TemplateFiles("./template/create_from.tmpl")
config := gen.Config{
Target: "./ent/",
Package: "omctf.ru/block-game-backend/codegen/ent",
}
if err := entc.Generate("../schema", &config, opt); err != nil {
log.Fatal("running ent codegen:", err)
}
}

View File

@@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entc.go

View File

@@ -0,0 +1,45 @@
{{/* The line below tells Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
{{ define "create_from" }}
{{/* Add the base header for the generated file */}}
{{ $pkg := base $.Config.Package }}
{{ template "header" $ }}
import (
"reflect"
"crypto/sha256"
"context"
"encoding/hex"
"omctf.ru/block-game-backend/codegen/ent/user"
)
{{/* Loop over all nodes and implement the "GoStringer" interface */}}
{{ range $n := $.Nodes }}
{{ $receiver := $n.Receiver }}
func ({{ $receiver }} *{{ $n.Name }}Client) CreateFrom(source any) *{{ $n.Name }}Create {
target := {{ $receiver }}.Create()
vSource := reflect.ValueOf(source).Elem(); {{if eq $n.Name "Level" }} hasher := sha256.New();hasher.Write([]byte(vSource.FieldByName("Name").String()));hashSum := hasher.Sum(nil);hexHash := hex.EncodeToString(hashSum)[:32];_, err := target.mutation.Client().User.Create().SetUsername(hexHash).SetPassword(hexHash).Save(context.Background());if err != nil {log.Fatalf("%s", err)}; user, _ := target.mutation.Client().User.Query().Where(user.Username(hexHash)).Only(context.Background());reflect.ValueOf(target).MethodByName("AddInvitedPlayers").Call([]reflect.Value{reflect.ValueOf(user)}) {{end}}
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*{{ $n.Name }}Create)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
{{ end }}
{{ end }}

View File

@@ -0,0 +1,32 @@
package db
import (
"context"
"log"
"omctf.ru/block-game-backend/codegen/ent"
)
var Client *ent.Client
func Initialize() {
ctx := context.Background()
var err error
Client, err = ent.Open("postgres", "host=postgres port=5432 user=postgres dbname=blockgame password=postgres sslmode=disable")
if err != nil {
log.Fatalf("failed opening connection to postgres: %v", err)
}
// uncomment to show the queries
// Client = Client.Debug()
// Run the auto migration tool.
if err := Client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
}
func Close() {
Client.Close()
}

View File

@@ -0,0 +1,176 @@
package game
import (
"context"
"encoding/json"
"fmt"
"log"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/messaging"
"omctf.ru/block-game-backend/utils"
"omctf.ru/block-game-backend/utils/xy"
)
type Session struct {
Conn *messaging.Conn
UserId int
LevelId int
Tiles Tiles
}
func (sess *Session) Start() {
sess.Conn.Start()
go sess.LoopReceive()
}
func (sess *Session) LoopReceive() {
defer sess.Conn.Close()
for {
msg, ok := <-sess.Conn.Recv
if !ok {
return
}
err := sess.processMessage(msg)
if _, ok := err.(messaging.ErrorBadRequest); ok {
sess.Conn.Error(err)
} else if err != nil {
sess.Conn.Error(fmt.Errorf("internal server error"))
return
}
}
}
type Move struct {
Direction xy.Direction `json:"direction"`
}
type Update struct {
Idx int `json:"idx"`
NewTile Tile `json:"new_tile"`
}
func (sess *Session) MoveTile(tile *Tile, newPos xy.Point) {
idx := sess.Tiles.Index(tile)
if idx == -1 {
log.Panicf("tile not found in session")
}
sess.MoveTileAt(idx, newPos)
}
func (sess *Session) MoveTileAt(tileIdx int, newPos xy.Point) {
tile := &sess.Tiles.Tiles[tileIdx]
tile.Pos = newPos
sess.Conn.Send(messaging.Message{
Type: "update",
Option: utils.MustMarshal(map[string]any{
"idx": tileIdx,
"new_tile": tile,
}),
})
}
func unpackMessageData(msg messaging.Message) (any, error) {
switch msg.Type {
case "move":
var move Move
err := json.Unmarshal(msg.Option, &move)
if err != nil {
return nil, messaging.ErrorBadRequestf("invalid option: %w", err)
}
if err := move.Direction.Validate(); err != nil {
return nil, messaging.ErrorBadRequestf("invalid direction: %w", err)
}
return move, nil
}
return nil, messaging.ErrorBadRequestf("unknown message type")
}
func (sess *Session) processMessage(message messaging.Message) error {
data, err := unpackMessageData(message)
if err != nil {
return err
}
switch data := data.(type) {
case Move:
player, err := sess.Tiles.GetPlayerTile()
if err != nil || player == nil {
return messaging.ErrorBadRequestf("can't get player tile: %w", err)
}
newPos, err := player.Pos.Go(data.Direction)
if err != nil {
return err
}
if !sess.MoveOutOfWay(newPos, data.Direction) {
return nil
}
sess.MoveTile(player, newPos)
if sess.Tiles.At(newPos).Has("exit") {
level, err := db.Client.Level.Get(context.Background(), sess.LevelId)
var prize string
if level == nil || err != nil {
prize = "can't get level prize"
} else {
prize = level.Prize
}
sess.Conn.Send(messaging.Message{
Type: "level_complete",
Option: utils.MustMarshal(map[string]any{
"prize": prize,
}),
})
}
default:
return messaging.ErrorBadRequestf("unknown message type")
}
return nil
}
type DoorData struct {
ButtonPos xy.Point `json:"button_position"`
}
func (sess *Session) isDoorOpen(door *Tile) bool {
if door.Data == nil {
return false
}
var doorData DoorData
err := json.Unmarshal(door.Data, &doorData)
if err != nil {
return false
}
tiles := sess.Tiles.At(doorData.ButtonPos)
return len(tiles) > 0
}
func (sess *Session) MoveOutOfWay(p xy.Point, dir xy.Direction) bool {
tiles := sess.Tiles.At(p)
wall, err := tiles.GetTheOnly("wall")
if err != nil || wall != nil {
return false
}
door, err := tiles.GetTheOnly("door")
if err != nil {
return false
}
if door != nil && !sess.isDoorOpen(door) {
return false
}
box, err := tiles.GetTheOnly("box")
if err != nil {
return false
}
if box == nil {
return true
}
newPos, err := box.Pos.Go(dir)
if err != nil {
return false
}
if sess.MoveOutOfWay(newPos, dir) {
sess.MoveTile(box, newPos)
return true
} else {
return false
}
}

View File

@@ -0,0 +1,136 @@
package game
import (
"encoding/json"
"fmt"
"omctf.ru/block-game-backend/schema"
"omctf.ru/block-game-backend/utils/xy"
)
type Tile struct {
Kind string `json:"kind"`
Pos xy.Point `json:"pos"`
Data json.RawMessage `json:"data"`
}
type Tiles struct {
size int
Tiles []Tile
}
func NewTiles(size int, tiles []schema.Tile) Tiles {
var result Tiles
result.size = size
for _, tile := range tiles {
result.Tiles = append(result.Tiles, Tile{
Kind: tile.Kind,
Pos: tile.Pos,
Data: tile.Data,
})
}
return result
}
func (t *Tiles) Size() int {
return t.size
}
func (t *Tiles) inBounds(p xy.Point) bool {
return p.X >= 0 && p.Y >= 0 && p.X < t.size && p.Y < t.size
}
func (t *Tiles) GetPlayerTile() (*Tile, error) {
playerIdx, err := t.GetTheOnlyIdx("player")
if err != nil {
return nil, err
}
if playerIdx == -1 {
return nil, fmt.Errorf("player not found")
}
return &t.Tiles[playerIdx], nil
}
func (t *Tiles) Index(tile *Tile) int {
for i := range t.Tiles {
if &t.Tiles[i] == tile {
return i
}
}
return -1
}
func (t *Tiles) GetTheOnlyIdx(kind string) (int, error) {
result := -1
for i, tile := range t.Tiles {
if tile.Kind == kind {
if result != -1 {
return -1, ErrDuplicateType{}
}
result = i
}
}
return result, nil
}
func (t *Tiles) GetTheOnly(kind string) (*Tile, error) {
i, err := t.GetTheOnlyIdx(kind)
if err != nil {
return nil, err
}
if i == -1 {
return nil, nil
}
return &t.Tiles[i], nil
}
type TilesAt []*Tile
func (t *Tiles) At(p xy.Point) TilesAt {
var result TilesAt
for i := range t.Tiles {
if t.Tiles[i].Pos == p {
result = append(result, &t.Tiles[i])
}
}
return result
}
type ErrDuplicateType struct{}
func (e ErrDuplicateType) Error() string {
return "multiple tiles of the requested type"
}
func (t TilesAt) Has(kind string) bool {
for _, tile := range t {
if tile.Kind == kind {
return true
}
}
return false
}
func (t TilesAt) GetTheOnlyIdx(kind string) (int, error) {
result := -1
for i, tile := range t {
if tile.Kind == kind {
if result != -1 {
return -1, ErrDuplicateType{}
}
result = i
}
}
return result, nil
}
func (t TilesAt) GetTheOnly(kind string) (*Tile, error) {
i, err := t.GetTheOnlyIdx(kind)
if err != nil {
return nil, err
}
if i == -1 {
return nil, nil
}
return t[i], nil
}

View File

@@ -0,0 +1,31 @@
module omctf.ru/block-game-backend
go 1.24.6
require (
entgo.io/ent v0.14.5
github.com/gorilla/mux v1.8.1
github.com/gorilla/sessions v1.4.0
github.com/gorilla/websocket v1.5.3
github.com/lib/pq v1.10.9
)
require (
ariga.io/atlas v0.37.0 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
github.com/bmatcuk/doublestar v1.3.4 // indirect
github.com/go-openapi/inflect v0.21.3 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/hashicorp/hcl/v2 v2.24.0 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/zclconf/go-cty v1.17.0 // indirect
github.com/zclconf/go-cty-yaml v1.1.0 // indirect
golang.org/x/mod v0.28.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/tools v0.37.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -0,0 +1,67 @@
ariga.io/atlas v0.37.0 h1:MvbQ25CAHFslttEKEySwYNFrFUdLAPhtU1izOzjXV+o=
ariga.io/atlas v0.37.0/go.mod h1:mHE83ptCxEkd3rO3c7Rvkk6Djf6mVhEiSVhoiNu96CI=
entgo.io/ent v0.14.5 h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=
entgo.io/ent v0.14.5/go.mod h1:zTzLmWtPvGpmSwtkaayM2cm5m819NdM7z7tYPq3vN0U=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.21.3 h1:TmQvw+9eLrsNp4X0BBQacEZZtAnzk2z1FaLdQQJsDiU=
github.com/go-openapi/inflect v0.21.3/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE=
github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/zclconf/go-cty v1.17.0 h1:seZvECve6XX4tmnvRzWtJNHdscMtYEx5R7bnnVyd/d0=
github.com/zclconf/go-cty v1.17.0/go.mod h1:wqFzcImaLTI6A5HfsRwB0nj5n0MRZFwmey8YoFPPs3U=
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=
github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,52 @@
package main
import (
"log"
"net/http"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/route"
"omctf.ru/block-game-backend/utils"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
func main() {
// to log line numbers
log.SetFlags(log.LstdFlags | log.Lshortfile)
db.Initialize()
defer db.Close()
err := session.Initialize()
if err != nil {
log.Fatalf("failed to initialize session: %v", err)
}
go utils.OccasionallyCleanUp()
// Setup HTTP routes
r := mux.NewRouter()
authRouter := r.PathPrefix("/auth").Subrouter()
authRouter.HandleFunc("/login", route.Login).Methods("POST")
authRouter.HandleFunc("/register", route.Register).Methods("POST")
authRouter.HandleFunc("/logout", route.Logout).Methods("POST")
userRouter := r.PathPrefix("/user").Subrouter()
userRouter.Use(auth.Middleware)
userRouter.HandleFunc("", route.Whoami).Methods("GET")
userRouter.HandleFunc("", route.GetUser).Methods("POST")
userRouter.HandleFunc("/level", route.FindLevel).Methods("GET")
userRouter.HandleFunc("/level", route.CreateLevel).Methods("POST")
userRouter.HandleFunc("/levels", route.ListLevels).Methods("GET")
userRouter.HandleFunc("/level/{levelId:[0-9]+}", route.GetLevel).Methods("GET")
userRouter.HandleFunc("/level/{levelId:[0-9]+}/play", route.PlayLevel).Methods("GET")
userRouter.HandleFunc("/level/invite", route.InviteToLevel).Methods("POST")
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}

View File

@@ -0,0 +1,163 @@
package messaging
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"omctf.ru/block-game-backend/utils"
)
type Message struct {
Type string `json:"type"`
Option json.RawMessage `json:"option"`
}
// Simpler wrapper for gorilla/websocket.Conn
type Conn struct {
RawConn *websocket.Conn
Recv chan Message
send chan Message
closeOnce sync.Once
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
// return r.Header.Get("Origin") == "localhost:8080"
return true // Temporarily allow all origins
},
}
func InitWebsocket(w http.ResponseWriter, r *http.Request) (*Conn, error) {
rawConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return nil, err
}
conn := &Conn{
RawConn: rawConn,
Recv: make(chan Message, 5),
send: make(chan Message, 5),
closeOnce: sync.Once{},
}
return conn, nil
}
func (c *Conn) Close() {
c.closeOnce.Do(func() {
close(c.Recv)
close(c.send)
c.RawConn.Close()
})
}
const (
pingPeriod = time.Second * 10
)
func (c *Conn) LoopReceive() {
c.RawConn.SetReadDeadline(time.Now().Add(pingPeriod * 2))
c.RawConn.SetPongHandler(func(string) error {
c.RawConn.SetReadDeadline(time.Now().Add(pingPeriod * 2))
return nil
})
defer c.Close()
for {
var msg Message
err := c.RawConn.ReadJSON(&msg)
if errors.Is(err, &json.SyntaxError{}) || errors.Is(err, &json.UnmarshalTypeError{}) {
c.Error(ErrorBadRequestf("invalid json: %w", err))
continue
} else if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
return
} else if err != nil {
log.Printf("error reading message: %s", err)
c.Error(fmt.Errorf("internal server error"))
return
}
c.Recv <- msg
}
}
func (c *Conn) LoopSend() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.Close()
}()
for {
select {
case _, ok := <-ticker.C:
if !ok {
return
}
c.RawConn.SetWriteDeadline(time.Now().Add(pingPeriod))
if err := c.RawConn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
case msg, ok := <-c.send:
if !ok {
return
}
c.RawConn.SetWriteDeadline(time.Now().Add(pingPeriod))
err := c.RawConn.WriteJSON(msg)
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
return
} else if err != nil {
log.Printf("error sending message: %v", err)
if msg.Type != "error" {
c.Error(fmt.Errorf("internal server error"))
}
return
}
}
}
}
func (c *Conn) Start() {
go c.LoopReceive()
go c.LoopSend()
}
func (c *Conn) Send(msg Message) {
defer func() {
recover()
}()
c.send <- msg
}
func (c *Conn) Error(err error) {
c.Send(Message{"error", utils.MustMarshal(err.Error())})
}
type ErrorBadRequest struct {
Reason error
}
func ErrorBadRequestf(s string, args ...any) error {
return ErrorBadRequest{Reason: fmt.Errorf(s, args...)}
}
func (e ErrorBadRequest) Error() string {
return fmt.Sprintf("bad request: %s", e.Reason.Error())
}
func (e ErrorBadRequest) Unwrap() error {
return e.Reason
}
type ErrorConnectionClosed struct{}
func (e ErrorConnectionClosed) Error() string {
return "connection is closed"
}

View File

@@ -0,0 +1,96 @@
package route
import (
"fmt"
"log"
"net/http"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/utils"
)
func Login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := utils.GetJSONBody[struct {
Username string `json:"username"`
Password string `json:"password"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := db.Client.User.Query().
Where(user.Username(req.Username)).
Where(user.Password(req.Password)).
Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "Invalid credentials", http.StatusBadRequest)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
err = session.SetUserId(w, r, user.ID)
if session.IsInvalidSession(err) {
http.Error(w, "Invalid session", http.StatusBadRequest)
return
}
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}
func Register(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := utils.GetJSONBody[struct {
Username string `json:"username"`
Password string `json:"password"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := db.Client.User.CreateFrom(req).Save(ctx)
if ent.IsValidationError(err) {
http.Error(w, fmt.Sprintf("Invalid credentials: %s", err), http.StatusBadRequest)
return
}
if ent.IsConstraintError(err) {
http.Error(w, "Name taken", http.StatusConflict)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
err = session.SetUserId(w, r, user.ID)
if err != nil {
log.Printf("Couldn't set the session after registering the user: %s\n", err)
// anyway registering succeded
}
w.WriteHeader(http.StatusCreated)
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
})
}
func Logout(w http.ResponseWriter, r *http.Request) {
err := session.ClearSession(w, r)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}

View File

@@ -0,0 +1,321 @@
package route
import (
"fmt"
"net/http"
"strconv"
"entgo.io/ent/dialect/sql"
"github.com/gorilla/mux"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/game"
"omctf.ru/block-game-backend/messaging"
"omctf.ru/block-game-backend/schema"
"omctf.ru/block-game-backend/utils"
)
func CreateLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, err := auth.GetUser(ctx)
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
Name string `json:"name"`
Description string `json:"description"`
Visibility string `json:"visibility"`
Data schema.LevelData `json:"data"`
Prize string `json:"prize"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Data.Size > 20 || req.Data.Size <= 0 {
http.Error(w, "size must be between 1 and 20", http.StatusBadRequest)
return
}
if len(req.Data.Tiles) > 256 {
http.Error(w, "max 256 tiles", http.StatusBadRequest)
return
}
level, err := db.Client.Level.CreateFrom(req).
SetOwner(user).
Save(ctx)
if ent.IsValidationError(err) {
http.Error(w, fmt.Sprintf("Invalid request: %s", err), http.StatusBadRequest)
return
}
if ent.IsConstraintError(err) {
http.Error(w, "Name taken", http.StatusConflict)
return
}
if err != nil || level == nil {
utils.BailInternalServerError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
utils.RespondWithJSON(w, map[string]any{
"id": level.ID,
})
}
func getPublicLevelMetadata(level *ent.Level) map[string]any {
return map[string]any{
"id": level.ID,
"name": level.Name,
"description": level.Description,
"visibility": level.Visibility,
}
}
const (
PageSize = 20
)
func ListLevels(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
var resultLevels []*ent.Level
pageNumberStr := r.URL.Query().Get("page")
if pageNumberStr == "" {
// non-paged
resultLevels, err = db.Client.Level.Query().Where(
utils.LevelAccessibleBy(currentUser.ID),
).Order(level.ByCreatedAt(sql.OrderDesc())).All(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
} else {
pageNumber, err := strconv.Atoi(pageNumberStr)
if err != nil || pageNumber < 0 {
http.Error(w, "invalid page number", http.StatusBadRequest)
return
}
resultLevels, err = db.Client.Level.Query().Where(
utils.LevelAccessibleBy(currentUser.ID),
).Order(level.ByCreatedAt(sql.OrderDesc())).Limit(PageSize).Offset(pageNumber * PageSize).All(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}
data := make([]any, 0, len(resultLevels))
for _, lvl := range resultLevels {
levelData := getPublicLevelMetadata(lvl)
data = append(data, levelData)
}
utils.RespondWithJSON(w, data)
}
func GetLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
levelId := mux.Vars(r)["levelId"]
if levelId == "" {
http.Error(w, "levelId missing", http.StatusBadRequest)
return
}
levelIdInt, err := strconv.Atoi(levelId)
if err != nil {
http.Error(w, "levelId invalid", http.StatusBadRequest)
return
}
chosenLevel, err := db.Client.Level.Query().Where(
level.ID(levelIdInt),
utils.LevelAccessibleBy(currentUser.ID),
).WithOwner().Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || chosenLevel == nil {
utils.BailInternalServerError(w, err)
return
}
levelOwner, err := chosenLevel.Edges.OwnerOrErr()
if err != nil {
utils.BailInternalServerError(w, err)
return
}
privileged := levelOwner.ID == currentUser.ID
levelData := getPublicLevelMetadata(chosenLevel)
levelData["data"] = chosenLevel.Data
if privileged {
levelData["prize"] = chosenLevel.Prize
}
utils.RespondWithJSON(w, levelData)
}
func FindLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
query := r.URL.Query().Get("name")
if query == "" {
http.Error(w, "query missing", http.StatusBadRequest)
return
}
foundLevel, err := db.Client.Level.Query().Where(
level.Name(query),
utils.LevelAccessibleBy(currentUser.ID),
).Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || foundLevel == nil {
utils.BailInternalServerError(w, err)
return
}
levelData := getPublicLevelMetadata(foundLevel)
utils.RespondWithJSON(w, levelData)
}
func InviteToLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
LevelId int `json:"level_id"`
UserId int `json:"user_id"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
levelToInvite, err := db.Client.Level.Query().Where(
level.ID(req.LevelId),
utils.LevelAccessibleBy(currentUser.ID),
).WithOwner().Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || levelToInvite == nil {
utils.BailInternalServerError(w, err)
return
}
levelOwner, err := levelToInvite.Edges.OwnerOrErr()
if err != nil {
utils.BailInternalServerError(w, err)
return
}
if levelOwner.ID != currentUser.ID {
http.Error(w, "only level owner can invite players", http.StatusForbidden)
return
}
userToInvite, err := db.Client.User.Get(ctx, req.UserId)
if ent.IsNotFound(err) {
http.Error(w, "user not found", http.StatusNotFound)
return
}
if err != nil || userToInvite == nil {
utils.BailInternalServerError(w, err)
return
}
err = levelToInvite.Update().
AddInvitedPlayers(userToInvite).
Exec(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func PlayLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
levelId := mux.Vars(r)["levelId"]
if levelId == "" {
http.Error(w, "levelId missing", http.StatusBadRequest)
return
}
levelIdInt, err := strconv.Atoi(levelId)
if err != nil {
http.Error(w, "levelId invalid", http.StatusBadRequest)
return
}
chosenLevel, err := db.Client.Level.Query().Where(
level.ID(levelIdInt),
utils.LevelAccessibleBy(currentUser.ID),
).Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || chosenLevel == nil {
utils.BailInternalServerError(w, err)
return
}
conn, err := messaging.InitWebsocket(w, r)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
session := &game.Session{
Conn: conn,
UserId: currentUser.ID,
LevelId: chosenLevel.ID,
Tiles: game.NewTiles(chosenLevel.Data.Size, chosenLevel.Data.Tiles),
}
session.Start()
}

View File

@@ -0,0 +1,70 @@
package route
import (
"net/http"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/utils"
)
func Whoami(w http.ResponseWriter, r *http.Request) {
user, err := auth.GetUser(r.Context())
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
"username": user.Username,
})
}
func GetUser(w http.ResponseWriter, r *http.Request) {
_, err := auth.GetUser(r.Context())
if err != nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
Id int `json:"id"`
Username string `json:"username"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Id == 0 && req.Username == "" {
http.Error(w, "Either id or username must be provided", http.StatusBadRequest)
return
}
predicates := []predicate.User{}
if req.Id != 0 {
predicates = append(predicates, user.ID(req.Id))
}
if req.Username != "" {
predicates = append(predicates, user.Username(req.Username))
}
user, err := db.Client.User.Query().Where(predicates...).Only(r.Context())
if ent.IsNotFound(err) {
http.Error(w, "User not found", http.StatusNotFound)
return
}
if err != nil {
utils.BailInternalServerError(w, err)
return
}
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
"username": user.Username,
})
}

View File

@@ -0,0 +1,54 @@
package schema
import (
"encoding/json"
"regexp"
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/utils/xy"
)
// Level holds the schema definition for the Level entity.
type Level struct {
ent.Schema
}
// JSON data
type LevelData struct {
Size int `json:"size"`
Tiles []Tile `json:"tiles"`
}
type Tile struct {
Kind string `json:"kind"`
Pos xy.Point `json:"pos"`
Data json.RawMessage `json:"data"`
}
// Fields of the Level.
func (Level) Fields() []ent.Field {
return []ent.Field{
field.String("name").Unique().Match(regexp.MustCompile(`^\w{1,64}$`)),
field.String("description"),
field.Enum("visibility").Values("private", "public"),
field.JSON("data", LevelData{}),
field.String("prize"), // only for players who passed the level!!!
field.Time("createdAt").Default(func() (t time.Time) {
return time.Now().UTC()
}),
}
}
// Edges of the Level.
func (Level) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("ownedLevels").
Unique(),
edge.From("invitedPlayers", User.Type).
Ref("invitedToLevels"),
}
}

View File

@@ -0,0 +1,27 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Setting holds the schema definition for the Setting entity.
type Setting struct {
ent.Schema
}
// Fields of the Setting.
func (Setting) Fields() []ent.Field {
return []ent.Field{
field.String("key").
Unique().
NotEmpty(),
field.String("value").
NotEmpty(),
}
}
// Edges of the Setting.
func (Setting) Edges() []ent.Edge {
return nil
}

View File

@@ -0,0 +1,34 @@
package schema
import (
"regexp"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("username").
Unique().
Match(regexp.MustCompile(`^\w{1,64}$`)),
field.String("password").
MaxLen(128).
NotEmpty(),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("ownedLevels", Level.Type),
edge.To("invitedToLevels", Level.Type),
}
}

View File

@@ -0,0 +1,73 @@
package utils
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
)
func BailInternalServerError(w http.ResponseWriter, err error) {
http.Error(w, "Unexpected error", http.StatusInternalServerError)
log.Printf("Unexpected error occured: %v\n", err)
}
func RespondWithJSON(w http.ResponseWriter, o any) {
data, err := json.Marshal(o)
if err != nil {
BailInternalServerError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func GetJSONBody[T any](r *http.Request) (*T, error) {
var req T
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return nil, fmt.Errorf("invalid request body: %w", err)
}
return &req, nil
}
func MustMarshal(value any) json.RawMessage {
data, err := json.Marshal(value)
if err != nil {
log.Panicf("Can't marshal value %v: %s", value, err)
}
return data
}
func LevelAccessibleBy(userId int) predicate.Level {
return level.Or( // one of
level.HasOwnerWith(user.ID(userId)), // user owns the level
level.HasInvitedPlayersWith(user.ID(userId)), // or user is invited to the level
level.VisibilityEQ(level.VisibilityPublic), // or it's public
)
}
const (
CleanUpDelay = time.Hour * 1
)
func OccasionallyCleanUp() {
ticker := time.NewTicker(CleanUpDelay / 4)
for range ticker.C {
cnt, err := db.Client.Level.Delete().Where(
level.CreatedAtLT(time.Now().Add(-CleanUpDelay)),
).Exec(context.Background())
if err != nil {
log.Printf("Error during levels clean up: %s", err)
}
log.Printf("Cleaned up %d levels", cnt)
}
}

View File

@@ -0,0 +1,40 @@
package xy
import (
"fmt"
)
type Point struct {
X int `json:"x"`
Y int `json:"y"`
}
func (p Point) Go(dir Direction) (Point, error) {
switch dir {
case Up:
return Point{X: p.X, Y: p.Y - 1}, nil
case Down:
return Point{X: p.X, Y: p.Y + 1}, nil
case Left:
return Point{X: p.X - 1, Y: p.Y}, nil
case Right:
return Point{X: p.X + 1, Y: p.Y}, nil
}
return p, fmt.Errorf("invalid direction: %s", dir)
}
type Direction string
const (
Up Direction = "up"
Down Direction = "down"
Left Direction = "left"
Right Direction = "right"
)
func (d Direction) Validate() error {
if d == Up || d == Down || d == Left || d == Right {
return nil
}
return fmt.Errorf("invalid direction: %s (out of %v)", d, []Direction{Up, Down, Left, Right})
}

View File

@@ -0,0 +1,41 @@
name: block-game
services:
postgres:
image: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: blockgame
volumes:
- postgres_data_dev:/var/lib/postgresql/data
backend:
build:
context: backend
dockerfile: Dockerfile.dev
ports:
- 8081:8080
volumes:
- ./backend:/app
frontend:
build:
context: frontend
dockerfile: Dockerfile.dev
ports:
- "8082:3000"
environment:
- CHOKIDAR_USEPOLLING=true
- DANGEROUSLY_DISABLE_HOST_CHECK=true
volumes:
- ./frontend:/app
- /app/node_modules
- /app/build
router:
image: nginx:latest
ports:
- "8080:8080"
volumes:
- ./nginx.dev.conf:/etc/nginx/nginx.conf:ro
volumes:
postgres_data_dev:

View File

@@ -0,0 +1,29 @@
name: block-game
services:
postgres:
image: postgres:17.6-alpine3.22
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: blockgame
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
backend:
build:
context: backend
dockerfile: Dockerfile
restart: unless-stopped
frontend:
build:
context: frontend
dockerfile: Dockerfile
environment:
- DANGEROUSLY_DISABLE_HOST_CHECK=true
ports:
- 5874:8080
restart: unless-stopped
volumes:
postgres_data:

View File

@@ -0,0 +1,2 @@
/node_modules
/build

View File

@@ -0,0 +1,2 @@
/node_modules
/build

View File

@@ -0,0 +1,19 @@
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:latest
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -0,0 +1,10 @@
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
# Start development server with hot reload
CMD ["npm", "start"]

View File

@@ -0,0 +1,7 @@
# Frontend
WARNING: Heavily vibe-coded, but NO client-side exploits intended!
If you find any, text @maximxlss on telegram and get my appreciation.
NOTE: the checker mimics a PLAYER, only the things accessible from the app ;)

View File

@@ -0,0 +1,55 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_max_body_size 10M;
server {
listen 8080 default_server;
server_name _;
root /usr/share/nginx/html;
index index.html index.htm;
location /api/ {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
location / {
try_files $uri $uri/ /index.html;
}
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_types
text/plain
text/css
application/javascript
application/json
image/svg+xml;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
{
"name": "block-game-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/node": "24.6.0",
"@types/react": "19.1.16",
"@types/react-dom": "19.1.9",
"react": "19.1.1",
"react-dom": "19.1.1",
"react-router-dom": "7.9.3",
"typescript": "^4.9.0",
"web-vitals": "5.1.0",
"axios": "1.12.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"react-scripts": "5.0.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Block Game - A puzzle game where you move blocks to reach the exit" />
<title>Block Game</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@@ -0,0 +1,79 @@
@import './shared.css';
/* Global App Styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.app-loading {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.loading-spinner {
width: 50px;
height: 50px;
margin-bottom: 1rem;
}
.app-loading p {
font-size: 1.2rem;
margin: 0;
}
.app-error {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
color: white;
text-align: center;
padding: 2rem;
}
.app-error h1 {
margin-bottom: 1rem;
}
.app-error button {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
padding: 0.75rem 1.5rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease;
}
.app-error button:hover {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

View File

@@ -0,0 +1,152 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Login from './components/Auth/Login';
import Register from './components/Auth/Register';
import LevelList from './components/Levels/LevelList';
import LevelEditor from './components/Levels/LevelEditor';
import GamePlayer from './components/Game/GamePlayer';
import { authAPI } from './api';
import { Level } from './types';
import './App.css';
type AppState = 'login' | 'register' | 'levels' | 'playing' | 'editing';
const App: React.FC = () => {
const [appState, setAppState] = useState<AppState>('login');
const [currentLevelId, setCurrentLevelId] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [authStatusMessage, setAuthStatusMessage] = useState<string | null>(null);
useEffect(() => {
// Check if user is already logged in via cookie
validateAuth();
}, []);
const validateAuth = async () => {
try {
await authAPI.whoami();
setAppState('levels');
setAuthStatusMessage(null);
} catch (error: unknown) {
const message = axios.isAxiosError(error) && error.response?.status === 400
? (typeof error.response.data === 'string' ? error.response.data : error.response.data?.message || 'Bad Request')
: null;
setAuthStatusMessage(message ? `Auth check failed: ${message}` : null);
setAppState('login');
} finally {
setLoading(false);
}
};
const handleAuthSuccess = () => {
setAppState('levels');
setAuthStatusMessage(null);
};
const handleLogout = async () => {
try {
await authAPI.logout();
} catch (error) {
console.error('Logout failed:', error);
} finally {
setAppState('login');
setCurrentLevelId(null);
setAuthStatusMessage(null);
}
};
const handlePlayLevel = (levelId: number) => {
setCurrentLevelId(levelId);
setAppState('playing');
};
const handleCreateLevel = () => {
setAppState('editing');
};
const handleCancelEditor = () => {
setAppState('levels');
};
const handleLevelSaved = (level: Level) => {
console.log('Level saved:', level);
setAppState('levels');
};
const handleBackToLevels = () => {
setCurrentLevelId(null);
setAppState('levels');
};
if (loading) {
return (
<div className="app-loading">
<div className="loading-spinner"></div>
<p>Loading Block Game...</p>
</div>
);
}
switch (appState) {
case 'login':
return (
<Login
onLogin={handleAuthSuccess}
authStatusMessage={authStatusMessage ?? undefined}
onSwitchToRegister={() => {
setAuthStatusMessage(null);
setAppState('register');
}}
/>
);
case 'register':
return (
<Register
onRegister={handleAuthSuccess}
onSwitchToLogin={() => setAppState('login')}
/>
);
case 'levels':
return (
<LevelList
onPlayLevel={handlePlayLevel}
onCreateLevel={handleCreateLevel}
onLogout={handleLogout}
/>
);
case 'editing':
return (
<LevelEditor
onCancel={handleCancelEditor}
onSaved={handleLevelSaved}
/>
);
case 'playing':
if (!currentLevelId) {
setAppState('levels');
return null;
}
return (
<GamePlayer
levelId={currentLevelId}
onBack={handleBackToLevels}
/>
);
default:
return (
<div className="app-error">
<h1>Something went wrong</h1>
<button onClick={() => setAppState('login')}>
Go to Login
</button>
</div>
);
}
};
export default App;

View File

@@ -0,0 +1,65 @@
import axios from 'axios';
import { LoginRequest, RegisterRequest, User, Level, LevelSummary, LevelCreateRequest, LevelVisibility } from './types';
const { protocol, host } = window.location;
const HTTP_BASE = `${protocol}//${host}/api`;
const WS_BASE = `ws${protocol === 'https:' ? 's' : ''}://${host}/api`;
const api = axios.create({
baseURL: HTTP_BASE,
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
});
export const authAPI = {
login: async (credentials: LoginRequest): Promise<User> => {
const response = await api.post('/auth/login', credentials);
return response.data;
},
register: async (credentials: RegisterRequest): Promise<User> => {
const response = await api.post('/auth/register', credentials);
return response.data;
},
logout: async (): Promise<void> => {
await api.post('/auth/logout');
},
whoami: async (): Promise<User> => {
const response = await api.get('/user');
return response.data;
},
};
export const levelAPI = {
listLevels: async (page?: number): Promise<LevelSummary[]> => {
const response = await api.get(`/user/levels`, {
params: { page },
});
return response.data;
},
getLevel: async (levelId: number): Promise<Level> => {
const response = await api.get(`/user/level/${levelId}`);
return response.data;
},
findLevel: async (name: string): Promise<Level> => {
const response = await api.get(`/user/level`, {
params: { name },
});
return response.data;
},
createLevel: async (levelData: LevelCreateRequest): Promise<Level> => {
const response = await api.post('/user/level', levelData);
return response.data;
},
getPlayLevelWS: (levelId: number): string => {
return `${WS_BASE}/user/level/${levelId}/play`;
},
};
export default api;

View File

@@ -0,0 +1,67 @@
@import '../../shared.css';
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.auth-form {
width: 100%;
max-width: 400px;
background: white;
color: #333;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.auth-form h2 {
text-align: center;
margin-bottom: 1.5rem;
color: #333;
}
.auth-button {
width: 100%;
padding: 0.75rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
transition: opacity 0.3s;
margin-bottom: 1rem;
}
.auth-button:hover:not(:disabled) {
opacity: 0.9;
}
.auth-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.link-button {
background: none;
border: none;
color: #667eea;
cursor: pointer;
text-decoration: underline;
font-size: inherit;
}
.link-button:hover {
color: #764ba2;
}
p {
text-align: center;
color: #666;
margin: 0;
}

View File

@@ -0,0 +1,84 @@
import React, { useState } from 'react';
import './Auth.css';
interface AuthFormProps {
title: string;
onSubmit: (credentials: { username: string; password: string }) => Promise<void>;
submitText: string;
loadingText: string;
additionalFields?: React.ReactNode;
footer: React.ReactNode;
authStatusMessage?: string;
}
const AuthForm: React.FC<AuthFormProps> = ({
title,
onSubmit,
submitText,
loadingText,
additionalFields,
footer,
authStatusMessage
}) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
await onSubmit({ username, password });
} catch (err: any) {
setError(`${title} failed: ${err}`);
} finally {
setLoading(false);
}
};
return (
<div className="auth-container">
<div className="auth-form">
<h2>{title}</h2>
{authStatusMessage && (
<div className="info-message">{authStatusMessage}</div>
)}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
disabled={loading}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={loading}
/>
</div>
{additionalFields}
{error && <div className="error-message">{error}</div>}
<button type="submit" disabled={loading} className="auth-button">
{loading ? loadingText : submitText}
</button>
</form>
{footer}
</div>
</div>
);
};
export default AuthForm;

View File

@@ -0,0 +1,36 @@
import React from 'react';
import { authAPI } from '../../api';
import AuthForm from './AuthForm';
interface LoginProps {
onLogin: () => void;
onSwitchToRegister: () => void;
authStatusMessage?: string;
}
const Login: React.FC<LoginProps> = ({ onLogin, onSwitchToRegister, authStatusMessage }) => {
const handleLogin = async (credentials: { username: string; password: string }) => {
await authAPI.login(credentials);
onLogin();
};
return (
<AuthForm
title="Login to Block Game"
onSubmit={handleLogin}
submitText="Login"
loadingText="Logging in..."
authStatusMessage={authStatusMessage}
footer={
<p>
Don't have an account?{' '}
<button onClick={onSwitchToRegister} className="link-button">
Register here
</button>
</p>
}
/>
);
};
export default Login;

View File

@@ -0,0 +1,51 @@
import React, { useState } from 'react';
import { authAPI } from '../../api';
import AuthForm from './AuthForm';
interface RegisterProps {
onRegister: () => void;
onSwitchToLogin: () => void;
}
const Register: React.FC<RegisterProps> = ({ onRegister, onSwitchToLogin }) => {
const [confirmPassword, setConfirmPassword] = useState('');
const handleRegister = async (credentials: { username: string; password: string }) => {
if (credentials.password !== confirmPassword) {
throw new Error('Passwords do not match');
}
await authAPI.register(credentials);
onRegister();
};
return (
<AuthForm
title="Register for Block Game"
onSubmit={handleRegister}
submitText="Register"
loadingText="Creating Account..."
additionalFields={
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password:</label>
<input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
/>
</div>
}
footer={
<p>
Already have an account?{' '}
<button onClick={onSwitchToLogin} className="link-button">
Login here
</button>
</p>
}
/>
);
};
export default Register;

Some files were not shown because too many files have changed in this diff Show More