Compare commits

...

5 commits

Author SHA1 Message Date
a3409c0a42 Updated chi
Signed-off-by: arzumify <jliwin98@danwin1210.de>
2025-03-20 18:40:22 +00:00
6cda63c538 Fixed a potential directory traversal, fixed storage being very borked, made the auth login process less memory intensive and rely more on JWTs
Signed-off-by: arzumify <jliwin98@danwin1210.de>
2025-01-25 14:47:51 +00:00
2ece60f84e Updated nucleus libs, yet again
Signed-off-by: arzumify <jliwin98@danwin1210.de>
2025-01-11 15:50:51 +00:00
ffc03f2213 Updated nucleus libs, tidied modfile
Signed-off-by: arzumify <jliwin98@danwin1210.de>
2025-01-11 15:45:57 +00:00
a65b7f6e0d Updated nucleus libs
Signed-off-by: arzumify <jliwin98@danwin1210.de>
2025-01-11 15:42:55 +00:00
6 changed files with 122 additions and 133 deletions

18
go.mod
View file

@ -4,23 +4,21 @@ go 1.23.3
require (
git.ailur.dev/ailur/fg-library/v3 v3.6.2
git.ailur.dev/ailur/fg-nucleus-library v1.1.2
git.ailur.dev/ailur/fg-nucleus-library v1.2.2
git.ailur.dev/ailur/pow v1.0.3
github.com/CAFxX/httpcompression v0.0.9
github.com/cespare/xxhash/v2 v2.3.0
github.com/go-chi/chi/v5 v5.2.0
github.com/go-playground/validator/v10 v10.23.0
github.com/go-chi/chi/v5 v5.2.1
github.com/go-playground/validator/v10 v10.25.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/klauspost/compress v1.17.11
github.com/klauspost/compress v1.18.0
github.com/lib/pq v1.10.9
github.com/mattn/go-sqlite3 v1.14.24
gopkg.in/yaml.v3 v3.0.1
)
require (
git.ailur.dev/ailur/datatracker v1.0.0 // indirect
git.ailur.dev/ailur/fg-library/v2 v2.0.1 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/go-playground/locales v0.14.1 // indirect
@ -29,9 +27,9 @@ require (
github.com/leodido/go-urn v1.4.0 // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
github.com/stretchr/testify v1.10.0 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/net v0.34.0 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/crypto v0.36.0 // indirect
golang.org/x/net v0.37.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.23.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)

46
go.sum
View file

@ -1,21 +1,7 @@
git.ailur.dev/ailur/datatracker v1.0.0 h1:zJ0HppqiGEUkpwPVtKDGdHryUkTjnQvP2y+kFcA1gD0=
git.ailur.dev/ailur/datatracker v1.0.0/go.mod h1:0WE5ozzsgckCbIrKJRav+7iOhikl3B9XGHuJ8LCnRQE=
git.ailur.dev/ailur/fg-library/v2 v2.0.1 h1:ltPYXf/Om0hnMD8gr1K5bkYrfHqKPSbb0hxa0wtTnZ0=
git.ailur.dev/ailur/fg-library/v2 v2.0.1/go.mod h1:1jYbWhabGcIwp7CkhHqvRwC8eP+nHv5BrXPe9NX2HE8=
git.ailur.dev/ailur/fg-library/v3 v3.5.0 h1:BGDlS4nQ2PyZWNU4gH3eckVqhZUFIM/zKIj/HXx8RmA=
git.ailur.dev/ailur/fg-library/v3 v3.5.0/go.mod h1:ArNsafpqES2JuxQM5aM+bNe0FwHLIsL6pbjpiWvDwGs=
git.ailur.dev/ailur/fg-library/v3 v3.5.1 h1:9QH1myeXhGIlkihzYnH5jdgnD8UUStWC7aVWWq81hUU=
git.ailur.dev/ailur/fg-library/v3 v3.5.1/go.mod h1:ArNsafpqES2JuxQM5aM+bNe0FwHLIsL6pbjpiWvDwGs=
git.ailur.dev/ailur/fg-library/v3 v3.5.2 h1:rGvZSvmWPRMDGcM7ORMEAR2bd6QJx8vUKdki1SjRkoE=
git.ailur.dev/ailur/fg-library/v3 v3.5.2/go.mod h1:ArNsafpqES2JuxQM5aM+bNe0FwHLIsL6pbjpiWvDwGs=
git.ailur.dev/ailur/fg-library/v3 v3.6.2 h1:PNJKxpvbel2iDeB9+/rpYRyMoim6JjRHOXPYFYky7Ng=
git.ailur.dev/ailur/fg-library/v3 v3.6.2/go.mod h1:ArNsafpqES2JuxQM5aM+bNe0FwHLIsL6pbjpiWvDwGs=
git.ailur.dev/ailur/fg-nucleus-library v1.1.0 h1:D0eWwdlaw4IiOwz96MiRwHIdU/VIwiHUCeO00HkzzsU=
git.ailur.dev/ailur/fg-nucleus-library v1.1.0/go.mod h1:CHuOSByCmookwkcpjJBiinHEF27+IA70BhVtnR2cAhA=
git.ailur.dev/ailur/fg-nucleus-library v1.1.1 h1:IRpAQqgikeT2FyhVbhe16GyIxuTsf1Xq8oLqeUplgHk=
git.ailur.dev/ailur/fg-nucleus-library v1.1.1/go.mod h1:stxiTyMv3Fa7GzpyLbBUh3ahlb7110p0NnCl8ZTjwBs=
git.ailur.dev/ailur/fg-nucleus-library v1.1.2 h1:MXn0BorA8TV46Ig+4C96RU0NpFqrsGNbuw2QCc/7K6Q=
git.ailur.dev/ailur/fg-nucleus-library v1.1.2/go.mod h1:stxiTyMv3Fa7GzpyLbBUh3ahlb7110p0NnCl8ZTjwBs=
git.ailur.dev/ailur/fg-nucleus-library v1.2.2 h1:JbclmxGSoL+ByGZAl0W6PqWRoyBBGTrKrizWDJ7rdI0=
git.ailur.dev/ailur/fg-nucleus-library v1.2.2/go.mod h1:stxiTyMv3Fa7GzpyLbBUh3ahlb7110p0NnCl8ZTjwBs=
git.ailur.dev/ailur/pow v1.0.3 h1:LjLSol4ax+M+SoajVjbBoDjfmjH6pKu3fDka7bl2KGY=
git.ailur.dev/ailur/pow v1.0.3/go.mod h1:ClAmIdHQ/N9wTq5S4YWhQ5d9CPUBcEjVuOkT07zBdJ4=
github.com/CAFxX/httpcompression v0.0.9 h1:0ue2X8dOLEpxTm8tt+OdHcgA+gbDge0OqFQWGKSqgrg=
@ -31,16 +17,16 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/go-chi/chi/v5 v5.2.0 h1:Aj1EtB0qR2Rdo2dG4O94RIU35w2lvQSj6BRA4+qwFL0=
github.com/go-chi/chi/v5 v5.2.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8=
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o=
github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=
github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/brotli/go/cbrotli v0.0.0-20230829110029-ed738e842d2f h1:jopqB+UTSdJGEJT8tEqYyE29zN91fi2827oLET8tl7k=
@ -48,8 +34,8 @@ github.com/google/brotli/go/cbrotli v0.0.0-20230829110029-ed738e842d2f/go.mod h1
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@ -85,14 +71,14 @@ github.com/valyala/gozstd v1.20.1 h1:xPnnnvjmaDDitMFfDxmQ4vpx0+3CdTg2o3lALvXTU/g
github.com/valyala/gozstd v1.20.1/go.mod h1:y5Ew47GLlP37EkTB+B4s7r6A5rdaeB7ftbl9zoYiIPQ=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=

21
main.go
View file

@ -1,9 +1,8 @@
package main
import (
library "git.ailur.dev/ailur/fg-library/v3"
"errors"
library "git.ailur.dev/ailur/fg-library/v3"
"io"
"log"
"mime"
@ -393,7 +392,17 @@ func newFileServer(root string, directoryListing bool, path string) http.Handler
}
}
file, err := os.Open(filepath.Join(root, filepath.FromSlash(r.URL.Path)))
absolutePath, err := filepath.Abs(filepath.Join(root, filepath.FromSlash(r.URL.Path)))
if err != nil {
serverError(w, 500)
}
if !strings.HasPrefix(absolutePath, root) {
serverError(w, 403)
return
}
file, err := os.Open(absolutePath)
if err != nil {
serverError(w, 500)
return
@ -561,6 +570,12 @@ func svInit(message library.InterServiceMessage) {
return
}
_, err = pluginConn.Exec("PRAGMA journal_mode=WAL")
if err != nil {
message.Respond(library.InternalError, err, dummyInfo)
return
}
db = library.Database{
DB: pluginConn,
DBType: library.Sqlite,

View file

@ -266,10 +266,6 @@ func Main(information *library.ServiceInitializationInformation) {
if err != nil {
logFunc(err.Error(), 3, information)
}
_, err = mem.Exec("DROP TABLE IF EXISTS challengeResponse")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the sessions table
_, err = mem.Exec("CREATE TABLE sessions (id BLOB NOT NULL, session TEXT NOT NULL, device TEXT NOT NULL DEFAULT '?')")
if err != nil {
@ -285,11 +281,6 @@ func Main(information *library.ServiceInitializationInformation) {
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the challenge-response table
_, err = mem.Exec("CREATE TABLE challengeResponse (challenge TEXT NOT NULL UNIQUE, userId BLOB NOT NULL, expires INTEGER NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Set up the signing keys
// Check if the global table has the keys
@ -632,30 +623,6 @@ func Main(information *library.ServiceInitializationInformation) {
})
router.Post("/api/loginChallenge", func(w http.ResponseWriter, r *http.Request) {
type login struct {
Username string `json:"username"`
}
var data login
err = json.NewDecoder(r.Body).Decode(&data)
if err != nil {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JSON"}, information)
return
}
// Get the id for the user
var userId []byte
err = conn.DB.QueryRow("SELECT id FROM users WHERE username = $1", data.Username).Scan(&userId)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
renderJSON(401, w, map[string]interface{}{"error": "Invalid username"}, information)
} else {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "12"}, information)
logFunc(err.Error(), 2, information)
}
return
}
// Generate a new challenge
challenge, err := randomChars(512)
if err != nil {
@ -664,22 +631,27 @@ func Main(information *library.ServiceInitializationInformation) {
return
}
// Insert the challenge with one minute expiration
_, err = mem.Exec("INSERT INTO challengeResponse (challenge, userId, expires) VALUES (?, ?, ?)", challenge, userId, time.Now().Unix()+60)
// Issue a new JWT token with the challenge
token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims{
"challenge": challenge,
"exp": time.Now().Add(time.Second * 20).Unix(),
})
tokenString, err := token.SignedString(privateKey)
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "53"}, information)
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "51"}, information)
logFunc(err.Error(), 2, information)
return
}
// Return the challenge
renderJSON(200, w, map[string]interface{}{"challenge": challenge}, information)
renderJSON(200, w, map[string]interface{}{"challenge": challenge, "verifier": tokenString}, information)
})
router.Post("/api/login", func(w http.ResponseWriter, r *http.Request) {
type login struct {
Username string `json:"username"`
Signature string `json:"signature"`
Verifier string `json:"verifier"`
}
var data login
@ -691,8 +663,8 @@ func Main(information *library.ServiceInitializationInformation) {
// Try to select the user
var userId []byte
var publicKey []byte
err = conn.DB.QueryRow("SELECT id, publicKey FROM users WHERE username = $1", data.Username).Scan(&userId, &publicKey)
var userPublicKey []byte
err = conn.DB.QueryRow("SELECT id, publicKey FROM users WHERE username = $1", data.Username).Scan(&userId, &userPublicKey)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
renderJSON(401, w, map[string]interface{}{"error": "Invalid username"}, information)
@ -711,33 +683,43 @@ func Main(information *library.ServiceInitializationInformation) {
}
// Verify the challenge
// Select the current challenge from the database
var challenge string
err = mem.QueryRow("SELECT challenge FROM challengeResponse WHERE userId = ?", userId).Scan(&challenge)
token, err := jwt.Parse(data.Verifier, func(token *jwt.Token) (interface{}, error) {
return publicKey, nil
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
renderJSON(401, w, map[string]interface{}{"error": "Invalid challenge"}, information)
} else {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "52"}, information)
logFunc(err.Error(), 2, information)
}
renderJSON(401, w, map[string]interface{}{"error": "Invalid verifier"}, information)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
renderJSON(401, w, map[string]interface{}{"error": "Invalid verifier: no claims"}, information)
return
}
expired, err := claims.GetExpirationTime()
if err != nil {
renderJSON(401, w, map[string]interface{}{"error": "Invalid verifier: no expiry"}, information)
return
}
if expired.Before(time.Now()) {
renderJSON(401, w, map[string]interface{}{"error": "Expired verifier"}, information)
return
}
challenge, ok := claims["challenge"].(string)
if !ok {
renderJSON(401, w, map[string]interface{}{"error": "Invalid verifier: no challenge"}, information)
return
}
// Check if the challenge is correct by verifying the signature
if !ed25519.Verify(publicKey, []byte(challenge), signature) {
if !ed25519.Verify(userPublicKey, []byte(challenge), signature) {
renderJSON(401, w, map[string]interface{}{"error": "Invalid signature"}, information)
return
}
// Delete the challenge
_, err = mem.Exec("DELETE FROM challengeResponse WHERE userId = ?", userId)
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "53"}, information)
logFunc(err.Error(), 2, information)
return
}
// Create a new session
// We want the session token to be somewhat legible, so we use randomChars
// As a trade-off for this, we use a longer session token
@ -1573,17 +1555,7 @@ func Main(information *library.ServiceInitializationInformation) {
if err != nil {
logFunc(err.Error(), 1, information)
} else {
affected, err := mem.Exec("DELETE FROM challengeResponse WHERE expires < ?", time.Now().Unix())
if err != nil {
logFunc(err.Error(), 1, information)
} else {
affectedCount2, err := affected.RowsAffected()
if err != nil {
logFunc(err.Error(), 1, information)
} else {
logFunc("Cleanup complete, deleted "+strconv.FormatInt(affectedCount+affectedCount2, 10)+" entries", 0, information)
}
}
logFunc("Cleanup complete, deleted "+strconv.FormatInt(affectedCount, 10)+" entries", 0, information)
}
}
}

View file

@ -192,6 +192,7 @@ func main() {
signupBody := map[string]interface{}{
"username": username,
"signature": base64.StdEncoding.EncodeToString(signature),
"verifier": responseMap["verifier"].(string),
}
// Marshal the body

View file

@ -3,6 +3,7 @@ package main
import (
library "git.ailur.dev/ailur/fg-library/v3"
nucleusLibrary "git.ailur.dev/ailur/fg-nucleus-library"
"io"
"bytes"
"os"
@ -28,7 +29,6 @@ var ServiceInformation = library.Service{
}
var (
conn library.Database
loggerService = uuid.MustParse("00000000-0000-0000-0000-000000000002")
)
@ -49,7 +49,7 @@ func respondError(message library.InterServiceMessage, err error, information *l
message.Respond(errCode, err, information)
}
func checkUserExists(userID uuid.UUID) bool {
func checkUserExists(userID uuid.UUID, conn library.Database) bool {
// Check if a user exists in the database
var userCheck []byte
err := conn.DB.QueryRow("SELECT id FROM users WHERE id = $1", userID[:]).Scan(&userCheck)
@ -65,10 +65,10 @@ func checkUserExists(userID uuid.UUID) bool {
}
// addQuota can be used with a negative quota to remove quota from a user
func addQuota(information *library.ServiceInitializationInformation, message library.InterServiceMessage) {
func addQuota(information *library.ServiceInitializationInformation, message library.InterServiceMessage, conn library.Database) {
// Add more quota to a user
userID := message.Message.(nucleusLibrary.Quota).User
if checkUserExists(userID) {
if checkUserExists(userID, conn) {
_, err := conn.DB.Exec("UPDATE users SET quota = quota + $1 WHERE id = $2", message.Message.(nucleusLibrary.Quota).Bytes, message.Message.(nucleusLibrary.Quota).User)
if err != nil {
respondError(message, err, information, true)
@ -85,16 +85,16 @@ func addQuota(information *library.ServiceInitializationInformation, message lib
}
// And so does addReserved
func addReserved(information *library.ServiceInitializationInformation, message library.InterServiceMessage) {
func addReserved(information *library.ServiceInitializationInformation, message library.InterServiceMessage, conn library.Database) {
// Add more reserved space to a user
userID := message.Message.(nucleusLibrary.Quota).User
if checkUserExists(userID) {
if checkUserExists(userID, conn) {
// Check if the user has enough space
quota, err := getQuota(userID)
quota, err := getQuota(information, userID, conn)
if err != nil {
respondError(message, err, information, true)
}
used, err := getUsed(userID, information)
used, err := getUsed(userID, information, conn)
if err != nil {
respondError(message, err, information, true)
}
@ -122,17 +122,25 @@ func addReserved(information *library.ServiceInitializationInformation, message
message.Respond(library.Success, nil, information)
}
func getQuota(userID uuid.UUID) (int64, error) {
func getQuota(information *library.ServiceInitializationInformation, userID uuid.UUID, conn library.Database) (int64, error) {
// Get the quota for a user
var quota int64
err := conn.DB.QueryRow("SELECT quota FROM users WHERE id = $1", userID[:]).Scan(&quota)
if err != nil {
return 0, err
if errors.Is(err, sql.ErrNoRows) {
_, err := conn.DB.Exec("INSERT INTO users (id, quota, reserved) VALUES ($1, $2, 0)", userID[:], int64(information.Configuration["defaultQuota"].(int)))
if err != nil {
return 0, err
}
return int64(information.Configuration["defaultQuota"].(int)), nil
} else {
return 0, err
}
}
return quota, nil
}
func getUsed(userID uuid.UUID, information *library.ServiceInitializationInformation) (int64, error) {
func getUsed(userID uuid.UUID, information *library.ServiceInitializationInformation, conn library.Database) (int64, error) {
// Get the used space for a user by first getting the reserved space from file storage
_, err := os.Stat(filepath.Join(information.Configuration["path"].(string), userID.String()))
if os.IsNotExist(err) {
@ -161,13 +169,21 @@ func getUsed(userID uuid.UUID, information *library.ServiceInitializationInforma
var reserved int64
err = conn.DB.QueryRow("SELECT reserved FROM users WHERE id = $1", userID[:]).Scan(&reserved)
if err != nil {
return 0, err
if errors.Is(err, sql.ErrNoRows) {
_, err := conn.DB.Exec("INSERT INTO users (id, quota, reserved) VALUES ($1, $2, 0)", userID[:], int64(information.Configuration["defaultQuota"].(int)))
if err != nil {
return 0, err
}
return 0, nil
} else {
return 0, err
}
}
return used + reserved, nil
}
func modifyFile(information *library.ServiceInitializationInformation, message library.InterServiceMessage) {
func modifyFile(information *library.ServiceInitializationInformation, message library.InterServiceMessage, conn library.Database) {
// Check if the file already exists
path := filepath.Join(information.Configuration["path"].(string), message.Message.(nucleusLibrary.File).User.String(), message.Message.(nucleusLibrary.File).Name)
@ -185,15 +201,15 @@ func modifyFile(information *library.ServiceInitializationInformation, message l
}
// Check if the user has enough space
quota, err := getQuota(message.Message.(nucleusLibrary.File).User)
quota, err := getQuota(information, message.Message.(nucleusLibrary.File).User, conn)
if err != nil {
respondError(message, err, information, true)
}
used, err := getUsed(message.Message.(nucleusLibrary.File).User, information)
used, err := getUsed(message.Message.(nucleusLibrary.File).User, information, conn)
if err != nil {
respondError(message, err, information, true)
}
if used+int64(len(message.Message.(nucleusLibrary.File).Bytes)) > quota {
if used+message.Message.(nucleusLibrary.File).Reader.N > quota {
respondError(message, errors.New("insufficient storage"), information, false)
return
}
@ -205,7 +221,7 @@ func modifyFile(information *library.ServiceInitializationInformation, message l
}
// Write the file
_, err = file.Write(message.Message.(nucleusLibrary.File).Bytes)
_, err = io.Copy(file, message.Message.(nucleusLibrary.File).Reader)
if err != nil {
respondError(message, err, information, true)
}
@ -226,6 +242,7 @@ func getFile(information *library.ServiceInitializationInformation, message libr
_, err := os.Stat(path)
if os.IsNotExist(err) {
println("file not found: " + path)
respondError(message, errors.New("file not found"), information, false)
return
}
@ -262,20 +279,20 @@ func deleteFile(information *library.ServiceInitializationInformation, message l
}
// processInterServiceMessages listens for incoming messages and processes them
func processInterServiceMessages(information *library.ServiceInitializationInformation) {
func processInterServiceMessages(information *library.ServiceInitializationInformation, conn library.Database) {
// Listen for incoming messages
for {
message := information.AcceptMessage()
switch message.MessageType {
case 1:
// Add quota
addQuota(information, message)
addQuota(information, message, conn)
case 2:
// Add reserved
addReserved(information, message)
addReserved(information, message, conn)
case 3:
// Modify file
modifyFile(information, message)
modifyFile(information, message, conn)
case 4:
// Get file
getFile(information, message)
@ -312,5 +329,5 @@ func Main(information *library.ServiceInitializationInformation) {
}
// Listen for incoming messages
go processInterServiceMessages(information)
go processInterServiceMessages(information, conn)
}