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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
|
package space.anity
import at.favre.lib.crypto.bcrypt.*
import io.javalin.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.*
import org.joda.time.*
import java.sql.*
import java.util.logging.*
class DatabaseController(dbFileLocation: String = "main.db") {
val db: Database = Database.connect("jdbc:sqlite:$dbFileLocation", "org.sqlite.JDBC")
private val log = Logger.getLogger(this.javaClass.name)
/**
* Database table indexing the file locations
*/
object FileLocation : Table() {
val id = integer("id").autoIncrement().primaryKey()
val path = text("path")
val isDirectory = bool("isDirectory").default(false)
val userId = integer("userId").references(UserData.id)
val accessId = varchar("accessId", 64).uniqueIndex()
val isShared = bool("isShared").default(false)
}
/**
* Database table indexing the users with their regarding passwords
*/
object UserData : Table() {
val id = integer("id").autoIncrement().primaryKey()
val username = varchar("username", 24).uniqueIndex()
val password = varchar("password", 64)
val verification = varchar("verification", 64).uniqueIndex()
}
/**
* Database table indexing the users with their regarding role (multi line per user)
*/
object UserRoles : Table() {
val id = integer("id").autoIncrement().primaryKey()
val userId = integer("userId").references(UserData.id)
val roleId = integer("role").references(RolesData.id)
}
/**
* Database table indexing the soon-to-be registered users by username
*/
object UserRegistration : Table() {
val id = integer("id").autoIncrement().primaryKey()
val username = varchar("username", 24).uniqueIndex()
val token = varchar("token", 64).uniqueIndex()
}
/**
* Database table declaring available roles
*/
object RolesData : Table() {
val id = integer("id").autoIncrement().primaryKey()
val role = varchar("roles", 16)
}
/**
* Database table indexing the login attempts of an ip in combination with the timestamp
*/
object LoginAttempts : Table() {
val id = integer("id").autoIncrement().primaryKey()
val ip = varchar("ip", 16)
val timestamp = datetime("timestamp")
}
/**
* Database table storing general data/states
*/
object General : Table() {
val id = integer("id").autoIncrement().primaryKey()
val initialUse = bool("initialUse").default(true)
val isSetup = bool("isSetup").default(false)
}
init {
// Create connection
TransactionManager.manager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE
// Add tables
transaction {
SchemaUtils.createMissingTablesAndColumns(
FileLocation,
UserData,
UserRoles,
UserRegistration,
RolesData,
LoginAttempts,
General
)
}
}
/**
* Creates the user in the database using username, password and the role
*/
fun createUser(usernameString: String, passwordString: String, roleString: String): Boolean {
return transaction {
try {
val usersId = UserData.insert {
it[username] = usernameString
it[password] = BCrypt.withDefaults().hashToString(12, passwordString.toCharArray())
it[verification] = generateRandomString()
}[UserData.id]
UserRoles.insert { roles ->
roles[userId] = usersId!!
roles[roleId] = RolesData.select { RolesData.role eq roleString }.map { it[RolesData.id] }[0]
}
true
} catch (_: Exception) {
log.warning("User already exists!")
false
}
}
}
/**
* Checks whether the user is allowed to register
*/
fun isUserRegistrationValid(usernameString: String, tokenString: String): Boolean {
return transaction {
try {
if (UserData.select { UserData.username eq usernameString }.empty() &&
UserRegistration.select { UserRegistration.token eq tokenString }.map { it[UserRegistration.token] }[0] == tokenString
) {
usernameString == UserRegistration.select { UserRegistration.username eq usernameString }.map { it[UserRegistration.username] }[0]
} else false
} catch (_: Exception) {
false
}
}
}
/**
* Adds a user to the registration table
*/
fun indexUserRegistration(ctx: Context) {
val usernameString = ctx.queryParam("username", "").toString()
val tokenString = generateRandomString()
var error = false
transaction {
try {
UserRegistration.insert {
it[username] = usernameString
it[token] = tokenString
}
} catch (_: Exception) {
error = true
}
}
if (error) ctx.result("User already exists")
else ctx.result(
"Registration url: " + "http://${ctx.host()}/user/register?username=$usernameString&token=$tokenString"
)
}
/**
* Removes the registration index of [usernameString]
*/
fun removeRegistrationIndex(usernameString: String) {
transaction {
UserRegistration.deleteWhere { UserRegistration.username eq usernameString }
}
}
/**
* Tests whether the password [passwordString] of the user [usernameString] is correct
*/
fun checkUser(usernameString: String, passwordString: String): Boolean {
return transaction {
try {
val passwordHash =
UserData.select { UserData.username eq usernameString }.map { it[UserData.password] }[0]
BCrypt.verifyer().verify(passwordString.toCharArray(), passwordHash).verified
} catch (_: Exception) {
false
}
}
}
/**
* Returns the corresponding username using [userId]
*/
fun getUsername(userId: Int): String {
return transaction {
try {
UserData.select { UserData.id eq userId }.map { it[UserData.username] }[0]
} catch (_: Exception) {
""
}
}
}
/**
* Returns the corresponding username using [verificationId]
*/
fun getUserIdByVerificationId(verificationId: String): Int {
return transaction {
try {
UserData.select { UserData.verification eq verificationId }.map { it[UserData.id] }[0]
} catch (_: Exception) {
-1
}
}
}
/**
* Returns the corresponding verification id using [usernameString]
*/
fun getVerificationId(usernameString: String): String {
return transaction {
try {
UserData.select { UserData.username eq usernameString }.map { it[UserData.verification] }[0]
} catch (_: Exception) {
""
}
}
}
/**
* Returns the corresponding userId using [usernameString]
*/
fun getUserId(usernameString: String): Int {
return transaction {
try {
UserData.select { UserData.username eq usernameString }.map { it[UserData.id] }[0]
} catch (_: Exception) {
-1
}
}
}
/**
* Returns the corresponding role using [userId]
*/
fun getRoles(userId: Int): List<Roles> {
return transaction {
try {
val userRoleId = UserRoles.select { UserRoles.userId eq userId }.map { it[UserRoles.roleId] }[0]
val userRoles = mutableListOf<Roles>()
RolesData.select { RolesData.id eq userRoleId }.map { it[RolesData.role] }.forEach {
when (Roles.valueOf(it)) {
Roles.GUEST -> {
userRoles.add(Roles.GUEST)
}
Roles.USER -> {
userRoles.add(Roles.USER)
}
Roles.ADMIN -> {
userRoles.add(Roles.GUEST)
userRoles.add(Roles.USER)
userRoles.add(Roles.ADMIN)
}
}
}
userRoles
} catch (_: Exception) {
listOf(Roles.GUEST)
}
}
}
/**
* Adds the uploaded file to the database
*/
fun addFile(fileLocation: String, usersId: Int, isDirectoryBool: Boolean = false): Boolean {
return transaction {
try {
if (FileLocation.select { (FileLocation.path eq fileLocation) and (FileLocation.userId eq usersId) }.empty()) {
FileLocation.insert {
it[path] = fileLocation
it[userId] = usersId
it[accessId] = generateRandomString()
it[isDirectory] = isDirectoryBool
}
true
} else {
if (!isDirectoryBool) log.warning("File already exists!")
false
}
} catch (_: Exception) {
if (!isDirectoryBool) log.warning("File already exists!")
false
}
}
}
/**
* Removes the file from the database
*/
fun deleteFile(fileLocation: String, userId: Int) {
transaction {
try {
// TODO: Think of new solution for directory deleting (instead of wildcards)
FileLocation.deleteWhere { (FileLocation.path like "$fileLocation%") and (FileLocation.userId eq userId) }
} catch (_: Exception) {
log.warning("File does not exist!")
}
}
}
/**
* Returns the accessId of the given file
*/
fun getAccessId(fileLocation: String, userId: Int): String {
return transaction {
try {
FileLocation.update({ (FileLocation.userId eq userId) and (FileLocation.path like "$fileLocation%") }) {
it[isShared] = true
}
FileLocation.select { (FileLocation.path eq fileLocation) and (FileLocation.userId eq userId) }.map { it[FileLocation.accessId] }[0]
} catch (_: Exception) {
""
}
}
}
/**
* Returns accessId of file in directory
*/
fun getAccessIdOfDirectory(filename: String, accessId: String): String {
return transaction {
try {
val fileData =
FileLocation.select {
FileLocation.accessId eq accessId
}.map { it[FileLocation.path] to it[FileLocation.userId] to it[FileLocation.isShared] }[0]
if (fileData.second)
FileLocation.select {
(FileLocation.path eq "${fileData.first.first}${filename.substring(1)}") and (FileLocation.userId eq fileData.first.second)
}.map { it[FileLocation.accessId] }[0]
else ""
} catch (_: Exception) {
""
}
}
}
/**
* Gets the shared file via [accessId]
*/
fun getSharedFile(accessId: String): ReturnFileData {
return transaction {
try {
if (FileLocation.select { FileLocation.accessId eq accessId }.map { it[FileLocation.isShared] }[0]) {
val userId =
FileLocation.select { FileLocation.accessId eq accessId }.map { it[FileLocation.userId] }[0]
val fileLocation =
FileLocation.select { FileLocation.accessId eq accessId }.map { it[FileLocation.path] }[0]
val isDir =
FileLocation.select { FileLocation.accessId eq accessId }.map { it[FileLocation.isDirectory] }[0]
ReturnFileData(userId, fileLocation, isDir)
} else
ReturnFileData(-1, "", false)
} catch (_: Exception) {
log.warning("File does not exist!")
ReturnFileData(-1, "", false)
}
}
}
/**
* Checks whether the site has been set up
*/
fun isSetup(): Boolean {
return transaction {
try {
General.selectAll().map { it[General.isSetup] }[0]
} catch (_: Exception) {
false
}
}
}
/**
* Toggles the setup state
*/
fun toggleSetup() {
transaction {
General.update({ General.initialUse eq false }) {
it[isSetup] = true
}
}
}
/**
* Adds an login attempt to the database
*/
fun loginAttempt(dateTime: DateTime, requestIp: String) {
transaction {
LoginAttempts.insert {
it[timestamp] = dateTime
it[ip] = requestIp
}
}
}
/**
* Gets all login attempts of [requestIp]
*/
fun getLoginAttempts(requestIp: String): List<Pair<DateTime, String>> {
return transaction {
LoginAttempts.select { LoginAttempts.ip eq requestIp }
.map { it[LoginAttempts.timestamp] to it[LoginAttempts.ip] }
}
}
/**
* Initializes the database
*/
fun initDatabase() {
val initialUseRow = transaction { General.selectAll().map { it[General.initialUse] } }
if (initialUseRow.isEmpty() || initialUseRow[0]) {
transaction {
RolesData.insert {
it[role] = "ADMIN"
}
RolesData.insert {
it[role] = "USER"
}
RolesData.insert {
it[role] = "GUEST"
}
UserRoles.insert {
it[userId] = 1
it[roleId] = 1
}
General.insert {
it[initialUse] = false
}
}
} else {
log.info("Already initialized Database.")
}
}
/**
* Generates a random string with [length] characters
*/
private fun generateRandomString(length: Int = 64): String {
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
}
data class ReturnFileData(
val userId: Int,
val fileLocation: String,
val isDirectory: Boolean
)
|