aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/App.kt
blob: d9290ba990621f7e9e74adcde5301be72fedde5f (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
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
package space.anity

import com.fizzed.rocker.*
import com.fizzed.rocker.runtime.*
import io.javalin.*
import io.javalin.apibuilder.ApiBuilder.*
import io.javalin.rendering.*
import io.javalin.rendering.template.TemplateUtil.model
import io.javalin.security.*
import io.javalin.security.SecurityUtil.roles
import org.slf4j.*
import java.net.*
import kotlin.system.*

const val debug = true
var silent = true
// TODO: Add abstract and secure file home support for windows/BSD/macOS
val fileHome = if (System.getProperty("os.name") != "Linux" || debug) "files" else "/usr/share/kloud/files"
val databaseController = DatabaseController()
val userHandler = UserHandler()
val fileController = FileController()
private val log = LoggerFactory.getLogger("App.kt")

fun main(args: Array<String>) {
    val app = startServer(args)

    // Set up templating
    RockerRuntime.getInstance().isReloading = false
    JavalinRenderer.register(
        FileRenderer { filepath, model -> Rocker.template(filepath).bind(model).render().toString() }, ".rocker.html"
    )

    databaseController.initDatabase()

    app.routes {
        /**
         * Normalizes and cleans the requested url
         */
        before("/*") { ctx ->
            if (URI(ctx.url()).normalize().toString() != ctx.url()) ctx.redirect(URI(ctx.url()).normalize().toString())
        }

        /**
         * Renders the static resources (important for deployed jar files)
         */
        get(
            "/css/*", { ctx ->
                ctx.contentType("text/css")
                try {
                    ctx.result(Thread.currentThread().contextClassLoader.getResourceAsStream("css/" + ctx.splat(0)))
                } catch (_: Exception) {
                    throw NotFoundResponse()
                }
            },
            roles(Roles.GUEST, Roles.USER)
        )
        get(
            "/js/*", { ctx ->
                ctx.contentType("text/javascript")
                try {
                    ctx.result(Thread.currentThread().contextClassLoader.getResourceAsStream("js/" + ctx.splat(0)))
                } catch (_: Exception) {
                    throw NotFoundResponse()
                }
            },
            roles(Roles.GUEST, Roles.USER)
        )
        get(
            "/fonts/*", { ctx ->
                try {
                    ctx.result(Thread.currentThread().contextClassLoader.getResourceAsStream("fonts/" + ctx.splat(0)))
                } catch (_: Exception) {
                    throw NotFoundResponse()
                }
            },
            roles(Roles.GUEST, Roles.USER)
        )

        /**
         * Main page
         */
        get("/", { ctx ->
            ctx.render(
                "index.rocker.html",
                model("username", databaseController.getUsername(userHandler.getVerifiedUserId(ctx)), "ctx", ctx)
            )
        }, roles(Roles.GUEST, Roles.USER))

        /**
         * Renders the login page
         */
        get("/user/login", userHandler::renderLogin, roles(Roles.GUEST, Roles.USER))

        /**
         * Endpoint for user authentication
         */
        post("/user/login", userHandler::login, roles(Roles.GUEST))

        /**
         * Logs the user out
         */
        get("/user/logout", userHandler::logout, roles(Roles.USER))

        /**
         * Toggles the users theme
         */
        post("/user/theme", userHandler::toggleTheme, roles(Roles.USER))

        /**
         * Renders the registration page
         */
        get("/user/register", userHandler::renderRegistration, roles(Roles.GUEST))

        /**
         * Registers new user
         */
        post("/user/register", userHandler::register, roles(Roles.GUEST))

        /**
         * Adds part of a new user (username) to database
         */
        post("/user/add", databaseController::indexUserRegistration, roles(Roles.ADMIN))

        /**
         * Renders the admin interface
         */
        get("/admin", userHandler::renderAdmin, roles(Roles.ADMIN))

        /**
         * Renders the setup page (only on initial use)
         */
        get("/setup", userHandler::renderSetup, roles(Roles.GUEST))

        /**
         * Endpoint for setup (only on initial use)
         */
        post("/setup", userHandler::setup, roles(Roles.GUEST))

        /**
         * Renders the file list view
         */
        get("/files/*", fileController::crawl, roles(Roles.USER))

        /**
         * Receives and saves multipart media data
         */
        post("/upload/*", fileController::upload, roles(Roles.USER))

        /**
         * Indexes every file of the user into the database
         */
        get("/index", fileController::indexAll, roles(Roles.USER))

        /**
         * Deletes file
         */
        post("/delete/*", fileController::delete, roles(Roles.USER))

        /**
         * Shares file
         */
        post("/share/*", fileController::share, roles(Roles.USER))

        /**
         * Shares file in directory
         */
        post("/share", fileController::handleSharedFile, roles(Roles.USER))

        /**
         * Shows the shared file
         */
        get("/shared", fileController::renderShared, roles(Roles.GUEST, Roles.USER))
    }
}

/**
 * Sets up the roles with the database and declares the handling of roles
 */
fun roleManager(handler: Handler, ctx: Context, permittedRoles: Set<Role>) {
    if (userHandler.getVerifiedUserId(ctx) == ctx.cookieStore("userId") ?: "userId"
        && databaseController.getRoles(userHandler.getVerifiedUserId(ctx)).any { it in permittedRoles }
    ) handler.handle(ctx)
    else if (userHandler.getVerifiedUserId(ctx) != ctx.cookieStore("userId") ?: "userId"
        && databaseController.getRoles(userHandler.getVerifiedUserId(ctx)).any { it in permittedRoles }
    ) handler.handle(ctx)
    else ctx.status(401).redirect("/user/login")
}

/**
 * Starts the server and parses the command line arguments
 */
fun startServer(args: Array<String>): Javalin {
    var runServer = true
    var port = 7000

    args.forEachIndexed { index, element ->
        run {
            val wantsDebug = element.startsWith("-d") || element.startsWith("--debug")
            val wantsPort = element.startsWith("-p") || element.startsWith("--port")
            val wantsHelp = element.startsWith("-h") || element.startsWith("--help")

            if (wantsPort) {
                val portArgument = args[index + 1].toInt()
                if (portArgument in 1..65535) port = portArgument
            }
            if (wantsDebug) {
                silent = false
            }
            if (wantsHelp) {
                runServer = false
                log.info(
                    "Help: \n" +
                            "Use -p or --port to specify a port\n" +
                            "Use -d or --debug to enable debug mode\n" +
                            "Use -h or --help to show this help message"
                )
            }
        }
    }

    return if (runServer) {
        try {
            Javalin.create().apply {
                port(port)
                accessManager { handler, ctx, permittedRoles -> roleManager(handler, ctx, permittedRoles) }
                disableStartupBanner()
            }.start()
        } catch (_: Exception) {
            throw PortUnreachableException("Port already in use!")
        }
    } else exitProcess(1)
}

/**
 * Declares the roles in which a user can be in
 */
enum class Roles : Role {
    ADMIN, USER, GUEST
}