aboutsummaryrefslogtreecommitdiff
path: root/src/app.cpp
blob: 472c26649b1fd1c7f3de2b315894dedcb1d091cf (plain)
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#include <format>
#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <expected>
#include <filesystem>
#include <iterator>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>

#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
#include <inja.hpp>
#include <mw/http_server.hpp>
#include <mw/url.hpp>
#include <mw/utils.hpp>
#include <mw/error.hpp>
#include <mw/auth.hpp>

#include "app.hpp"
#include "config.hpp"
#include "data.hpp"
#include "mw/error.hpp"

namespace
{

std::unordered_map<std::string, std::string> parseCookies(std::string_view value)
{
    std::unordered_map<std::string, std::string> cookies;
    size_t begin = 0;
    while(true)
    {
        if(begin >= value.size())
        {
            break;
        }

        size_t semicolon = value.find(';', begin);
        if(semicolon == std::string::npos)
        {
            semicolon = value.size();
        }

        std::string_view section = value.substr(begin, semicolon - begin);

        begin = semicolon + 1;
        // Skip spaces
        while(begin < value.size() && value[begin] == ' ')
        {
            begin++;
        }

        size_t equal = section.find('=');
        if(equal == std::string::npos) continue;
        cookies.emplace(section.substr(0, equal),
                        section.substr(equal+1, semicolon - equal - 1));
        if(semicolon >= value.size())
        {
            continue;
        }
    }
    return cookies;
}

void setTokenCookies(const mw::Tokens& tokens, App::Response& res)
{
    int64_t expire_sec = 300;
    if(tokens.expiration.has_value())
    {
        auto expire = std::chrono::duration_cast<std::chrono::seconds>(
            *tokens.expiration - mw::Clock::now());
        expire_sec = expire.count();
    }
    res.set_header("Set-Cookie", std::format(
                       "webdir-access-token={}; Max-Age={}",
                       mw::urlEncode(tokens.access_token), expire_sec));
    // Add refresh token to cookie, with one month expiration.
    if(tokens.refresh_token.has_value())
    {
        expire_sec = 1800;
        if(tokens.refresh_expiration.has_value())
        {
            auto expire = std::chrono::duration_cast<std::chrono::seconds>(
                *tokens.refresh_expiration - mw::Clock::now());
            expire_sec = expire.count();
        }

        res.set_header("Set-Cookie", std::format(
                           "webdir-refresh-token={}; Max-Age={}",
                           mw::urlEncode(*tokens.refresh_token), expire_sec));
    }
}

mw::HTTPServer::ListenAddress listenAddrFromConfig(const Configuration& config)
{
    if(config.listen_port == 0)
    {
        mw::SocketFileInfo sock(config.listen_address);
        sock.user = config.socket_user;
        sock.group = config.socket_group;
        sock.permission = config.socket_permission;
        return sock;
    }

    mw::IPSocketInfo sock;
    sock.address = config.listen_address;
    sock.port = config.listen_port;
    return sock;
}

nlohmann::json jsonFromItem(const LinkItem& item)
{
    return {
        {"id", item.id},
        {"owner_id", item.owner_id},
        {"parent_id", item.parent_id},
        {"name", item.name},
        {"url", item.url},
        {"description", item.description},
        {"visibility", LinkItem::visibilityToStr(item.visibility)},
        {"time", mw::timeToSeconds(item.time)},
        {"time_str", mw::timeToStr(item.time)},
    };
}

} // namespace

App::App(const Configuration& conf,
         std::unique_ptr<DataSourceInterface> data_source,
         std::unique_ptr<mw::AuthInterface> openid_auth)
        : mw::HTTPServer(listenAddrFromConfig(conf)),
          config(conf),
          templates((std::filesystem::path(config.data_dir) / "templates" / "")
                    .string()),
          data(std::move(data_source)),
          auth(std::move(openid_auth))
{
    auto u = mw::URL::fromStr(conf.base_url);
    if(u.has_value())
    {
        base_url = *std::move(u);
    }

    templates.add_callback("url_for", [&](const inja::Arguments& args) ->
                           std::string
    {
        switch(args.size())
        {
        case 1:
            return urlFor(args.at(0)->get_ref<const std::string&>());
        case 2:
            return urlFor(args.at(0)->get_ref<const std::string&>(),
                          args.at(1)->get_ref<const std::string&>());
        default:
            return "Invalid number of url_for() arguments";
        }
    });
}

std::string App::urlFor(const std::string& name, const std::string& arg) const
{
    if(name == "statics")
    {
        return mw::URL(base_url).appendPath("_/statics").appendPath(arg).str();
    }
    if(name == "login")
    {
        return mw::URL(base_url).appendPath("_/login").str();
    }
    if(name == "openid-redirect")
    {
        return mw::URL(base_url).appendPath("_/openid-redirect").str();
    }
    if(name == "index")
    {
        return base_url.str();
    }
    if(name == "dir")           // /dir/<username or item_id>
    {
        return mw::URL(base_url).appendPath("dir").appendPath(arg).str();
    }

    return "";
}

void App::handleIndex(Response& res) const
{
    res.set_redirect(urlFor("dir", "mw"), 301);
}

void App::handleDir(const Request& req, Response& res)
{
    auto session = prepareSession(req, res, true);
    if(!req.has_param("owner_or_id"))
    {
        res.status = 400;
        res.set_content("Need parameter", "text/plain");
        return;
    }
    std::string owner_or_id = req.get_param_value("owner_or_id");
    std::string owner;
    // If owner_or_id is an integer, it’s the ID of an item. Otherwise
    // it’s a username.
    auto item_id_maybe = mw::strToNumber<int64_t>(owner_or_id);
    std::vector<LinkItem> items;
    if(item_id_maybe.has_value())
    {
        ASSIGN_OR_RESPOND_ERROR(std::optional<LinkItem> item,
                                data->itemByID(*item_id_maybe), res);
        if(!item.has_value())
        {
            res.status = 400;
            res.set_content("Item not found", "text/plain");
            return;
        }
        ASSIGN_OR_RESPOND_ERROR(std::optional<User> user,
                                data->userByID(item->owner_id), res);
        if(!user.has_value())
        {
            res.status = 500;
            res.set_content("Owner of item not found", "text/plain");
            return;
        }
        owner = user->name;
        ASSIGN_OR_RESPOND_ERROR(items, data->itemsByParent(*item_id_maybe),
                                res);
    }
    else
    {
        ASSIGN_OR_RESPOND_ERROR(std::optional<User> user,
                                data->userByName(owner_or_id), res);
        if(!user.has_value())
        {
            res.status = 404;
            res.set_content(std::string("Unknown user: ") + owner_or_id,
                            "text/plain");
            return;
        }
        owner = owner_or_id;
        ASSIGN_OR_RESPOND_ERROR(items, data->itemsTopLevelByUser(user->id),
                                res);
    }

    nlohmann::json items_data = nlohmann::json::array();
    for(const LinkItem& item: items)
    {
        if(item.visibility == LinkItem::PRIVATE)
        {
            if(session->status == SessionValidation::INVALID)
            {
                continue;
            }
            if(session->user.name != owner)
            {
                continue;
            }
        }
        items_data.push_back(jsonFromItem(item));
    }
    nlohmann::json data = {
        {"session_user", session->user.name},
        {"owner", owner},
        {"this_url", req.target},
        {"items", std::move(items_data)},
    };
    std::string result = templates.render_file("dir.html", std::move(data));
    res.set_content(result, "text/html");
}

void App::handleLogin(Response& res) const
{
    res.set_redirect(auth->initialURL(), 301);
}

void App::handleOpenIDRedirect(const Request& req, Response& res) const
{
    if(req.has_param("error"))
    {
        res.status = 500;
        if(req.has_param("error_description"))
        {
            res.set_content(
                std::format("{}: {}.", req.get_param_value("error"),
                            req.get_param_value("error_description")),
                "text/plain");
        }
        return;
    }
    else if(!req.has_param("code"))
    {
        res.status = 500;
        res.set_content("No error or code in auth response", "text/plain");
        return;
    }

    std::string code = req.get_param_value("code");
    spdlog::debug("OpenID server visited {} with code {}.", req.path, code);
    ASSIGN_OR_RESPOND_ERROR(mw::Tokens tokens, auth->authenticate(code), res);
    ASSIGN_OR_RESPOND_ERROR(mw::UserInfo user, auth->getUser(tokens), res);

    setTokenCookies(tokens, res);
    res.set_redirect(urlFor("index"), 301);
}


std::string App::getPath(const std::string& name,
                         const std::string& arg_name) const
{
    return mw::URL::fromStr(urlFor(name, std::string(":") + arg_name)).value()
        .path();
}

void App::setup()
{
    {
        std::string statics_dir = (std::filesystem::path(config.data_dir) /
                                   "statics").string();
        spdlog::info("Mounting static dir at {}...", statics_dir);
        if (!server.set_mount_point("/_/statics", statics_dir))
        {
            spdlog::error("Failed to mount statics");
            return;
        }
    }

    server.Get(getPath("login"), [&]([[maybe_unused]] const Request& req,
                                     Response& res)
    {
        handleLogin(res);
    });
    server.Get(getPath("openid-redirect"), [&](const Request& req, Response& res)
    {
        handleOpenIDRedirect(req, res);
    });
    server.Get(getPath("index"), [&]([[maybe_unused]] const Request& req,
                                     Response& res)
    {
        handleIndex(res);
    });
    server.Get(getPath("dir", "owner_or_id"),
               [&]([[maybe_unused]] const Request& req, Response& res)
    {
        handleDir(req, res);
    });
}

mw::E<App::SessionValidation> App::validateSession(const Request& req) const
{
    if(!req.has_header("Cookie"))
    {
        spdlog::debug("Request has no cookie.");
        return SessionValidation::invalid();
    }

    auto cookies = parseCookies(req.get_header_value("Cookie"));
    if(auto it = cookies.find("webdir-access-token");
       it != std::end(cookies))
    {
        spdlog::debug("Cookie has access token.");
        mw::Tokens tokens;
        tokens.access_token = it->second;
        mw::E<mw::UserInfo> user = auth->getUser(tokens);
        if(user.has_value())
        {
            return SessionValidation::valid(*std::move(user));
        }
    }
    // No access token or access token expired
    if(auto it = cookies.find("webdir-refresh-token");
       it != std::end(cookies))
    {
        spdlog::debug("Cookie has refresh token.");
        // Try to refresh the tokens.
        ASSIGN_OR_RETURN(mw::Tokens tokens, auth->refreshTokens(it->second));
        ASSIGN_OR_RETURN(mw::UserInfo user, auth->getUser(tokens));
        return SessionValidation::refreshed(std::move(user), std::move(tokens));
    }
    return SessionValidation::invalid();
}

std::optional<App::SessionValidation> App::prepareSession(
    const Request& req, Response& res, bool allow_error_and_invalid) const
{
    mw::E<SessionValidation> session = validateSession(req);
    if(!session.has_value())
    {
        if(allow_error_and_invalid)
        {
            return SessionValidation::invalid();
        }
        else
        {
            res.status = 500;
            res.set_content("Failed to validate session.", "text/plain");
            return std::nullopt;
        }
    }

    switch(session->status)
    {
    case SessionValidation::INVALID:
        if(allow_error_and_invalid)
        {
            return *session;
        }
        else
        {
            res.status = 401;
            res.set_content("Invalid session.", "text/plain");
            return std::nullopt;
        }
    case SessionValidation::VALID:
        break;
    case SessionValidation::REFRESHED:
        setTokenCookies(session->new_tokens, res);
        break;
    }
    return *session;
}