Compare commits

..

No commits in common. "dev-local" and "main" have entirely different histories.

6 changed files with 683 additions and 35 deletions

414
.gitignore vendored Normal file
View File

@ -0,0 +1,414 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml

View File

@ -9,6 +9,8 @@ using SPTarkov.Server.Core.Utils;
namespace PersonalAuthMod; namespace PersonalAuthMod;
[Injectable(TypePriority = OnLoadOrder.PostSptModLoader + 100)] [Injectable(TypePriority = OnLoadOrder.PostSptModLoader + 100)]
public class AuthRouter : StaticRouter public class AuthRouter : StaticRouter
{ {
@ -19,14 +21,21 @@ public class AuthRouter : StaticRouter
DatabaseManager dbManager DatabaseManager dbManager
) : base(jsonUtil, ) : base(jsonUtil,
[ [
// Get Profile (Filter / Validate) // Get Profile (Filter / Validate)
new RouteAction<LoginRequestData>( new RouteAction<LoginRequestData>(
"/launcher/profile/get", "/launcher/profile/get",
async (url, info, sessionID, _) => async (url, info, sessionID, _) =>
{ {
// Rely on native SPT memory session validation via launcherCallbacks. if (!dbManager.ValidateSession(sessionID))
// We enforce authentication separately at the /login endpoint. return "FAILED";
var sessionUser = dbManager.GetUsernameBySession(sessionID);
// info.Username is typically passed by launcher. Verify it matches.
if (!string.IsNullOrEmpty(info.Username) && sessionUser != info.Username)
{
return "FAILED";
}
return await launcherCallbacks.Get(url, info, sessionID); return await launcherCallbacks.Get(url, info, sessionID);
} }
), ),
@ -35,6 +44,10 @@ public class AuthRouter : StaticRouter
"/launcher/profile/remove", "/launcher/profile/remove",
async (url, info, sessionID, _) => async (url, info, sessionID, _) =>
{ {
if (!dbManager.ValidateSession(sessionID)) return "FAILED";
// Also verify the user owns the profile being removed.
// Assuming sessionID is the "access token", calls to Remove need a valid session.
return await launcherCallbacks.RemoveProfile(url, info, sessionID); return await launcherCallbacks.RemoveProfile(url, info, sessionID);
} }
) )

View File

@ -76,7 +76,7 @@ public class DatabaseManager
var salt = GenerateSalt(); var salt = GenerateSalt();
var hash = HashPassword(password, salt); var hash = HashPassword(password, salt);
// Insert User and get ID // Insert User
using (var cmd = new NpgsqlCommand("INSERT INTO users (username, password_hash, salt) VALUES (@u, @p, @s)", conn)) using (var cmd = new NpgsqlCommand("INSERT INTO users (username, password_hash, salt) VALUES (@u, @p, @s)", conn))
{ {
cmd.Parameters.AddWithValue("u", username); cmd.Parameters.AddWithValue("u", username);
@ -84,6 +84,7 @@ public class DatabaseManager
cmd.Parameters.AddWithValue("s", salt); cmd.Parameters.AddWithValue("s", salt);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -93,43 +94,107 @@ public class DatabaseManager
} }
} }
public bool ValidateCredentials(string username, string password) public string? LoginUser(string username, string password)
{ {
try try
{ {
using var conn = new NpgsqlConnection(_connectionString); using var conn = new NpgsqlConnection(_connectionString);
conn.Open(); conn.Open();
int userId;
string storedHash, storedSalt; string storedHash, storedSalt;
using (var cmd = new NpgsqlCommand("SELECT password_hash, salt FROM users WHERE username = @u", conn))
using (var cmd = new NpgsqlCommand("SELECT id, password_hash, salt FROM users WHERE username = @u", conn))
{ {
cmd.Parameters.AddWithValue("u", username); cmd.Parameters.AddWithValue("u", username);
using var reader = cmd.ExecuteReader(); using var reader = cmd.ExecuteReader();
if (!reader.Read()) if (!reader.Read()) return null; // User not found
{
Console.WriteLine($"[PersonalAuthMod] ValidateCredentials Failed: User '{username}' not found in DB."); userId = reader.GetInt32(0);
return false; storedHash = reader.GetString(1);
} storedSalt = reader.GetString(2);
storedHash = reader.GetString(0);
storedSalt = reader.GetString(1);
} }
var hash = HashPassword(password, storedSalt); var hash = HashPassword(password, storedSalt);
if (hash != storedHash) if (hash != storedHash) return null; // Wrong password
// Generate Session (Must be 24-character hex for MongoId compatibility)
var sessionBytes = new byte[12];
using (var rng = RandomNumberGenerator.Create())
{ {
Console.WriteLine($"[PersonalAuthMod] ValidateCredentials Failed: Password mismatch for user '{username}'."); rng.GetBytes(sessionBytes);
return false;
} }
return true; var sessionId = Convert.ToHexString(sessionBytes).ToLower();
// Invalidate old sessions for this user? Requirement: "block existing login sessions".
using (var delCmd = new NpgsqlCommand("DELETE FROM sessions WHERE user_id = @uid", conn))
{
delCmd.Parameters.AddWithValue("uid", userId);
delCmd.ExecuteNonQuery();
}
using (var insertCmd = new NpgsqlCommand("INSERT INTO sessions (session_id, user_id) VALUES (@sid, @uid)", conn))
{
insertCmd.Parameters.AddWithValue("sid", sessionId);
insertCmd.Parameters.AddWithValue("uid", userId);
insertCmd.ExecuteNonQuery();
}
return sessionId;
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"[PersonalAuthMod] ValidateCredentials Failed: {ex.Message}"); Console.WriteLine($"[PersonalAuthMod] LoginUser Failed: {ex.Message}");
return null;
}
}
public bool ValidateSession(string sessionId)
{
if (string.IsNullOrEmpty(sessionId)) return false;
try
{
using var conn = new NpgsqlConnection(_connectionString);
conn.Open();
using (var cmd = new NpgsqlCommand("SELECT COUNT(*) FROM sessions WHERE session_id = @sid", conn))
{
cmd.Parameters.AddWithValue("sid", sessionId);
var count = (long)cmd.ExecuteScalar();
return count > 0;
}
}
catch (Exception ex)
{
Console.WriteLine($"[PersonalAuthMod] ValidateSession Failed: {ex.Message}");
return false; return false;
} }
} }
public string? GetUsernameBySession(string sessionId)
{
try
{
using var conn = new NpgsqlConnection(_connectionString);
conn.Open();
using (var cmd = new NpgsqlCommand(@"
SELECT u.username
FROM sessions s
JOIN users u ON s.user_id = u.id
WHERE s.session_id = @sid", conn))
{
cmd.Parameters.AddWithValue("sid", sessionId);
return cmd.ExecuteScalar() as string;
}
}
catch (Exception ex)
{
Console.WriteLine($"[PersonalAuthMod] GetUsernameBySession Failed: {ex.Message}");
return null;
}
}
private string GenerateSalt() private string GenerateSalt()
{ {

View File

@ -34,7 +34,7 @@ public static class AuthContext
} }
/// <summary> /// <summary>
/// Patch HttpRouter.HandleRoute to capture session ID globally before deserialization happens. /// Patch HttpRouter.HandleRoute to capture session ID and extract password globally.
/// </summary> /// </summary>
public class HttpRouterHandleRoutePatch : AbstractPatch public class HttpRouterHandleRoutePatch : AbstractPatch
{ {
@ -44,16 +44,84 @@ public class HttpRouterHandleRoutePatch : AbstractPatch
} }
[PatchPrefix] [PatchPrefix]
public static void Prefix(MongoId sessionID) public static void Prefix(MongoId sessionID, ref string? body)
{ {
// Capture the session ID for other patches (like profile filtering) // Capture the session ID for other patches (like profile filtering)
AuthContext.CurrentSessionID = sessionID.ToString(); AuthContext.CurrentSessionID = sessionID.ToString();
if (string.IsNullOrEmpty(body))
{
return;
}
if (!body.Contains("\"password\""))
{
return;
}
try
{
var node = JsonNode.Parse(body);
if (node is JsonObject obj && obj.TryGetPropertyValue("password", out var passwordNode))
{
AuthContext.CurrentPassword = passwordNode?.GetValue<string>();
obj.Remove("password");
body = obj.ToJsonString();
}
}
catch
{
}
} }
} }
/// <summary>
/// Patch ProfileController.GetMiniProfiles to filter the list based on the authenticated user.
/// </summary>
public class ProfileControllerGetMiniProfilesPatch : AbstractPatch
{
protected override MethodBase GetTargetMethod()
{
return typeof(ProfileController).GetMethod(nameof(ProfileController.GetMiniProfiles))!;
}
[PatchPostfix]
public static void Postfix(ref List<MiniProfile> __result)
{
var sessionID = AuthContext.CurrentSessionID;
if (string.IsNullOrEmpty(sessionID) || __result == null)
{
return;
}
var dbManager = PersonalAuthMod.Instance?.DbManager;
if (dbManager == null || !dbManager.ValidateSession(sessionID))
{
// If session is invalid, return empty list (isolation)
__result = new List<MiniProfile>();
return;
}
var username = dbManager.GetUsernameBySession(sessionID);
if (string.IsNullOrEmpty(username))
{
__result = new List<MiniProfile>();
return;
}
// Filter the list to only include the user's own profile
int before = __result.Count;
__result = __result.Where(p => p.Username == username).ToList();
if (before != __result.Count)
{
Console.WriteLine($"[PersonalAuthMod] Isolated profiles for {username}: {before} -> {__result.Count}");
}
}
}
/// <summary> /// <summary>
/// Patch LauncherCallbacks.Login to enforce database authentication. /// Patch LauncherCallbacks.Login to enforce database authentication.
/// Returns true to let the original method execute and fetch the MongoId from memory.
/// Returns false if DB verification fails, aborting the original method.
/// </summary> /// </summary>
public class LauncherCallbacksLoginPatch : AbstractPatch public class LauncherCallbacksLoginPatch : AbstractPatch
{ {
@ -65,28 +133,31 @@ public class LauncherCallbacksLoginPatch : AbstractPatch
[PatchPrefix] [PatchPrefix]
public static bool Prefix(string url, LoginRequestData info, MongoId sessionID, ref ValueTask<string> __result) public static bool Prefix(string url, LoginRequestData info, MongoId sessionID, ref ValueTask<string> __result)
{ {
if (string.IsNullOrWhiteSpace(info.Username) || string.IsNullOrWhiteSpace(info.Password)) var password = AuthContext.CurrentPassword;
Console.WriteLine($"[PersonalAuthMod] Login Patch - User: {info.Username}, Password provided? {!string.IsNullOrEmpty(password)}");
if (string.IsNullOrWhiteSpace(info.Username) || string.IsNullOrWhiteSpace(password))
{ {
__result = new ValueTask<string>("FAILED"); __result = new ValueTask<string>("FAILED");
return false; return false; // Skip original method
} }
if (!PersonalAuthMod.Instance!.DbManager.ValidateCredentials(info.Username, info.Password)) var sessionId = PersonalAuthMod.Instance?.DbManager.LoginUser(info.Username, password);
if (sessionId == null)
{ {
Console.WriteLine($"[PersonalAuthMod] Login FAILED for user: {info.Username} (Invalid credentials via DB)"); Console.WriteLine($"[PersonalAuthMod] Login FAILED for user: {info.Username}");
__result = new ValueTask<string>("FAILED"); __result = new ValueTask<string>("FAILED");
return false; return false; // Skip original method
} }
Console.WriteLine($"[PersonalAuthMod] Login SUCCESS for user: {info.Username}, Validated by DB."); Console.WriteLine($"[PersonalAuthMod] Login SUCCESS for user: {info.Username}, Session: {sessionId}");
return true; __result = new ValueTask<string>(sessionId);
return false; // Skip original method
} }
} }
/// <summary> /// <summary>
/// Patch LauncherCallbacks.Register to enforce database registration. /// Patch LauncherCallbacks.Register to enforce database registration.
/// Returns true to let the original method execute and create the account in SaveServer.
/// Returns false if DB registration fails (e.g. user exists).
/// </summary> /// </summary>
public class LauncherCallbacksRegisterPatch : AbstractPatch public class LauncherCallbacksRegisterPatch : AbstractPatch
{ {
@ -98,20 +169,24 @@ public class LauncherCallbacksRegisterPatch : AbstractPatch
[PatchPrefix] [PatchPrefix]
public static bool Prefix(string url, RegisterData info, MongoId sessionID, ref ValueTask<string> __result) public static bool Prefix(string url, RegisterData info, MongoId sessionID, ref ValueTask<string> __result)
{ {
if (string.IsNullOrWhiteSpace(info.Username) || string.IsNullOrWhiteSpace(info.Password)) var password = AuthContext.CurrentPassword;
Console.WriteLine($"[PersonalAuthMod] Register Patch - User: {info.Username}, Password provided? {!string.IsNullOrEmpty(password)}");
if (string.IsNullOrWhiteSpace(info.Username) || string.IsNullOrWhiteSpace(password))
{ {
__result = new ValueTask<string>("FAILED"); __result = new ValueTask<string>("FAILED");
return false; return false; // Skip original method
} }
if (!PersonalAuthMod.Instance!.DbManager.RegisterUser(info.Username, info.Password)) if (PersonalAuthMod.Instance?.DbManager.RegisterUser(info.Username, password) == false)
{ {
Console.WriteLine($"[PersonalAuthMod] Register FAILED for user: {info.Username} (Already exists or DB error)"); Console.WriteLine($"[PersonalAuthMod] Register FAILED for user: {info.Username} (Already exists or DB error)");
__result = new ValueTask<string>("FAILED"); __result = new ValueTask<string>("FAILED");
return false; return false; // Skip original method
} }
Console.WriteLine($"[PersonalAuthMod] Register SUCCESS for user: {info.Username}"); Console.WriteLine($"[PersonalAuthMod] Register SUCCESS for user: {info.Username}");
// Allow original method to run (it will create the local profile)
return true; return true;
} }
} }

View File

@ -20,6 +20,7 @@ public class PersonalAuthMod(DatabaseManager dbManager) : IOnLoad
new HttpRouterHandleRoutePatch().Enable(); new HttpRouterHandleRoutePatch().Enable();
new LauncherCallbacksLoginPatch().Enable(); new LauncherCallbacksLoginPatch().Enable();
new LauncherCallbacksRegisterPatch().Enable(); new LauncherCallbacksRegisterPatch().Enable();
new ProfileControllerGetMiniProfilesPatch().Enable();
return Task.CompletedTask; return Task.CompletedTask;
} }

80
test_mod.sh Executable file
View File

@ -0,0 +1,80 @@
#!/bin/bash
# SPT C# Server Mod Test Script (Robust Version)
SERVER_URL="https://127.0.0.1:6969"
USERNAME="testuser_$(date +%s)"
PASSWORD="testpassword"
WRONG_PASSWORD="wrongpassword123"
# Helper function for curl
call_api() {
local endpoint=$1
local data=$2
local cookie=$3
local headers=(-H "Content-Type: application/json" -H "requestcompressed: 0" -H "responsecompressed: 0")
if [ ! -z "$cookie" ]; then
headers+=(-H "Cookie: PHPSESSID=$cookie")
fi
curl -k -s -i -X POST "$SERVER_URL$endpoint" "${headers[@]}" -d "$data"
}
get_body() {
echo "$1" | awk '/^\r?$/ {p=1; next} p {print}' | xargs
}
echo "=== [테스트 시작: $USERNAME] ==="
echo "1. 회원가입 테스트 (신규 가입)"
REG_RESP=$(call_api "/launcher/profile/register" "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\",\"edition\":\"Edge Of Darkness\"}")
REG_BODY=$(get_body "$REG_RESP")
echo "결과: $REG_BODY"
if [[ "$REG_BODY" == "FAILED" ]]; then
echo "오류: 신규 가입이 실패했습니다."
exit 1
fi
echo -e "\n2. 중복 회원가입 테스트 (이미 존재하는 아이디)"
DUP_REG_RESP=$(call_api "/launcher/profile/register" "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\",\"edition\":\"Edge Of Darkness\"}")
DUP_REG_BODY=$(get_body "$DUP_REG_RESP")
echo "결과: $DUP_REG_BODY (예상: FAILED)"
if [[ "$DUP_REG_BODY" != "FAILED" ]]; then
echo "오류: 중복 가입이 허용되었습니다!"
exit 1
fi
echo -e "\n3. 로그인 테스트 (틀린 비밀번호)"
WRONG_LOGIN_RESP=$(call_api "/launcher/profile/login" "{\"username\":\"$USERNAME\",\"password\":\"$WRONG_PASSWORD\"}")
WRONG_LOGIN_BODY=$(get_body "$WRONG_LOGIN_RESP")
echo "결과: $WRONG_LOGIN_BODY (예상: FAILED)"
if [[ "$WRONG_LOGIN_BODY" != "FAILED" ]]; then
echo "오류: 틀린 비밀번호로 로그인이 성공했습니다!"
exit 1
fi
echo -e "\n4. 로그인 테스트 (정상 로그인)"
LOGIN_RESP=$(call_api "/launcher/profile/login" "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}")
SESSION_ID=$(get_body "$LOGIN_RESP")
echo "결과: $SESSION_ID (세션 ID 전송됨)"
if [[ "$SESSION_ID" == "FAILED" || -z "$SESSION_ID" ]]; then
echo "오류: 정상 로그인이 실패했습니다."
exit 1
fi
echo -e "\n5. 프로필 목록 조회 테스트"
PROF_RESP=$(call_api "/launcher/profiles" "{}" "$SESSION_ID")
PROF_BODY=$(get_body "$PROF_RESP")
# 앞 15글자만 출력
TRUNCATED_BODY="${PROF_BODY:0:15}..."
echo "결과 (앞 15자): $TRUNCATED_BODY"
if [[ "$PROF_BODY" == "["* ]]; then
echo "성공: 정상적인 프로필 리스트(JSON Array)가 수신되었습니다."
else
echo "오류: 프로필 조회 응답이 올바르지 않습니다."
echo "전체 응답: $PROF_BODY"
exit 1
fi
echo -e "\n=== [모든 테스트 통과!] ==="