Code cleanup

This commit is contained in:
Laura Hausmann 2022-05-03 00:20:02 +02:00
parent ec16ec5def
commit 6ab3774228
Signed by: zotan
GPG Key ID: D044E84C5BE01605
28 changed files with 699 additions and 721 deletions

View File

@ -1,21 +1,21 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Mvc;
namespace trainav.web.Controllers {
[ApiController, Route("api/[controller]")]
public class TestController : ControllerBase {
[HttpGet]
public ApiResponse Get() => new ApiResponse("test", 4);
namespace trainav.web.Controllers;
[ApiController, Route("api/[controller]")]
public class TestController : ControllerBase {
[HttpGet]
public ApiResponse Get() => new("test", 4);
}
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")]
public class ApiResponse {
public ApiResponse(string string1, int int1) {
String1 = string1;
Int1 = int1;
}
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")]
public class ApiResponse {
public ApiResponse(string string1, int int1) {
String1 = string1;
Int1 = int1;
}
public string String1 { get; }
public int Int1 { get; }
}
public string String1 { get; }
public int Int1 { get; }
}

View File

@ -6,100 +6,100 @@ using LinqToDB.Data;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web {
public static class Migrations {
private const int DbVer = 1;
namespace trainav.web;
private static readonly List<Migration> _migrations = new() {
new Migration(1,
"CREATE TEMPORARY TABLE Tickets_backup(\"TicketID\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \"UserID\" INTEGER NOT NULL, \"OrderID\" TEXT NOT NULL UNIQUE, \"TicketInfo\" TEXT NOT NULL, \"TicketQR\" BLOB NOT NULL, \"TicketPkPass\" BLOB NOT NULL, \"TicketSecCode\" BLOB NOT NULL, \"Traveller\" TEXT)"),
new Migration(1, "INSERT INTO Tickets_backup SELECT TicketID, UserID, OrderID, TicketInfo, TicketQR, TicketPkPass, TicketSecCode, Traveller FROM Tickets"),
new Migration(1, "DROP Table Tickets"),
new Migration(1,
"CREATE TABLE Tickets(\"TicketID\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \"UserID\" INTEGER NOT NULL, \"OrderID\" TEXT NOT NULL UNIQUE, \"TicketInfo\" TEXT NOT NULL, \"TicketQR\" BLOB NOT NULL, \"TicketPkPass\" BLOB, \"TicketSecCode\" BLOB NOT NULL, \"Traveller\" TEXT)"),
new Migration(1, "INSERT INTO Tickets SELECT TicketID, UserID, OrderID, TicketInfo, TicketQR, TicketPkPass, TicketSecCode, Traveller FROM Tickets_backup"),
new Migration(1, "DROP TABLE Tickets_backup")
};
public static class Migrations {
private const int DbVer = 1;
public static void RunMigrations() {
using var db = new Database.DbConn();
var ccolor = Console.ForegroundColor;
private static readonly List<Migration> _migrations = new() {
new Migration(1,
"CREATE TEMPORARY TABLE Tickets_backup(\"TicketID\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \"UserID\" INTEGER NOT NULL, \"OrderID\" TEXT NOT NULL UNIQUE, \"TicketInfo\" TEXT NOT NULL, \"TicketQR\" BLOB NOT NULL, \"TicketPkPass\" BLOB NOT NULL, \"TicketSecCode\" BLOB NOT NULL, \"Traveller\" TEXT)"),
new Migration(1, "INSERT INTO Tickets_backup SELECT TicketID, UserID, OrderID, TicketInfo, TicketQR, TicketPkPass, TicketSecCode, Traveller FROM Tickets"),
new Migration(1, "DROP Table Tickets"),
new Migration(1,
"CREATE TABLE Tickets(\"TicketID\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \"UserID\" INTEGER NOT NULL, \"OrderID\" TEXT NOT NULL UNIQUE, \"TicketInfo\" TEXT NOT NULL, \"TicketQR\" BLOB NOT NULL, \"TicketPkPass\" BLOB, \"TicketSecCode\" BLOB NOT NULL, \"Traveller\" TEXT)"),
new Migration(1, "INSERT INTO Tickets SELECT TicketID, UserID, OrderID, TicketInfo, TicketQR, TicketPkPass, TicketSecCode, Traveller FROM Tickets_backup"),
new Migration(1, "DROP TABLE Tickets_backup")
};
if (!db.DataProvider.GetSchemaProvider().GetSchema(db).Tables.Any()) {
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("Running migration: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Initialize Database");
db.CreateTable<DbInfo>();
db.CreateTable<Card>();
db.CreateTable<Leg>();
db.CreateTable<Ticket>();
db.CreateTable<TicketLeg>();
db.CreateTable<Trip>();
db.CreateTable<User>();
db.InsertWithIdentity(new DbInfo { DbVer = DbVer });
}
else if (db.DataProvider.GetSchemaProvider().GetSchema(db).Tables.All(t => t.TableName != "DbInfo")) {
db.CreateTable<DbInfo>();
db.InsertWithIdentity(new DbInfo { DbVer = 0 });
}
public static void RunMigrations() {
using var db = new Database.DbConn();
var ccolor = Console.ForegroundColor;
if (!db.DataProvider.GetSchemaProvider().GetSchema(db).Tables.Any()) {
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("Running migration: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Database version: {db.DbInfo.ToList().First().DbVer}");
Console.WriteLine("Initialize Database");
var migrationsToRun = _migrations.FindAll(p => p.IntroducedWithDbVer > db.DbInfo.First().DbVer);
if (migrationsToRun.Count == 0) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("No migrations to run.");
}
else {
new Migration(0, "BEGIN TRANSACTION").Run(db);
try {
migrationsToRun.ForEach(p => p.Run(db));
}
catch {
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"Migrating to database version {DbVer} failed.");
new Migration(0, "ROLLBACK TRANSACTION").Run(db);
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Rolled back migrations.");
Environment.Exit(1);
}
db.CreateTable<DbInfo>();
db.CreateTable<Card>();
db.CreateTable<Leg>();
db.CreateTable<Ticket>();
db.CreateTable<TicketLeg>();
db.CreateTable<Trip>();
db.CreateTable<User>();
new Migration(0, "COMMIT TRANSACTION").Run(db);
var newdb = new Database.DbConn();
var dbinfo = newdb.DbInfo.First();
dbinfo.DbVer = DbVer;
newdb.Update(dbinfo);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine($"Database version is now: {DbVer}");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Finished running migrations.");
}
Console.ForegroundColor = ccolor;
db.InsertWithIdentity(new DbInfo { DbVer = DbVer });
}
else if (db.DataProvider.GetSchemaProvider().GetSchema(db).Tables.All(t => t.TableName != "DbInfo")) {
db.CreateTable<DbInfo>();
db.InsertWithIdentity(new DbInfo { DbVer = 0 });
}
private class Migration {
private readonly string _sql;
public readonly int IntroducedWithDbVer;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Database version: {db.DbInfo.ToList().First().DbVer}");
public Migration(int introducedWithDbVer, string sql) {
IntroducedWithDbVer = introducedWithDbVer;
_sql = sql;
var migrationsToRun = _migrations.FindAll(p => p.IntroducedWithDbVer > db.DbInfo.First().DbVer);
if (migrationsToRun.Count == 0) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("No migrations to run.");
}
else {
new Migration(0, "BEGIN TRANSACTION").Run(db);
try {
migrationsToRun.ForEach(p => p.Run(db));
}
catch {
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"Migrating to database version {DbVer} failed.");
new Migration(0, "ROLLBACK TRANSACTION").Run(db);
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Rolled back migrations.");
Environment.Exit(1);
}
public void Run(DataConnection db) {
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("Running migration: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(_sql);
db.Execute(_sql);
}
new Migration(0, "COMMIT TRANSACTION").Run(db);
var newdb = new Database.DbConn();
var dbinfo = newdb.DbInfo.First();
dbinfo.DbVer = DbVer;
newdb.Update(dbinfo);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine($"Database version is now: {DbVer}");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Finished running migrations.");
}
Console.ForegroundColor = ccolor;
}
private class Migration {
private readonly string _sql;
public readonly int IntroducedWithDbVer;
public Migration(int introducedWithDbVer, string sql) {
IntroducedWithDbVer = introducedWithDbVer;
_sql = sql;
}
public void Run(DataConnection db) {
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("Running migration: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(_sql);
db.Execute(_sql);
}
}
}
}

View File

@ -11,58 +11,55 @@ using trainav.web.database.Tables;
using trainav.web.JSON.CardResponse;
using trainav.web.JSON.ListOrdersResponse;
namespace trainav.web.Pages {
public class CardModel : PageModel {
public void OnPost() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
namespace trainav.web.Pages;
using var db = new Database.DbConn();
var request = new XDocument(new XElement("rqorderheadlist",
new XElement("rqheader", new XAttribute("ts", "2020-02-19T15:59:00"), new XAttribute("l", "de"),
new XAttribute("v", "19120000"), new XAttribute("d", "iPad7,5"),
new XAttribute("os", "iOS_13.3.1"), new XAttribute("app", "NAVIGATOR")),
new XElement("authlogin", new XAttribute("user", Request.Form["user"]),
new XAttribute("pw", Request.Form["pass"]),
new XElement("sso", new XAttribute("genToken", "FALSE"))),
new XElement("criteria", new XAttribute("validonly", "0")))).ToString();
var response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
var xmlobj = new XmlDocument();
public class CardModel : PageModel {
public void OnPost() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
using var db = new Database.DbConn();
var request = new XDocument(new XElement("rqorderheadlist",
new XElement("rqheader", new XAttribute("ts", "2020-02-19T15:59:00"), new XAttribute("l", "de"), new XAttribute("v", "19120000"),
new XAttribute("d", "iPad7,5"), new XAttribute("os", "iOS_13.3.1"), new XAttribute("app", "NAVIGATOR")),
new XElement("authlogin", new XAttribute("user", Request.Form["user"]), new XAttribute("pw", Request.Form["pass"]),
new XElement("sso", new XAttribute("genToken", "FALSE"))),
new XElement("criteria", new XAttribute("validonly", "0")))).ToString();
var response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
var xmlobj = new XmlDocument();
xmlobj.LoadXml(response);
var json = JsonConvert.SerializeXmlNode(xmlobj);
var parsed = ListOrdersResponse.FromJson(json);
foreach (var order in parsed.Rporderheadlist.Orderheadlist.Orderhead.Where(order => order.On.StartsWith("EBC_"))) {
request = new XDocument(new XElement("rqorderdetails", new XAttribute("version", "1.0"),
new XElement("rqheader", new XAttribute("ts", "2019-10-31T23:20:48"), new XAttribute("l", "de"), new XAttribute("v", "19100000"),
new XAttribute("d", "iPad7,5"), new XAttribute("os", "iOS_13.1.3"), new XAttribute("app", "NAVIGATOR")),
new XElement("rqorder", new XAttribute("on", order.On)), new XElement("authname", new XAttribute("tln", Request.Form["name"]))))
.ToString();
response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
xmlobj = new XmlDocument();
xmlobj.LoadXml(response);
var json = JsonConvert.SerializeXmlNode(xmlobj);
var parsed = ListOrdersResponse.FromJson(json);
json = JsonConvert.SerializeXmlNode(xmlobj);
var parsedCard = CardResponse.FromJson(json);
foreach (var order in parsed.Rporderheadlist.Orderheadlist.Orderhead.Where(order => order.On.StartsWith("EBC_"))) {
request = new XDocument(new XElement("rqorderdetails", new XAttribute("version", "1.0"),
new XElement("rqheader", new XAttribute("ts", "2019-10-31T23:20:48"), new XAttribute("l", "de"),
new XAttribute("v", "19100000"), new XAttribute("d", "iPad7,5"),
new XAttribute("os", "iOS_13.1.3"), new XAttribute("app", "NAVIGATOR")),
new XElement("rqorder", new XAttribute("on", order.On)),
new XElement("authname", new XAttribute("tln", Request.Form["name"])))).ToString();
response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
xmlobj = new XmlDocument();
xmlobj.LoadXml(response);
json = JsonConvert.SerializeXmlNode(xmlobj);
var parsedCard = CardResponse.FromJson(json);
db.InsertWithInt32Identity(new Card {
OrderId = order.On,
UserId = int.Parse(HttpContext.Session.GetString("uid")),
Class = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "klasse").Text),
Value = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "rbs").Text),
CardNumber = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "bcnummer").Text,
CardInfo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Txt,
CardQr = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text,
CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text,
CardImage = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection,
Traveller = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "inhaber").Text,
ValidFrom = parsedCard.Rporderdetails.Order.Vfrom,
ValidTo = parsedCard.Rporderdetails.Order.Vto,
QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text,
QrValidTo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text
});
}
db.InsertWithInt32Identity(new Card {
OrderId = order.On,
UserId = int.Parse(HttpContext.Session.GetString("uid")),
Class = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "klasse").Text),
Value = int.Parse(parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "rbs").Text),
CardNumber = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "bcnummer").Text,
CardInfo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Txt,
CardQr = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text,
CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text,
CardImage = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection,
Traveller = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "inhaber").Text,
ValidFrom = parsedCard.Rporderdetails.Order.Vfrom,
ValidTo = parsedCard.Rporderdetails.Order.Vto,
QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text,
QrValidTo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text
});
}
}
}

View File

@ -11,45 +11,44 @@ using trainav.web.database;
using trainav.web.database.Tables;
using trainav.web.JSON.CardResponse;
namespace trainav.web.Pages {
public class CardsModel : PageModel {
public List<Card> Cards;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
public class CardsModel : PageModel {
public List<Card> Cards;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
using var db = new Database.DbConn();
if (Request.Query.ContainsKey("refresh")) {
var card = db.Cards.First(p => p.CardId == int.Parse(Request.Query["refresh"]));
if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
using var db = new Database.DbConn();
var request = new XDocument(new XElement("rqorderdetails", new XAttribute("version", "1.0"),
new XElement("rqheader", new XAttribute("ts", "2019-10-31T23:20:48"), new XAttribute("l", "de"),
new XAttribute("v", "19100000"), new XAttribute("d", "iPad7,5"), new XAttribute("os", "iOS_13.1.3"),
new XAttribute("app", "NAVIGATOR")), new XElement("rqorder", new XAttribute("on", card.OrderId)),
new XElement("authname", new XAttribute("tln", card.Traveller.Split(" ").Last())))).ToString();
if (Request.Query.ContainsKey("refresh")) {
var card = db.Cards.First(p => p.CardId == int.Parse(Request.Query["refresh"]));
if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
var response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
var xmlobj = new XmlDocument();
xmlobj.LoadXml(response);
var json = JsonConvert.SerializeXmlNode(xmlobj);
var parsedCard = CardResponse.FromJson(json);
var request = new XDocument(new XElement("rqorderdetails", new XAttribute("version", "1.0"),
new XElement("rqheader", new XAttribute("ts", "2019-10-31T23:20:48"), new XAttribute("l", "de"),
new XAttribute("v", "19100000"), new XAttribute("d", "iPad7,5"),
new XAttribute("os", "iOS_13.1.3"), new XAttribute("app", "NAVIGATOR")),
new XElement("rqorder", new XAttribute("on", card.OrderId)),
new XElement("authname", new XAttribute("tln", card.Traveller.Split(" ").Last())))).ToString();
card.CardQr = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text;
card.CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text;
card.CardImage = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection;
card.QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text;
card.QrValidTo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text;
var response = new WebClient().UploadString("https://fahrkarten.bahn.de/mobile/dbc/xs.go", "POST", request);
var xmlobj = new XmlDocument();
xmlobj.LoadXml(response);
var json = JsonConvert.SerializeXmlNode(xmlobj);
var parsedCard = CardResponse.FromJson(json);
card.CardQr = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "barcode").Text;
card.CardSecCode = parsedCard.Rporderdetails.Order.Tcklist.Tck.Htdata.Ht.First(p => p.Name == "sichtmerkmal").Text;
card.CardImage = parsedCard.Rporderdetails.Order.Tcklist.Tck.Bahncardimage.CdataSection;
card.QrValidFrom = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigab").Text;
card.QrValidTo = parsedCard.Rporderdetails.Order.Tcklist.Tck.Mtk.Nvplist.Nvp.First(p => p.Name == "ebcbarcodegueltigbis").Text;
db.Update(card);
return;
}
Cards = db.Cards.Where(p => p.UserId == int.Parse(HttpContext.Session.GetString("uid"))).ToList();
db.Update(card);
return;
}
Cards = db.Cards.Where(p => p.UserId == int.Parse(HttpContext.Session.GetString("uid"))).ToList();
}
}

View File

@ -5,81 +5,78 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class DeleteModel : PageModel {
public User AuthorizedUser;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
public class DeleteModel : PageModel {
public User AuthorizedUser;
if (!Request.Query.ContainsKey("confirm") || Request.Query["confirm"] != "true")
return;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
var id = int.Parse(Request.Query["id"]);
if (!Request.Query.ContainsKey("confirm") || Request.Query["confirm"] != "true")
return;
switch (Request.Query["item"]) {
case "trip": {
var trip = db.Trips.First(p => p.TripId == id);
if (trip.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
var id = int.Parse(Request.Query["id"]);
db.Trips.Delete(p => p.TripId == id);
db.Legs.Delete(p => p.TripId == id);
break;
}
case "leg": {
var leg = db.Legs.First(p => p.LegId == id);
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
switch (Request.Query["item"]) {
case "trip": {
var trip = db.Trips.First(p => p.TripId == id);
if (trip.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
var tripid = db.Legs.First(p => p.LegId == id).TripId;
db.Trips.Delete(p => p.TripId == id);
db.Legs.Delete(p => p.TripId == id);
break;
}
case "leg": {
var leg = db.Legs.First(p => p.LegId == id);
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
db.Legs.Delete(p => p.LegId == id);
var tripid = db.Legs.First(p => p.LegId == id).TripId;
if (!db.Legs.Any(p => p.TripId == tripid))
db.Trips.Delete(p => p.TripId == tripid);
else if (db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First());
else if (db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First());
db.Legs.Delete(p => p.LegId == id);
var failsafe = false;
foreach (var failsafeleg in db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).ToList()) {
if (failsafeleg.DepTime.EndsWith("placeholder")) {
if (failsafe == false) {
failsafe = true;
}
else {
db.Legs.Delete(p => p.LegId == failsafeleg.LegId);
}
}
else {
failsafe = false;
}
if (!db.Legs.Any(p => p.TripId == tripid))
db.Trips.Delete(p => p.TripId == tripid);
else if (db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First());
else if (db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First());
var failsafe = false;
foreach (var failsafeleg in db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).ToList())
if (failsafeleg.DepTime.EndsWith("placeholder")) {
if (failsafe == false)
failsafe = true;
else
db.Legs.Delete(p => p.LegId == failsafeleg.LegId);
}
else {
failsafe = false;
}
break;
}
case "ticket": {
var leg = db.Legs.First(p => p.LegId == id);
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
break;
}
case "ticket": {
var leg = db.Legs.First(p => p.LegId == id);
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
db.Legs.Where(p => p.LegId == id).Set(p => p.TicketId, 0).Update();
break;
}
case "card": {
var card = db.Cards.First(p => p.CardId == id);
if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
db.Legs.Where(p => p.LegId == id).Set(p => p.TicketId, 0).Update();
break;
}
case "card": {
var card = db.Cards.First(p => p.CardId == id);
if (card.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
db.Cards.Delete(p => p.CardId == id);
break;
}
db.Cards.Delete(p => p.CardId == id);
break;
}
}
}

View File

@ -3,19 +3,19 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace trainav.web.Pages {
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel {
private readonly ILogger<ErrorModel> _logger;
namespace trainav.web.Pages;
public ErrorModel(ILogger<ErrorModel> logger) => _logger = logger;
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel {
private readonly ILogger<ErrorModel> _logger;
public string RequestId { get; set; }
public ErrorModel(ILogger<ErrorModel> logger) => _logger = logger;
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public string RequestId { get; set; }
public void OnGet() {
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet() {
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}

View File

@ -14,30 +14,31 @@ using trainav.web.database;
using trainav.web.database.Tables;
using Calendar = Ical.Net.Calendar;
namespace trainav.web.Pages {
public class GenIcs : PageModel {
public string IcsOutput;
public List<Leg> Legs;
public new string User;
namespace trainav.web.Pages;
public void OnGet() {
using var db = new Database.DbConn();
public class GenIcs : PageModel {
public string IcsOutput;
public List<Leg> Legs;
public new string User;
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
IcsOutput = "";
return;
}
public void OnGet() {
using var db = new Database.DbConn();
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
if (Request.Query["user"] != User) {
IcsOutput = "";
return;
}
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
IcsOutput = "";
return;
}
List<Ds100object> ds100Mapping;
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
if (Request.Query["user"] != User) {
IcsOutput = "";
return;
}
using (var reader = new StreamReader("ds100.csv"))
List<Ds100object> ds100Mapping;
using (var reader = new StreamReader("ds100.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) {
csv.Configuration.Delimiter = ";";
csv.Configuration.Encoding = Encoding.UTF8;
@ -45,60 +46,51 @@ namespace trainav.web.Pages {
ds100Mapping = csv.GetRecords<Ds100object>().ToList();
}
var calendar = new Calendar();
foreach (var leg in Legs.Where(p => p.TrainType != "placeholder")) {
var depst = ds100Mapping.Where(p => p.Station == leg.DepStation)
.DefaultIfEmpty(new Ds100object {Station = leg.DepStation, Ds100 = leg.DepStation})
.First()
.Ds100;
var arrst = ds100Mapping.Where(p => p.Station == leg.ArrStation)
.DefaultIfEmpty(new Ds100object {Station = leg.ArrStation, Ds100 = leg.ArrStation})
.First()
.Ds100;
var title = $"{depst} -> {arrst} ({leg.TrainType} {leg.TrainNr})";
var e = new CalendarEvent {
Summary = title, Start = new CalDateTime(DateTime.Parse(leg.DepTime)), End = new CalDateTime(DateTime.Parse(leg.ArrTime))
};
var calendar = new Calendar();
foreach (var leg in Legs.Where(p => p.TrainType != "placeholder")) {
var depst = ds100Mapping.Where(p => p.Station == leg.DepStation).DefaultIfEmpty(new Ds100object { Station = leg.DepStation, Ds100 = leg.DepStation }).First().Ds100;
var arrst = ds100Mapping.Where(p => p.Station == leg.ArrStation).DefaultIfEmpty(new Ds100object { Station = leg.ArrStation, Ds100 = leg.ArrStation }).First().Ds100;
var title = $"{depst} -> {arrst} ({leg.TrainType} {leg.TrainNr})";
var e = new CalendarEvent { Summary = title, Start = new CalDateTime(DateTime.Parse(leg.DepTime)), End = new CalDateTime(DateTime.Parse(leg.ArrTime)) };
if (!string.IsNullOrWhiteSpace(leg.Comment))
e.Description =
leg.Comment
+ "\n"
+ "\n"
+ $"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";
if (!string.IsNullOrWhiteSpace(leg.Comment))
e.Description = leg.Comment
+ "\n"
+ "\n"
+ $"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";
else
e.Description = $"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";
else
e.Description =
$"https://marudor.de/details/{leg.TrainType}{leg.TrainNr}/{DateTime.Parse(leg.DepTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}000/?station={leg.DepStationId}";
calendar.Events.Add(e);
}
var serializer = new CalendarSerializer();
IcsOutput = serializer.SerializeToString(calendar);
calendar.Events.Add(e);
}
private class Ds100object {
[Name("Bundesland")] public string Bundesland { get; set; }
var serializer = new CalendarSerializer();
IcsOutput = serializer.SerializeToString(calendar);
}
[Name("RB")] public string Regionalbereich { get; set; }
private class Ds100object {
[Name("Bundesland")] public string Bundesland { get; set; }
[Name("BM")] public string Bahnhofsmanagement { get; set; }
[Name("RB")] public string Regionalbereich { get; set; }
[Name("Bf. Nr.")] public string BfNr { get; set; }
[Name("BM")] public string Bahnhofsmanagement { get; set; }
[Name("Station")] public string Station { get; set; }
[Name("Bf. Nr.")] public string BfNr { get; set; }
[Name("Bf DS 100Abk.")] public string Ds100 { get; set; }
[Name("Station")] public string Station { get; set; }
[Name("Kat. Vst")] public string Kategorie { get; set; }
[Name("Bf DS 100Abk.")] public string Ds100 { get; set; }
[Name("Straße")] public string Strasse { get; set; }
[Name("Kat. Vst")] public string Kategorie { get; set; }
[Name("PLZ")] public string Plz { get; set; }
[Name("Straße")] public string Strasse { get; set; }
[Name("Ort")] public string Ort { get; set; }
[Name("PLZ")] public string Plz { get; set; }
[Name("Aufgabenträger")] public string Verkehrsverbund { get; set; }
}
[Name("Ort")] public string Ort { get; set; }
[Name("Aufgabenträger")] public string Verkehrsverbund { get; set; }
}
}

View File

@ -4,17 +4,17 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class IndexModel : PageModel {
public User AuthorizedUser;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
public class IndexModel : PageModel {
public User AuthorizedUser;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
}
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
}
}

View File

@ -6,24 +6,24 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class InspectionModel : PageModel {
public Leg Leg;
public Ticket Ticket;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
public class InspectionModel : PageModel {
public Leg Leg;
public Ticket Ticket;
using var db = new Database.DbConn();
Leg = db.Legs.First(p => p.LegId == int.Parse(Request.Query["leg"]));
Ticket = db.Tickets.First(p => p.TicketId == Leg.TicketId);
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
if (!Ticket.TicketQr.StartsWith("data:image/png"))
Ticket.TicketQr = Encoding.UTF8.GetString(Convert.FromBase64String(Ticket.TicketQr));
using var db = new Database.DbConn();
Leg = db.Legs.First(p => p.LegId == int.Parse(Request.Query["leg"]));
Ticket = db.Tickets.First(p => p.TicketId == Leg.TicketId);
if (!Ticket.TicketSecCode.StartsWith("data:image/png"))
Ticket.TicketSecCode = Encoding.UTF8.GetString(Convert.FromBase64String(Ticket.TicketSecCode));
}
if (!Ticket.TicketQr.StartsWith("data:image/png"))
Ticket.TicketQr = Encoding.UTF8.GetString(Convert.FromBase64String(Ticket.TicketQr));
if (!Ticket.TicketSecCode.StartsWith("data:image/png"))
Ticket.TicketSecCode = Encoding.UTF8.GetString(Convert.FromBase64String(Ticket.TicketSecCode));
}
}
}

View File

@ -7,47 +7,47 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
namespace trainav.web.Pages {
public class LoginModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType || string.IsNullOrWhiteSpace(Request.Form["user"]) || string.IsNullOrWhiteSpace(Request.Form["pass"]))
return;
namespace trainav.web.Pages;
using var db = new Database.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString() && p.Password == Request.Form["pass"].ToString().Sha256());
if (user == null)
return;
public class LoginModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType || string.IsNullOrWhiteSpace(Request.Form["user"]) || string.IsNullOrWhiteSpace(Request.Form["pass"]))
return;
var uid = user.UserId;
HttpContext.Session.SetString("uid", uid.ToString());
HttpContext.Session.SetString("authorized", "true");
using var db = new Database.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString() && p.Password == Request.Form["pass"].ToString().Sha256());
if (user == null)
return;
//TODO
}
var uid = user.UserId;
HttpContext.Session.SetString("uid", uid.ToString());
HttpContext.Session.SetString("authorized", "true");
//TODO
}
}
public static class StringExtensions {
public static string Sha256(this string rawData) {
// Create a SHA256
using var sha256Hash = SHA256.Create();
// ComputeHash - returns byte array
var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
var builder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
builder.Append(bytes[i].ToString("x2"));
return builder.ToString();
}
public static class StringExtensions {
public static string Sha256(this string rawData) {
// Create a SHA256
using var sha256Hash = SHA256.Create();
// ComputeHash - returns byte array
var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// Convert byte array to a string
var builder = new StringBuilder();
for (var i = 0; i < bytes.Length; i++)
builder.Append(bytes[i].ToString("x2"));
return builder.ToString();
}
public static string Base64Encode(this string plainText) {
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
public static string UrlEncode(this string plainText) => HttpUtility.UrlEncode(plainText);
public static string Delimit(this string input, int max) => input.PadRight(max, ' ').Substring(0, max).TrimEnd();
public static string Base64Encode(this string plainText) {
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
public static string UrlEncode(this string plainText) => HttpUtility.UrlEncode(plainText);
public static string Delimit(this string input, int max) => input.PadRight(max, ' ').Substring(0, max).TrimEnd();
}

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace trainav.web.Pages {
public class LogoutModel : PageModel {
public void OnGet() {
HttpContext.Session.Clear();
}
namespace trainav.web.Pages;
public class LogoutModel : PageModel {
public void OnGet() {
HttpContext.Session.Clear();
}
}

View File

@ -12,65 +12,68 @@ using Leg = trainav.web.database.Tables.Leg;
// ReSharper disable PossibleInvalidOperationException
namespace trainav.web.Pages {
public class OEAPIModel : PageModel {
public int TripId;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
public class OEAPIModel : PageModel {
public int TripId;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
var link = Request.Query["link"].ToString();
var shortcode = link;
var oepage = "oeffisear.ch";
if (link.Contains("oeffisear.ch")) {
shortcode = link.Split("/#/").Last();
}
else if (link.Contains("transit.ztn.sh")) {
shortcode = link.Split("/#/").Last();
oepage = "transit.ztn.sh";
}
var jid = shortcode.Split("/").Last();
shortcode = shortcode.Split("/").First();
using var db = new Database.DbConn();
var response = new WebClient().DownloadString($"https://{oepage}/journeys?{{\"reqId\":\"{shortcode}\"}}");
var parsed = OeapiResponse.FromJson(response);
if (!string.IsNullOrWhiteSpace(Request.Query["tripid"].ToString()))
if (db.Trips.First(p => p.TripId == int.Parse(Request.Query["tripid"].ToString())).UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
var link = Request.Query["link"].ToString();
var shortcode = link;
var oepage = "oeffisear.ch";
if (link.Contains("oeffisear.ch"))
shortcode = link.Split("/#/").Last();
else if (link.Contains("transit.ztn.sh")) {
shortcode = link.Split("/#/").Last();
oepage = "transit.ztn.sh";
}
var jid = shortcode.Split("/").Last();
shortcode = shortcode.Split("/").First();
var tripId = Request.Query["action"] == "addleg"
? int.Parse(Request.Query["tripid"])
: db.InsertWithInt32Identity(new Trip { UserId = int.Parse(HttpContext.Session.GetString("uid")) });
using var db = new Database.DbConn();
var response = new WebClient().DownloadString($"https://{oepage}/journeys?{{\"reqId\":\"{shortcode}\"}}");
var parsed = OeapiResponse.FromJson(response);
if (!string.IsNullOrWhiteSpace(Request.Query["tripid"].ToString()))
if (db.Trips.First(p => p.TripId == int.Parse(Request.Query["tripid"].ToString())).UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
var tripId = Request.Query["action"] == "addleg"
? int.Parse(Request.Query["tripid"])
: db.InsertWithInt32Identity(new Trip {UserId = int.Parse(HttpContext.Session.GetString("uid"))});
foreach (var journey in parsed.Data.Journeys[jid].Legs.Where(p => p.IsTransfer != true && p.IsWalking != true)) {
var arrtime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var deptime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
arrtime = arrtime.AddSeconds((long) journey.Arrival.PlannedTime).ToLocalTime();
deptime = deptime.AddSeconds((long) journey.Departure.PlannedTime).ToLocalTime();
var trainNo = int.Parse(journey.Line.TripNum);
if (trainNo == 0) {
var extractedTrainNo = Regex.Match(journey.Line.Name, @"\d+").Value;
if (extractedTrainNo.Length > 0)
trainNo = int.Parse(extractedTrainNo);
}
db.InsertWithInt32Identity(new database.Tables.Leg {
TripId = tripId,
UserId = int.Parse(HttpContext.Session.GetString("uid")),
TrainType = journey.Line.ProductName,
TrainNr = trainNo,
ArrStation = journey.Arrival.Point.Stop.Name,
ArrStationId = int.Parse(journey.Arrival.Point.Stop.Id),
ArrTime = arrtime.ToString("yyyy-MM-ddTHH:mm:ss"),
DepStation = journey.Departure.Point.Stop.Name,
DepStationId = int.Parse(journey.Departure.Point.Stop.Id),
DepTime = deptime.ToString("yyyy-MM-ddTHH:mm:ss")
});
foreach (var journey in parsed.Data.Journeys[jid].Legs.Where(p => p.IsTransfer != true && p.IsWalking != true)) {
var arrtime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var deptime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
arrtime = arrtime.AddSeconds((long)journey.Arrival.PlannedTime).ToLocalTime();
deptime = deptime.AddSeconds((long)journey.Departure.PlannedTime).ToLocalTime();
var trainNo = int.Parse(journey.Line.TripNum);
if (trainNo == 0) {
var extractedTrainNo = Regex.Match(journey.Line.Name, @"\d+").Value;
if (extractedTrainNo.Length > 0)
trainNo = int.Parse(extractedTrainNo);
}
TripId = tripId;
db.InsertWithInt32Identity(new Leg {
TripId = tripId,
UserId = int.Parse(HttpContext.Session.GetString("uid")),
TrainType = journey.Line.ProductName,
TrainNr = trainNo,
ArrStation = journey.Arrival.Point.Stop.Name,
ArrStationId = int.Parse(journey.Arrival.Point.Stop.Id),
ArrTime = arrtime.ToString("yyyy-MM-ddTHH:mm:ss"),
DepStation = journey.Departure.Point.Stop.Name,
DepStationId = int.Parse(journey.Departure.Point.Stop.Id),
DepTime = deptime.ToString("yyyy-MM-ddTHH:mm:ss")
});
}
TripId = tripId;
}
}
}

View File

@ -4,17 +4,17 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class PlainModel : PageModel {
public User AuthorizedUser;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
public class PlainModel : PageModel {
public User AuthorizedUser;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
}
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
var uid = int.Parse(HttpContext.Session.GetString("uid"));
using var db = new Database.DbConn();
AuthorizedUser = db.Users.FirstOrDefault(p => p.UserId == uid);
}
}

View File

@ -1,12 +1,12 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace trainav.web.Pages {
public class PrivacyModel : PageModel {
private readonly ILogger<PrivacyModel> _logger;
namespace trainav.web.Pages;
public PrivacyModel(ILogger<PrivacyModel> logger) => _logger = logger;
public class PrivacyModel : PageModel {
private readonly ILogger<PrivacyModel> _logger;
public void OnGet() { }
}
public PrivacyModel(ILogger<PrivacyModel> logger) => _logger = logger;
public void OnGet() { }
}

View File

@ -5,27 +5,27 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class RegisterModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType
|| string.IsNullOrWhiteSpace(Request.Form["user"])
|| string.IsNullOrWhiteSpace(Request.Form["pass"])
|| string.IsNullOrWhiteSpace(Request.Form["code"]))
return;
namespace trainav.web.Pages;
if (Request.Form["code"] != System.IO.File.ReadAllLines("regkey.txt")[0])
return;
public class RegisterModel : PageModel {
public void OnPost() {
if (!Request.HasFormContentType
|| string.IsNullOrWhiteSpace(Request.Form["user"])
|| string.IsNullOrWhiteSpace(Request.Form["pass"])
|| string.IsNullOrWhiteSpace(Request.Form["code"]))
return;
using var db = new Database.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString());
if (user != null)
return; //user already exists
if (Request.Form["code"] != System.IO.File.ReadAllLines("regkey.txt")[0])
return;
var uid = db.InsertWithInt32Identity(new User {Username = Request.Form["user"].ToString(), Password = Request.Form["pass"].ToString().Sha256()});
using var db = new Database.DbConn();
var user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString());
if (user != null)
return; //user already exists
HttpContext.Session.SetString("uid", uid.ToString());
HttpContext.Session.SetString("authorized", "true");
}
var uid = db.InsertWithInt32Identity(new User { Username = Request.Form["user"].ToString(), Password = Request.Form["pass"].ToString().Sha256() });
HttpContext.Session.SetString("uid", uid.ToString());
HttpContext.Session.SetString("authorized", "true");
}
}
}

View File

@ -4,24 +4,24 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class SharedTripModel : PageModel {
public List<Leg> Legs;
public bool RedirToIndex;
public new string User;
namespace trainav.web.Pages;
public void OnGet() {
using var db = new Database.DbConn();
public class SharedTripModel : PageModel {
public List<Leg> Legs;
public bool RedirToIndex;
public new string User;
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
RedirToIndex = true;
return;
}
public void OnGet() {
using var db = new Database.DbConn();
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
if (Request.Query["user"] != User)
RedirToIndex = true;
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
RedirToIndex = true;
return;
}
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
if (Request.Query["user"] != User)
RedirToIndex = true;
}
}

View File

@ -6,62 +6,62 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
using trainav.web.database;
using trainav.web.database.Tables;
namespace trainav.web.Pages {
public class TripModel : PageModel {
public List<Leg> Legs;
public bool RedirToIndex;
public new string User;
namespace trainav.web.Pages;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
public class TripModel : PageModel {
public List<Leg> Legs;
public bool RedirToIndex;
public new string User;
using var db = new Database.DbConn();
if (Request.Query.ContainsKey("separator")) {
var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Query["legid"]));
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
public void OnGet() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
db.Insert(new Leg {
TripId = int.Parse(Request.Query["id"]),
UserId = int.Parse(HttpContext.Session.GetString("uid")),
TrainType = "placeholder",
TrainNr = int.Parse(Request.Query["legid"]),
ArrStation = "_",
ArrStationId = 0,
ArrTime = "_",
DepStation = "_",
DepStationId = 0,
DepTime = leg.DepTime + "_placeholder"
});
return;
}
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
RedirToIndex = true;
return;
}
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
}
public void OnPost() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
using var db = new Database.DbConn();
if (!Request.Form.ContainsKey("comment"))
return;
var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Form["id"]));
using var db = new Database.DbConn();
if (Request.Query.ContainsKey("separator")) {
var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Query["legid"]));
if (leg.UserId != int.Parse(HttpContext.Session.GetString("uid")))
return;
leg.Comment = Request.Form["comment"];
db.Update(leg);
db.Insert(new Leg {
TripId = int.Parse(Request.Query["id"]),
UserId = int.Parse(HttpContext.Session.GetString("uid")),
TrainType = "placeholder",
TrainNr = int.Parse(Request.Query["legid"]),
ArrStation = "_",
ArrStationId = 0,
ArrTime = "_",
DepStation = "_",
DepStationId = 0,
DepTime = leg.DepTime + "_placeholder"
});
return;
}
Legs = db.Legs.Where(p => p.TripId == int.Parse(Request.Query["id"])).OrderBy(p => p.DepTime).ToList();
if (!db.Legs.Any(p => p.TripId == int.Parse(Request.Query["id"]))) {
RedirToIndex = true;
return;
}
User = db.Users.First(p => p.UserId == Legs.First().UserId).Username;
}
public void OnPost() {
if (HttpContext.Session.GetString("authorized") != "true")
return;
using var db = new Database.DbConn();
if (!Request.Form.ContainsKey("comment"))
return;
var leg = db.Legs.First(p => p.LegId == int.Parse(Request.Form["id"]));