aboutsummaryrefslogtreecommitdiffstats
path: root/Program.cs
blob: 13923c92ed9d8e785c3d14faa6094ca8a06b0b76 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using MySqlConnector;
using System.Security.Cryptography;
using System.Text;

var SK_DB = "db-cred";
var SK_LOGGED = "logged-in";

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    WebRootPath = "frontend/dist"
});

builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();

var connection = new MySqlConnection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();

app.MapPost("/login", (LoginForm lgf, HttpResponse response, HttpContext context) =>
{
    var pass = hashPassword(lgf.password!);
    connection = new MySqlConnection(context.Session.GetString(SK_DB));
    connection.Open();
    var command = new MySqlCommand(null, connection);

    if (lgf.mode == "login")
    {
        command.CommandText = "SELECT * FROM user WHERE login = @login AND password = @password;";

        command.Parameters.AddWithValue("@login", lgf.login);
        command.Parameters.AddWithValue("@password", pass);

        var reader = command.ExecuteReader();
        while (reader.Read())
        {
            context.Session.SetString(SK_LOGGED, "true");
            connection.Close();
            return "ok";
        }
    }
    else
    {
        Console.WriteLine("registering");

        command.CommandText = "INSERT INTO user (email, login, password) VALUES (@email, @login, @password)";

        command.Parameters.AddWithValue("@login", lgf.login);
        command.Parameters.AddWithValue("@password", pass);
        command.Parameters.AddWithValue("@email", lgf.email);

        command.ExecuteNonQuery();
        connection.Close();
        return "ok";
    }
    connection.Close();
    return "error";
});
app.MapPost("/check-db", async (DbForm dbf, HttpResponse response, HttpContext context) =>
{
    try
    {
        var connstr = $"server={dbf.server};port={dbf.port};user={dbf.user};password={dbf.password};database={dbf.database}";
        var conn = new MySqlConnection(connstr);
        Console.WriteLine(connstr);
        await conn.OpenAsync();
        connection = conn;
        await conn.CloseAsync();
        context.Session.SetString(SK_DB, connstr);
        return "ok";
    }
    catch (Exception _)
    {
        return "error";
    }
});
app.MapMethods("/check-db", new[] { "OPTIONS" }, (HttpResponse response) =>
{
    response.Headers.AccessControlAllowOrigin = "*";
    response.Headers.AccessControlAllowHeaders = "*";
    return "ok";
});
app.MapGet("/", (HttpContext context) =>
{
    context.Response.SendFileAsync("./frontend/dist/index.html");
});
app.MapPost("/book", (Book book, HttpContext context) =>
{
    if (!checkRequest(context)) return "error";
    connection.Open();
    var command = new MySqlCommand(null, connection);
    if (book.id == null)
    {
        command.CommandText = "INSERT INTO book (author, title, year, publisher, isbn, format, pages, description) VALUES (@author, @title, @year, @publisher, @isbn, @format, @pages, @description)";
    }
    else
    {
        command.CommandText = "UPDATE book SET author = @author, title = @title, year = @year, publisher = @publisher, isbn = @isbn, format = @format, pages = @pages, description = @description WHERE id = @id";
        command.Parameters.AddWithValue("@id", book.id);
    }
    command.Parameters.AddWithValue("@author", book.author);
    command.Parameters.AddWithValue("@title", book.title);
    command.Parameters.AddWithValue("@year", MySqlDbType.Int32).Value = book.year;
    command.Parameters.AddWithValue("@publisher", book.publisher);
    command.Parameters.AddWithValue("@isbn", book.isbn);
    command.Parameters.AddWithValue("@format", book.format);
    command.Parameters.AddWithValue("@pages", book.pages);
    command.Parameters.AddWithValue("@description", book.description);
    command.ExecuteNonQuery();
    connection.Close();
    return "ok";
});
app.MapGet("/books", (HttpContext context) =>
{
    if (!checkRequest(context)) return Results.Ok("error");

    connection.Open();
    var command = new MySqlCommand("SELECT * FROM book;", connection);
    var reader = command.ExecuteReader();

    List<Dictionary<string, string>> books = new List<Dictionary<string, string>>();

    while (reader.Read())
    {
        Dictionary<string, string> book = new Dictionary<string, string>();

        book.Add("id", reader.GetValue(0).ToString() ?? "");
        book.Add("author", reader.GetValue(1).ToString() ?? "");
        book.Add("title", reader.GetValue(2).ToString() ?? "");
        book.Add("year", reader.GetValue(3).ToString() ?? "");
        book.Add("publisher", reader.GetValue(4).ToString() ?? "");
        book.Add("isbn", reader.GetValue(5).ToString() ?? "");
        book.Add("format", reader.GetValue(6).ToString() ?? "");
        book.Add("pages", reader.GetValue(7).ToString() ?? "");
        book.Add("description", reader.GetValue(8).ToString() ?? "");

        books.Add(book);
    }

    connection.Close();
    return Results.Json(books);
});

// Remove book
app.MapDelete("/book", (HttpContext context) =>
{
    if (!checkRequest(context)) return Results.Unauthorized();

    connection.Open();
    var command = new MySqlCommand(null, connection);

    command.CommandText = "DELETE FROM book WHERE id = @id;";
    command.Parameters.AddWithValue("@id", MySqlDbType.Int32).Value = Int32.Parse(context.Request.Query["bid"]);
    command.ExecuteNonQuery();

    connection.Close();
    return Results.Ok("ok");
});

app.Run("http://localhost:8000");

String hashPassword(string pass)
{
    var sha256 = SHA256.Create();
    return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(pass!)));
}

Boolean checkRequest(HttpContext context)
{
    return context.Session.GetString(SK_LOGGED) == "true";
}

class DbForm
{
    public string? server { get; set; }
    public int port { get; set; }
    public string? database { get; set; }
    public string? user { get; set; }
    public string? password { get; set; }
}
class LoginForm
{
    public string? email { get; set; }
    public string? login { get; set; }
    public string? password { get; set; }
    public string? mode { get; set; }
}
class Book
{
    public int? id { get; set; }
    public string? author { get; set; }
    public string? title { get; set; }
    public int? year { get; set; }
    public string? publisher { get; set; }
    public string? isbn { get; set; }
    public string? format { get; set; }
    public int? pages { get; set; }
    public string? description { get; set; }
}