first commit
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
name: Deploy Territory Autobattler Auth API
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: self-hosted
|
||||
|
||||
env:
|
||||
IMAGE_NAME: territory-autobattler-auth:latest
|
||||
IMAGE_TAR: /tmp/territory-autobattler-auth.tar
|
||||
NAMESPACE: territory-autobattler
|
||||
DEPLOYMENT_NAME: territory-autobattler-auth
|
||||
NODES: "192.168.86.72 192.168.86.73 192.168.86.74"
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build Docker image
|
||||
run: |
|
||||
cd microservices/AuthApi
|
||||
docker build -t "${IMAGE_NAME}" .
|
||||
|
||||
- name: Save Docker image to TAR
|
||||
run: |
|
||||
docker save "${IMAGE_NAME}" -o "${IMAGE_TAR}"
|
||||
|
||||
- name: Copy TAR to nodes
|
||||
run: |
|
||||
for node in ${NODES}; do
|
||||
echo "Copying image tar to $node ..."
|
||||
scp -o StrictHostKeyChecking=no "${IMAGE_TAR}" hz@"$node":"${IMAGE_TAR}"
|
||||
done
|
||||
|
||||
- name: Import image on nodes
|
||||
run: |
|
||||
for node in ${NODES}; do
|
||||
echo "Importing image on $node ..."
|
||||
ssh -o StrictHostKeyChecking=no hz@"$node" "sudo ctr -n k8s.io images import ${IMAGE_TAR}"
|
||||
done
|
||||
|
||||
- name: Clean TAR from nodes
|
||||
run: |
|
||||
for node in ${NODES}; do
|
||||
echo "Removing image tar on $node ..."
|
||||
ssh -o StrictHostKeyChecking=no hz@"$node" "rm -f ${IMAGE_TAR}"
|
||||
done
|
||||
|
||||
- name: Clean TAR on runner
|
||||
run: |
|
||||
rm -f "${IMAGE_TAR}"
|
||||
|
||||
- name: Write kubeconfig from secret
|
||||
env:
|
||||
KUBECONFIG_CONTENT: ${{ secrets.KUBECONFIG }}
|
||||
run: |
|
||||
mkdir -p /tmp/kube
|
||||
printf '%s\n' "$KUBECONFIG_CONTENT" > /tmp/kube/config
|
||||
|
||||
- name: Create namespace if missing
|
||||
env:
|
||||
KUBECONFIG: /tmp/kube/config
|
||||
run: |
|
||||
kubectl create namespace "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -
|
||||
|
||||
- name: Apply Auth manifests
|
||||
env:
|
||||
KUBECONFIG: /tmp/kube/config
|
||||
run: |
|
||||
kubectl apply -f microservices/AuthApi/k8s/configmap.yaml
|
||||
kubectl apply -f microservices/AuthApi/k8s/secret.yaml
|
||||
kubectl apply -f microservices/AuthApi/k8s/deployment.yaml
|
||||
kubectl apply -f microservices/AuthApi/k8s/service.yaml
|
||||
|
||||
- name: Restart Auth deployment
|
||||
env:
|
||||
KUBECONFIG: /tmp/kube/config
|
||||
run: |
|
||||
kubectl rollout restart deployment/"${DEPLOYMENT_NAME}" -n "${NAMESPACE}"
|
||||
kubectl rollout status deployment/"${DEPLOYMENT_NAME}" -n "${NAMESPACE}"
|
||||
@@ -0,0 +1,28 @@
|
||||
name: k8s smoke test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: self-hosted
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Write kubeconfig from secret
|
||||
env:
|
||||
KUBECONFIG_CONTENT: ${{ secrets.KUBECONFIG }}
|
||||
run: |
|
||||
mkdir -p /tmp/kube
|
||||
printf '%s\n' "$KUBECONFIG_CONTENT" > /tmp/kube/config
|
||||
|
||||
- name: Test kubectl connectivity
|
||||
env:
|
||||
KUBECONFIG: /tmp/kube/config
|
||||
run: |
|
||||
kubectl get nodes --kubeconfig "${KUBECONFIG}"
|
||||
@@ -0,0 +1,4 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
@@ -0,0 +1,2 @@
|
||||
# Normalize EOL for all files that Git considers text files.
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,3 @@
|
||||
# Godot 4+ specific ignores
|
||||
.godot/
|
||||
/android/
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
uid://mcipi7y664aq
|
||||
@@ -0,0 +1,7 @@
|
||||
[plugin]
|
||||
|
||||
name="Godot MCP"
|
||||
description="A plugin to enable communication between Godot Editor and Model Context Protocol (MCP) clients."
|
||||
author="Your Name"
|
||||
version="0.1.0"
|
||||
script="plugin.gd"
|
||||
@@ -0,0 +1,140 @@
|
||||
# Structure for addons/godot_mcp/plugin.gd
|
||||
@tool
|
||||
extends EditorPlugin
|
||||
|
||||
const SERVER_PORT = 6400
|
||||
var server: TCPServer = null
|
||||
var active_connections = []
|
||||
var command_handler
|
||||
|
||||
func _enter_tree():
|
||||
# Initialize the plugin
|
||||
print("Godot MCP Plugin activated")
|
||||
|
||||
# Create command handler
|
||||
command_handler = preload("res://addons/godot_mcp/command_handler.gd").new()
|
||||
command_handler.set_editor_plugin(self)
|
||||
|
||||
# Start the TCP server
|
||||
server = TCPServer.new()
|
||||
var error = server.listen(SERVER_PORT)
|
||||
if error != OK:
|
||||
push_error("Failed to start Godot MCP Server on port %d: %s" % [SERVER_PORT, error])
|
||||
return
|
||||
|
||||
print("Godot MCP Server listening on port %d" % SERVER_PORT)
|
||||
|
||||
# Add UI
|
||||
add_control_to_bottom_panel(
|
||||
preload("res://addons/godot_mcp/ui/mcp_panel.tscn").instantiate(),
|
||||
"MCP"
|
||||
)
|
||||
|
||||
func _exit_tree():
|
||||
# Clean up the plugin when disabled
|
||||
if server:
|
||||
server.stop()
|
||||
server = null
|
||||
|
||||
for connection in active_connections:
|
||||
if connection.get_status() == StreamPeerTCP.STATUS_CONNECTED:
|
||||
connection.disconnect_from_host()
|
||||
|
||||
active_connections.clear()
|
||||
|
||||
# Remove UI
|
||||
remove_control_from_bottom_panel(get_editor_interface().get_base_control().get_node("MCPPanel"))
|
||||
print("Godot MCP Plugin deactivated")
|
||||
|
||||
func _process(delta):
|
||||
# Check for new connections
|
||||
if server and server.is_connection_available():
|
||||
var connection = server.take_connection()
|
||||
if connection:
|
||||
active_connections.append(connection)
|
||||
print("New MCP connection established")
|
||||
|
||||
# Process existing connections
|
||||
var i = 0
|
||||
while i < active_connections.size():
|
||||
var connection = active_connections[i]
|
||||
|
||||
# Check connection status
|
||||
if connection.get_status() != StreamPeerTCP.STATUS_CONNECTED:
|
||||
active_connections.remove_at(i)
|
||||
print("MCP connection closed")
|
||||
continue
|
||||
|
||||
# Check for incoming messages
|
||||
if connection.get_available_bytes() > 0:
|
||||
var data = _read_message(connection)
|
||||
if data.size() > 0:
|
||||
# Process the command
|
||||
var response = _process_command(data)
|
||||
|
||||
# Send the response
|
||||
_send_message(connection, response)
|
||||
|
||||
i += 1
|
||||
|
||||
func _read_message(connection):
|
||||
# Read data from the connection
|
||||
var data = PackedByteArray()
|
||||
var bytes_available = connection.get_available_bytes()
|
||||
|
||||
if bytes_available > 0:
|
||||
data = connection.get_data(bytes_available)[1]
|
||||
|
||||
# Attempt to parse as JSON
|
||||
var json_string = data.get_string_from_utf8()
|
||||
var json = JSON.new()
|
||||
var error = json.parse(json_string)
|
||||
|
||||
if error == OK:
|
||||
return json.get_data()
|
||||
else:
|
||||
print("Failed to parse JSON: ", json.get_error_message())
|
||||
|
||||
return {}
|
||||
|
||||
func _send_message(connection, data):
|
||||
# Convert to JSON and send
|
||||
var json_string = JSON.stringify(data)
|
||||
connection.put_data(json_string.to_utf8_buffer())
|
||||
|
||||
|
||||
|
||||
func _process_command(data):
|
||||
# Process the command and return a response
|
||||
if data == null or typeof(data) != TYPE_DICTIONARY:
|
||||
return {
|
||||
"status": "error",
|
||||
"error": "Invalid command format. Expected a dictionary."
|
||||
}
|
||||
|
||||
if not data.has("type") or not data.has("params"):
|
||||
return {
|
||||
"status": "error",
|
||||
"error": "Invalid command format. Expected 'type' and 'params' fields."
|
||||
}
|
||||
|
||||
var command_type = data["type"]
|
||||
var params = data["params"]
|
||||
|
||||
if command_type == "ping":
|
||||
return {"status": "success", "result": {"message": "pong"}}
|
||||
|
||||
# Forward to command handler
|
||||
var result = command_handler.handle_command(command_type, params)
|
||||
|
||||
# Check if result is valid
|
||||
if result == null:
|
||||
return {
|
||||
"status": "error",
|
||||
"error": "Command handler returned null result"
|
||||
}
|
||||
|
||||
if result.has("error"):
|
||||
return {"status": "error", "error": result.error}
|
||||
else:
|
||||
return {"status": "success", "result": result}
|
||||
@@ -0,0 +1 @@
|
||||
uid://ddfhkiyge45tn
|
||||
@@ -0,0 +1,77 @@
|
||||
# addons/godot_mcp/ui/mcp_panel.gd
|
||||
@tool
|
||||
extends Control
|
||||
|
||||
var status_label: Label
|
||||
var port_field: SpinBox
|
||||
var start_button: Button
|
||||
var stop_button: Button
|
||||
var log_display: TextEdit
|
||||
|
||||
func _ready():
|
||||
# Set up references to UI elements
|
||||
status_label = $VBoxContainer/StatusPanel/StatusLabel
|
||||
port_field = $VBoxContainer/ConfigPanel/PortField
|
||||
start_button = $VBoxContainer/ButtonPanel/StartButton
|
||||
stop_button = $VBoxContainer/ButtonPanel/StopButton
|
||||
log_display = $VBoxContainer/LogPanel/LogDisplay
|
||||
|
||||
# Initialize UI
|
||||
port_field.value = 6400 # Default port
|
||||
start_button.disabled = false
|
||||
stop_button.disabled = true
|
||||
|
||||
# Connect signals
|
||||
start_button.pressed.connect(_on_start_button_pressed)
|
||||
stop_button.pressed.connect(_on_stop_button_pressed)
|
||||
|
||||
# Set initial status
|
||||
update_status("Not running")
|
||||
add_log_message("Godot MCP Plugin initialized")
|
||||
|
||||
func update_status(status_text: String, is_error: bool = false):
|
||||
status_label.text = "Status: " + status_text
|
||||
if is_error:
|
||||
status_label.add_theme_color_override("font_color", Color(1, 0.3, 0.3))
|
||||
else:
|
||||
status_label.remove_theme_color_override("font_color")
|
||||
|
||||
func add_log_message(message: String):
|
||||
var timestamp = Time.get_datetime_string_from_system()
|
||||
log_display.text += "[" + timestamp + "] " + message + "\n"
|
||||
log_display.scroll_vertical = log_display.get_line_count()
|
||||
|
||||
func _on_start_button_pressed():
|
||||
# This function will be called from the plugin.gd script
|
||||
# when the server is actually started
|
||||
update_status("Running on port " + str(port_field.value))
|
||||
start_button.disabled = true
|
||||
stop_button.disabled = false
|
||||
add_log_message("MCP Server started on port " + str(port_field.value))
|
||||
|
||||
func _on_stop_button_pressed():
|
||||
# This function will be called from the plugin.gd script
|
||||
# when the server is actually stopped
|
||||
update_status("Stopped")
|
||||
start_button.disabled = false
|
||||
stop_button.disabled = true
|
||||
add_log_message("MCP Server stopped")
|
||||
|
||||
# Function to be called from plugin.gd when a client connects
|
||||
func on_client_connected():
|
||||
add_log_message("Client connected")
|
||||
update_status("Client connected")
|
||||
|
||||
# Function to be called from plugin.gd when a client disconnects
|
||||
func on_client_disconnected():
|
||||
add_log_message("Client disconnected")
|
||||
update_status("Running (no clients)")
|
||||
|
||||
# Function to be called from plugin.gd when a command is received
|
||||
func on_command_received(command_type, params):
|
||||
add_log_message("Command received: " + command_type)
|
||||
|
||||
# Function to be called from plugin.gd when a response is sent
|
||||
func on_response_sent(command_type, success):
|
||||
var status = "Success" if success else "Failed"
|
||||
add_log_message("Response sent for " + command_type + ": " + status)
|
||||
@@ -0,0 +1 @@
|
||||
uid://bqabyd7ce60u0
|
||||
@@ -0,0 +1,69 @@
|
||||
[gd_scene load_steps=2 format=3 uid="uid://dxvt86ck6b2a4"]
|
||||
|
||||
[ext_resource type="Script" path="res://addons/godot_mcp/ui/mcp_panel.gd" id="1_4g23r"]
|
||||
|
||||
[node name="MCPPanel" type="Control"]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
script = ExtResource("1_4g23r")
|
||||
|
||||
[node name="VBoxContainer" type="VBoxContainer" parent="."]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
|
||||
[node name="StatusPanel" type="PanelContainer" parent="VBoxContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="StatusLabel" type="Label" parent="VBoxContainer/StatusPanel"]
|
||||
layout_mode = 2
|
||||
text = "Status: Not running"
|
||||
|
||||
[node name="ConfigPanel" type="PanelContainer" parent="VBoxContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/ConfigPanel"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="PortLabel" type="Label" parent="VBoxContainer/ConfigPanel/HBoxContainer"]
|
||||
layout_mode = 2
|
||||
text = "Port:"
|
||||
|
||||
[node name="PortField" type="SpinBox" parent="VBoxContainer/ConfigPanel"]
|
||||
layout_mode = 2
|
||||
min_value = 1024.0
|
||||
max_value = 65535.0
|
||||
value = 6400.0
|
||||
alignment = 1
|
||||
|
||||
[node name="ButtonPanel" type="PanelContainer" parent="VBoxContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="HBoxContainer" type="HBoxContainer" parent="VBoxContainer/ButtonPanel"]
|
||||
layout_mode = 2
|
||||
alignment = 1
|
||||
|
||||
[node name="StartButton" type="Button" parent="VBoxContainer/ButtonPanel"]
|
||||
layout_mode = 2
|
||||
text = "Start Server"
|
||||
|
||||
[node name="StopButton" type="Button" parent="VBoxContainer/ButtonPanel"]
|
||||
layout_mode = 2
|
||||
disabled = true
|
||||
text = "Stop Server"
|
||||
|
||||
[node name="LogPanel" type="PanelContainer" parent="VBoxContainer"]
|
||||
layout_mode = 2
|
||||
size_flags_vertical = 3
|
||||
|
||||
[node name="LogDisplay" type="TextEdit" parent="VBoxContainer/LogPanel"]
|
||||
layout_mode = 2
|
||||
editable = false
|
||||
wrap_mode = 1
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="124" height="124" x="2" y="2" fill="#363d52" stroke="#212532" stroke-width="4" rx="14"/><g fill="#fff" transform="translate(12.322 12.322)scale(.101)"><path d="M105 673v33q407 354 814 0v-33z"/><path fill="#478cbf" d="m105 673 152 14q12 1 15 14l4 67 132 10 8-61q2-11 15-15h162q13 4 15 15l8 61 132-10 4-67q3-13 15-14l152-14V427q30-39 56-81-35-59-83-108-43 20-82 47-40-37-88-64 7-51 8-102-59-28-123-42-26 43-46 89-49-7-98 0-20-46-46-89-64 14-123 42 1 51 8 102-48 27-88 64-39-27-82-47-48 49-83 108 26 42 56 81zm0 33v39c0 276 813 276 814 0v-39l-134 12-5 69q-2 10-14 13l-162 11q-12 0-16-11l-10-65H446l-10 65q-4 11-16 11l-162-11q-12-3-14-13l-5-69z"/><path d="M483 600c0 34 58 34 58 0v-86c0-34-58-34-58 0z"/><circle cx="725" cy="526" r="90"/><circle cx="299" cy="526" r="90"/></g><g fill="#414042" transform="translate(12.322 12.322)scale(.101)"><circle cx="307" cy="532" r="60"/><circle cx="717" cy="532" r="60"/></g></svg>
|
||||
|
After Width: | Height: | Size: 995 B |
@@ -0,0 +1,43 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://drj7e8fs1pl5e"
|
||||
path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://icon.svg"
|
||||
dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
svg/scale=1.0
|
||||
editor/scale_with_editor_scale=false
|
||||
editor/convert_colors_with_editor_theme=false
|
||||
@@ -0,0 +1,27 @@
|
||||
; Engine configuration file.
|
||||
; It's best edited using the editor UI and not directly,
|
||||
; since the parameters that go here are not all obvious.
|
||||
;
|
||||
; Format:
|
||||
; [section] ; section goes between []
|
||||
; param=value ; assign values to parameters
|
||||
|
||||
config_version=5
|
||||
|
||||
[application]
|
||||
|
||||
config/name="Territory-Autobattler"
|
||||
config/features=PackedStringArray("4.6", "Forward Plus")
|
||||
config/icon="res://icon.svg"
|
||||
|
||||
[editor_plugins]
|
||||
|
||||
enabled=PackedStringArray("res://addons/godot_mcp/plugin.cfg")
|
||||
|
||||
[physics]
|
||||
|
||||
3d/physics_engine="Jolt Physics"
|
||||
|
||||
[rendering]
|
||||
|
||||
rendering_device/driver.windows="d3d12"
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Bcrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
|
||||
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@AuthApi_HostAddress = http://localhost:5279
|
||||
|
||||
GET {{AuthApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,113 @@
|
||||
using AuthApi.Models;
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace AuthApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly UserService _users;
|
||||
private readonly IConfiguration _cfg;
|
||||
private readonly BlacklistService _blacklist;
|
||||
|
||||
public AuthController(UserService users, IConfiguration cfg, BlacklistService blacklist)
|
||||
{
|
||||
_users = users; _cfg = cfg; _blacklist = blacklist;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest req)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
|
||||
return BadRequest("Username and password required");
|
||||
|
||||
if (await _users.GetByUsernameAsync(req.Username) != null)
|
||||
return BadRequest("User already exists");
|
||||
|
||||
var hash = BCrypt.Net.BCrypt.HashPassword(req.Password);
|
||||
var user = new User { Username = req.Username, PasswordHash = hash, Role = "USER", Email = req.Email };
|
||||
await _users.CreateAsync(user);
|
||||
return Ok("User created");
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
|
||||
return Unauthorized();
|
||||
|
||||
var (accessToken, jti, expUtc) = GenerateJwtToken(user);
|
||||
user.RefreshToken = Guid.NewGuid().ToString("N");
|
||||
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
|
||||
await _users.UpdateAsync(user);
|
||||
|
||||
return Ok(new { accessToken, refreshToken = user.RefreshToken, user.Username, user.Role, jti, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("refresh")]
|
||||
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
|
||||
{
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user == null || user.RefreshToken != req.RefreshToken || user.RefreshTokenExpiry < DateTime.UtcNow)
|
||||
return Unauthorized("Invalid or expired refresh token");
|
||||
|
||||
var (accessToken, _, expUtc) = GenerateJwtToken(user);
|
||||
return Ok(new { accessToken, exp = expUtc });
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
|
||||
if (string.IsNullOrWhiteSpace(token)) return BadRequest("Token missing");
|
||||
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
|
||||
await _blacklist.AddToBlacklistAsync(jwt.Id, jwt.ValidTo);
|
||||
return Ok("Logged out.");
|
||||
}
|
||||
|
||||
[HttpPost("role")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> ChangeUserRole([FromBody] ChangeRoleRequest req)
|
||||
{
|
||||
if (req.NewRole is not ("USER" or "SUPER")) return BadRequest("Role must be 'USER' or 'SUPER'");
|
||||
var user = await _users.GetByUsernameAsync(req.Username);
|
||||
if (user is null) return NotFound("User not found");
|
||||
user.Role = req.NewRole;
|
||||
await _users.UpdateAsync(user);
|
||||
return Ok($"{req.Username}'s role updated to {req.NewRole}");
|
||||
}
|
||||
|
||||
[HttpGet("users")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> GetAllUsers() => Ok(await _users.GetAllAsync());
|
||||
|
||||
private (string token, string jti, DateTime expUtc) GenerateJwtToken(User user)
|
||||
{
|
||||
var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"]!);
|
||||
var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var audience = _cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
|
||||
var jti = Guid.NewGuid().ToString("N");
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Username),
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id),
|
||||
new Claim(ClaimTypes.Role, user.Role),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, jti)
|
||||
};
|
||||
|
||||
var exp = DateTime.UtcNow.AddMinutes(15);
|
||||
var token = new JwtSecurityToken(issuer, audience, claims, expires: exp, signingCredentials: creds);
|
||||
return (new JwtSecurityTokenHandler().WriteToken(token), jti, exp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# AuthApi document shapes
|
||||
|
||||
This service expects JSON request bodies for its auth endpoints and stores user
|
||||
documents in MongoDB.
|
||||
|
||||
Inbound JSON documents
|
||||
- RegisterRequest (`POST /api/auth/register`)
|
||||
```json
|
||||
{
|
||||
"username": "string",
|
||||
"password": "string",
|
||||
"email": "string (optional)"
|
||||
}
|
||||
```
|
||||
- LoginRequest (`POST /api/auth/login`)
|
||||
```json
|
||||
{
|
||||
"username": "string",
|
||||
"password": "string"
|
||||
}
|
||||
```
|
||||
- RefreshRequest (`POST /api/auth/refresh`)
|
||||
```json
|
||||
{
|
||||
"username": "string",
|
||||
"refreshToken": "string"
|
||||
}
|
||||
```
|
||||
- ChangeRoleRequest (`POST /api/auth/role`)
|
||||
```json
|
||||
{
|
||||
"username": "string",
|
||||
"newRole": "USER | SUPER"
|
||||
}
|
||||
```
|
||||
|
||||
Stored documents (MongoDB)
|
||||
- User
|
||||
```json
|
||||
{
|
||||
"id": "string (ObjectId)",
|
||||
"username": "string",
|
||||
"passwordHash": "string",
|
||||
"role": "USER | SUPER",
|
||||
"email": "string (optional)",
|
||||
"refreshToken": "string (optional)",
|
||||
"refreshTokenExpiry": "string (optional, ISO-8601 datetime)"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copy project file first to take advantage of Docker layer caching
|
||||
COPY ["AuthApi.csproj", "./"]
|
||||
RUN dotnet restore "AuthApi.csproj"
|
||||
|
||||
# Copy the remaining source and publish
|
||||
COPY . .
|
||||
RUN dotnet publish "AuthApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
ENV ASPNETCORE_URLS=http://+:8080 \
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["dotnet", "AuthApi.dll"]
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class RegisterRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; public string? Email { get; set; } }
|
||||
public class LoginRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; }
|
||||
public class ChangeRoleRequest { public string Username { get; set; } = ""; public string NewRole { get; set; } = ""; }
|
||||
public class RefreshRequest { public string Username { get; set; } = ""; public string RefreshToken { get; set; } = ""; }
|
||||
@@ -0,0 +1,16 @@
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace AuthApi.Models;
|
||||
|
||||
public class User
|
||||
{
|
||||
[BsonId] [BsonRepresentation(BsonType.ObjectId)]
|
||||
public string Id { get; set; } = default!;
|
||||
public string Username { get; set; } = default!;
|
||||
public string PasswordHash { get; set; } = default!;
|
||||
public string Role { get; set; } = "USER";
|
||||
public string? Email { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
public DateTime? RefreshTokenExpiry { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using AuthApi.Services;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// DI
|
||||
builder.Services.AddSingleton<UserService>();
|
||||
builder.Services.AddSingleton<BlacklistService>();
|
||||
|
||||
// Swagger + JWT auth in Swagger
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Auth API", Version = "v1" });
|
||||
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
|
||||
});
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
|
||||
},
|
||||
Array.Empty<string>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// AuthN/JWT
|
||||
var cfg = builder.Configuration;
|
||||
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
|
||||
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
||||
var aud = cfg["Jwt:Audience"] ?? issuer;
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true, ValidIssuer = issuer,
|
||||
ValidateAudience = true, ValidAudience = aud,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30)
|
||||
};
|
||||
o.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async ctx =>
|
||||
{
|
||||
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
|
||||
if (!string.IsNullOrEmpty(jti))
|
||||
{
|
||||
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
|
||||
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapGet("/healthz", () => Results.Ok("ok"));
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(o =>
|
||||
{
|
||||
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Auth API v1");
|
||||
o.RoutePrefix = "swagger";
|
||||
});
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7295;http://localhost:5279",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# AuthApi
|
||||
|
||||
## Document shapes
|
||||
See `DOCUMENTS.md` for request payloads and stored document shapes.
|
||||
|
||||
## Endpoints
|
||||
- `POST /api/auth/register` Register a new user.
|
||||
- `POST /api/auth/login` Issue access and refresh tokens.
|
||||
- `POST /api/auth/refresh` Refresh an access token.
|
||||
- `POST /api/auth/logout` Revoke the current access token.
|
||||
- `POST /api/auth/role` Update a user's role (SUPER only).
|
||||
- `GET /api/auth/users` List users (SUPER only).
|
||||
@@ -0,0 +1,36 @@
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class BlacklistedToken
|
||||
{
|
||||
[BsonId] public string Jti { get; set; } = default!;
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
}
|
||||
|
||||
public class BlacklistService
|
||||
{
|
||||
private readonly IMongoCollection<BlacklistedToken> _col;
|
||||
|
||||
public BlacklistService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
|
||||
|
||||
// TTL index so revocations expire automatically
|
||||
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
|
||||
}
|
||||
|
||||
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
|
||||
_col.ReplaceOneAsync(x => x.Jti == jti,
|
||||
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
|
||||
new ReplaceOptions { IsUpsert = true });
|
||||
|
||||
public Task<bool> IsBlacklistedAsync(string jti) =>
|
||||
_col.Find(x => x.Jti == jti).AnyAsync();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using AuthApi.Models;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace AuthApi.Services;
|
||||
|
||||
public class UserService
|
||||
{
|
||||
private readonly IMongoCollection<User> _col;
|
||||
|
||||
public UserService(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_col = db.GetCollection<User>("Users");
|
||||
|
||||
var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
|
||||
_col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
|
||||
}
|
||||
|
||||
public Task<User?> GetByUsernameAsync(string username) =>
|
||||
_col.Find(u => u.Username == username).FirstOrDefaultAsync();
|
||||
|
||||
public Task CreateAsync(User user) => _col.InsertOneAsync(user);
|
||||
|
||||
public Task UpdateAsync(User user) =>
|
||||
_col.ReplaceOneAsync(u => u.Id == user.Id, user);
|
||||
|
||||
public Task<List<User>> GetAllAsync() =>
|
||||
_col.Find(FilterDefinition<User>.Empty).ToListAsync();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:8080" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "territory-autobattler" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "territory-autobattler", "Audience": "territory-autobattler-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: territory-autobattler-auth-config
|
||||
namespace: territory-autobattler
|
||||
data:
|
||||
MongoDB__ConnectionString: mongodb://192.168.86.50:27017
|
||||
MongoDB__DatabaseName: territory-autobattler
|
||||
Jwt__Issuer: territory-autobattler
|
||||
Jwt__Audience: territory-autobattler-auth-api
|
||||
@@ -0,0 +1,34 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: territory-autobattler-auth
|
||||
namespace: territory-autobattler
|
||||
labels:
|
||||
app: territory-autobattler-auth
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app: territory-autobattler-auth
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: territory-autobattler-auth
|
||||
spec:
|
||||
containers:
|
||||
- name: territory-autobattler-auth
|
||||
image: territory-autobattler-auth:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: territory-autobattler-auth-config
|
||||
- secretRef:
|
||||
name: territory-autobattler-auth-secrets
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: 8080
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
@@ -0,0 +1,4 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: territory-autobattler
|
||||
@@ -0,0 +1,8 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: territory-autobattler-auth-secrets
|
||||
namespace: territory-autobattler
|
||||
type: Opaque
|
||||
stringData:
|
||||
Jwt__Key: SuperUltraSecureJwtKeyWithAtLeast32Chars!!
|
||||
@@ -0,0 +1,16 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: territory-autobattler-auth
|
||||
namespace: territory-autobattler
|
||||
labels:
|
||||
app: territory-autobattler-auth
|
||||
spec:
|
||||
selector:
|
||||
app: territory-autobattler-auth
|
||||
type: NodePort
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: 8080
|
||||
nodePort: 30081
|
||||
Reference in New Issue
Block a user