/* * This file is a part of the SteamWar software. * * Copyright (C) 2025 SteamWar.de-Serverteam * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ package de.steamwar.plugins import de.steamwar.config import de.steamwar.sql.SteamwarUser import io.ktor.http.* import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.plugins.contentnegotiation.* import io.ktor.server.plugins.cors.routing.* import io.ktor.server.plugins.ratelimit.* import io.ktor.server.response.* import io.ktor.server.sessions.* import kotlinx.serialization.json.Json import java.io.File import kotlin.time.Duration.Companion.seconds fun Application.configurePlugins() { install(CORS) { allowMethod(HttpMethod.Options) allowMethod(HttpMethod.Get) allowMethod(HttpMethod.Post) allowMethod(HttpMethod.Put) allowMethod(HttpMethod.Delete) allowHeader(HttpHeaders.Authorization) allowHeader(HttpHeaders.AccessControlAllowOrigin) allowHeader(HttpHeaders.ContentType) anyHost() allowXHttpMethodOverride() allowCredentials = true } install(RateLimit) { global { rateLimiter(limit = 60, refillPeriod = 60.seconds) requestKey { it.request.headers["X-Forwarded-For"] ?: it.request.local.remoteHost } requestWeight { applicationCall, _ -> if (!applicationCall.request.headers.contains("X-Forwarded-For")) { 0 } else { 1 } } } } authentication { // Disabled, Maybe for API later //bearer("sw-auth") { // realm = "SteamWar API" // authenticate { call -> // val token = Token.getTokenByCode(call.token) // if (token == null) { // null // } else { // if (!token.isValid) { // token.delete() // return@authenticate null // } // if (token.type == TokenType.REFRESH_TOKEN) { // token.delete() // } // SWAuthPrincipal(token.owner) // } // } //} session("sw-session") { validate { session -> val steamwarUser = session.userId.let { SteamwarUser.byId(it) } return@validate steamwarUser?.let { SWAuthPrincipal(it) } } challenge { call.respond(HttpStatusCode.Unauthorized) } } } install(Sessions) { cookie("sw-session", directorySessionStorage(File("sessions"))) { cookie.path = "/" cookie.maxAgeInSeconds = 60 * 60 * 24 * 7 cookie.httpOnly = true cookie.secure = true transform( SessionTransportTransformerEncrypt( config.sessionEncryptSecret.toByteArray(), config.sessionSignSecret.toByteArray() ) ) } } install(ContentNegotiation) { json(Json) } install(ErrorLogger) }