Compare commits

...

22 Commits

Author SHA1 Message Date
b2bcbb3301 Fix cors 2026-02-01 17:16:15 +01:00
bd18c978e1 flake: update vendor hash 2026-01-24 23:45:02 +01:00
03fd7b6ac7 Allow CORS from frontend 2026-01-24 23:27:07 +01:00
648fe10e10 Add comments 2026-01-24 20:50:36 +01:00
c7644f7df8 Disable register functionality 2026-01-24 20:50:29 +01:00
94671c4ed4 Make sure config directory exists 2026-01-24 20:00:25 +01:00
7f52f27085 Add docker deploy to flake 2026-01-24 19:43:26 +01:00
dc6654ee93 Make config directory configurable 2026-01-24 19:43:11 +01:00
de94315bd9 Improve library sync, add more config values 2026-01-24 19:00:22 +01:00
1c26770db0 Use config from .env and update api 2026-01-24 18:09:24 +01:00
1e02e659ab Make flake compiling work 2026-01-23 22:53:08 +01:00
ee733911d3 Fix variable name 2026-01-23 22:47:21 +01:00
948bffa88b Improve gitignore 2026-01-23 22:44:35 +01:00
13078993d4 Improve composer management 2026-01-23 22:42:33 +01:00
6ed4dec4f0 Simplify user management 2026-01-23 22:37:36 +01:00
16ac84eaf9 Add dockerfile 2026-01-23 22:34:50 +01:00
0a18e19e88 Add library sync functionality 2026-01-23 22:33:01 +01:00
5141bfe673 Add composers 2026-01-23 21:55:21 +01:00
4540c0d880 Improve Sheet model 2026-01-23 21:37:18 +01:00
18188ac353 Move code to src folder 2026-01-23 20:29:47 +01:00
9481a1bc06 Add build output and db to gitignore 2026-01-23 20:13:32 +01:00
3f11bad8f6 First setup of a go server 2026-01-23 20:05:23 +01:00
23 changed files with 1140 additions and 146 deletions

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
sheetless.db
sheetless-server

18
.env.example Normal file
View File

@@ -0,0 +1,18 @@
# Server Configuration
SERVER_HOSTNAME=127.0.0.1
SERVER_PORT=8080
GIN_MODE=debug
# Security Configuration
JWT_SECRET=your-super-secret-jwt-key-here
# Sync Configuration
SYNC_INTERVAL_MINUTES=1
# Default Admin User Configuration
ADMIN_EMAIL=admin@admin.com
ADMIN_PASSWORD=sheetless
# Directories containing permanent data
SHEETS_DIRECTORY=/data/sheets
CONFIG_DIRECTORY=/data/config

1
.envrc
View File

@@ -1 +1,2 @@
use flake
dotenv .env

4
.gitignore vendored
View File

@@ -1 +1,5 @@
/.direnv/
sheetless-server
sheetless.db
/result
/.env

32
Dockerfile Normal file
View File

@@ -0,0 +1,32 @@
# Build stage
FROM golang:1.21-alpine AS builder
WORKDIR /app
# Copy go mod and sum files
COPY src/go.mod src/go.sum .
# Download dependencies
RUN go mod download
# Copy source code
COPY ./src/ .
# Build the application
RUN go build -o sheetless-server
# Runtime stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /app/
# Copy the binary from builder
COPY --from=builder /app .
# Expose port
EXPOSE 8080
# Run the application
CMD ["./sheetless-server"]

View File

@@ -6,32 +6,64 @@
flake-utils.url = "github:numtide/flake-utils";
};
outputs =
{
self,
nixpkgs,
flake-utils,
}:
outputs = {
nixpkgs,
flake-utils,
...
}:
flake-utils.lib.eachDefaultSystem (
system:
let
system: let
pkgs = nixpkgs.legacyPackages.${system};
in
{
deploy = pkgs.writeShellScriptBin "deploy" ''
set -e; set -o pipefail; set -x;
nix build .#docker
image=$((docker load < result) | sed -n '$s/^Loaded image: //p')
docker image tag "$image" harbor.julian-mutter.de/sheetless/sheetless-server:latest
docker push harbor.julian-mutter.de/sheetless/sheetless-server:latest
'';
in {
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
go
gopls
go-tools
deploy
];
};
# packages.default = pkgs.buildGoModule {
# pname = "sheetless-server";
# version = "0.1.0";
# src = ./.;
# vendorHash = ""; # Will be computed on first build
# };
packages = rec {
default = sheetless-server;
sheetless-server = pkgs.buildGoModule {
pname = "sheetless-server";
version = "0.1.0";
src = ./src;
vendorHash = "sha256-jJe13G5zoUCY2SD9ZerN+6ahc/qOJ3oAhDXJgIhyuvw=";
};
docker = pkgs.dockerTools.buildImage {
name = "sheetless-server";
tag = "latest";
copyToRoot = with pkgs; [
dockerTools.usrBinEnv
dockerTools.binSh
dockerTools.caCertificates
coreutils
sheetless-server
];
config = {
Cmd = ["/bin/sheetless-server"];
Expose = "8080";
};
created = "now";
};
};
}
);
}

40
go.mod
View File

@@ -1,40 +0,0 @@
module sheetless-server
go 1.21
require (
github.com/gin-gonic/gin v1.9.1
github.com/golang-jwt/jwt/v5 v5.0.0
golang.org/x/crypto v0.9.0
gorm.io/driver/sqlite v1.5.4
gorm.io/gorm v1.25.5
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

90
go.sum
View File

@@ -1,90 +0,0 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
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.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.4 h1:IqXwXi8M/ZlPzH/947tn5uik3aYQslP9BVveoax0nV0=
gorm.io/driver/sqlite v1.5.4/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4=
gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

70
src/config/config.go Normal file
View File

@@ -0,0 +1,70 @@
package config
import (
"os"
"strconv"
"time"
)
type Config struct {
Server struct {
Hostname string
Port string
Mode string // gin.Mode: debug, release, test
}
JWT struct {
Secret string
}
Sync struct {
Interval time.Duration
}
Admin struct {
Email string
Password string
}
SheetsDirectory string
ConfigDirectory string
}
var AppConfig *Config
func Load() {
cfg := &Config{}
// Server configuration
cfg.Server.Hostname = getEnv("SERVER_HOSTNAME", "127.0.0.1")
cfg.Server.Port = getEnv("SERVER_PORT", "8080")
cfg.Server.Mode = getEnv("GIN_MODE", "debug")
// JWT configuration
cfg.JWT.Secret = getEnv("JWT_SECRET", "sheetless-default-jwt-secret-please-change")
// Sync configuration
syncMinutes := getEnvInt("SYNC_INTERVAL_MINUTES", 1)
cfg.Sync.Interval = time.Duration(syncMinutes) * time.Minute
// Admin configuration
cfg.Admin.Email = getEnv("ADMIN_EMAIL", "admin@admin.com")
cfg.Admin.Password = getEnv("ADMIN_PASSWORD", "sheetless")
cfg.SheetsDirectory = getEnv("SHEETS_DIRECTORY", "./sheets_directory")
cfg.ConfigDirectory = getEnv("CONFIG_DIRECTORY", "./config_directory")
AppConfig = cfg
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func getEnvInt(key string, defaultValue int) int {
if value := os.Getenv(key); value != "" {
if intValue, err := strconv.Atoi(value); err == nil {
return intValue
}
}
return defaultValue
}

View File

@@ -0,0 +1,74 @@
package database
import (
"log"
"path/filepath"
"sheetless-server/config"
"sheetless-server/models"
"golang.org/x/crypto/bcrypt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var DB *gorm.DB
func InitDatabase() {
var err error
databaseFile := filepath.Join(config.AppConfig.ConfigDirectory, "sheetless.db")
DB, err = gorm.Open(sqlite.Open(databaseFile), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
tables, err := DB.Migrator().GetTables()
if err != nil {
log.Fatal("Failed to list tables of database:", err)
}
isNewDatabase := len(tables) == 0
// Auto migrate the schema
err = DB.AutoMigrate(&models.User{}, &models.Sheet{}, &models.Composer{})
if err != nil {
log.Fatal("Failed to migrate database:", err)
}
if isNewDatabase {
createDefaultAdminUser()
}
log.Println("Database connected and migrated successfully")
}
func createDefaultAdminUser() {
// Check if admin user already exists
var existingUser models.User
err := DB.Where("email = ?", config.AppConfig.Admin.Email).First(&existingUser).Error
if err == nil {
// Admin user already exists, don't recreate
log.Printf("Admin user already exists: %s", config.AppConfig.Admin.Email)
return
}
// Hash the admin password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(config.AppConfig.Admin.Password), bcrypt.DefaultCost)
if err != nil {
log.Printf("Failed to hash admin password: %v", err)
return
}
// Create admin user
adminUser := models.User{
Username: "admin",
Email: config.AppConfig.Admin.Email,
Password: string(hashedPassword),
}
if err := DB.Create(&adminUser).Error; err != nil {
log.Printf("Failed to create admin user: %v", err)
return
}
log.Printf("Default admin user created with email: %s", config.AppConfig.Admin.Email)
}

44
src/go.mod Normal file
View File

@@ -0,0 +1,44 @@
module sheetless-server
go 1.23.0
require (
github.com/gin-contrib/cors v1.7.6
github.com/gin-gonic/gin v1.10.1
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/google/uuid v1.6.0
golang.org/x/crypto v0.39.0
gorm.io/driver/sqlite v1.5.4
gorm.io/gorm v1.25.5
)
require (
github.com/bytedance/sonic v1.13.3 // indirect
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.26.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
golang.org/x/arch v0.18.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

106
src/go.sum Normal file
View File

@@ -0,0 +1,106 @@
github.com/bytedance/sonic v1.13.3 h1:MS8gmaH16Gtirygw7jV91pDCN33NyMrPbN7qiYhEsF0=
github.com/bytedance/sonic v1.13.3/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
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.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
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/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
golang.org/x/arch v0.18.0 h1:WN9poc33zL4AzGxqf8VtpKUnGvMi8O9lhNyBMF/85qc=
golang.org/x/arch v0.18.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
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=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.4 h1:IqXwXi8M/ZlPzH/947tn5uik3aYQslP9BVveoax0nV0=
gorm.io/driver/sqlite v1.5.4/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4=
gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=

95
src/handlers/auth.go Normal file
View File

@@ -0,0 +1,95 @@
package handlers
import (
"net/http"
"sheetless-server/config"
"sheetless-server/database"
"sheetless-server/models"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
type RegisterRequest struct {
Username string `json:"username" binding:"required"`
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=6"`
}
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
func Register(c *gin.Context) {
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Check if user already exists
var existingUser models.User
if err := database.DB.Where("username = ? OR email = ?", req.Username, req.Email).First(&existingUser).Error; err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "User already exists"})
return
}
// Hash password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to hash password"})
return
}
// Create user
user := models.User{
Username: req.Username,
Email: req.Email,
Password: string(hashedPassword),
}
if err := database.DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "User created successfully"})
}
func Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Find user
var user models.User
if err := database.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
// Check password
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
// Generate JWT token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": user.ID,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, err := token.SignedString([]byte(config.AppConfig.JWT.Secret))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
return
}
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}

96
src/handlers/composers.go Normal file
View File

@@ -0,0 +1,96 @@
package handlers
import (
"errors"
"net/http"
"sheetless-server/database"
"sheetless-server/models"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func AddComposer(c *gin.Context) {
var req struct {
Name string `json:"name" binding:"required"`
Bio string `json:"bio"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
uuid, err := GenerateNonexistentComposerUuid()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Could not generate composer uuid"})
return
}
composer := models.Composer{
Uuid: *uuid,
Name: req.Name,
Bio: req.Bio,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := database.DB.Create(&composer).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create composer"})
return
}
c.JSON(http.StatusCreated, gin.H{
"message": "Composer created successfully",
"composer": composer,
})
}
func ListComposers(c *gin.Context) {
var composers []models.Composer
if err := database.DB.Find(&composers).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch composers"})
return
}
c.JSON(http.StatusOK, gin.H{"composers": composers})
}
func GetComposer(c *gin.Context) {
uuid, err := uuid.Parse(c.Param("uuid"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid composer ID"})
return
}
var composer models.Composer
if err := database.DB.First(&composer, uuid).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Composer not found"})
return
}
c.JSON(http.StatusOK, composer)
}
func GenerateNonexistentComposerUuid() (*uuid.UUID, error) {
for i := 0; i < 10; i++ {
uuid := uuid.New()
var exists bool
err := database.DB.Model(&models.Composer{}).
Select("count(*) > 0").
Where("uuid = ?", uuid).
Find(&exists).
Error
if err != nil {
return nil, err
}
if !exists {
return &uuid, nil
}
}
return nil, errors.New("Somehow unable to generate new uuid for sheet.")
}

179
src/handlers/sheets.go Normal file
View File

@@ -0,0 +1,179 @@
package handlers
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sheetless-server/config"
"sheetless-server/database"
"sheetless-server/models"
"sheetless-server/utils"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func UploadSheet(c *gin.Context) {
// Get form data
title := c.PostForm("title")
if title == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Title is required"})
return
}
composerUUIDStr := c.PostForm("composer_uuid")
if composerUUIDStr == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Composer UUID is required"})
return
}
composerUUID, err := uuid.Parse(composerUUIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid composer UUID"})
return
}
var composer models.Composer
if err := database.DB.First(&composer, composerUUID).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Composer not found"})
return
}
description := c.PostForm("description")
// Get uploaded file
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "File upload failed"})
return
}
defer file.Close()
// Validate file type (should be PDF)
if filepath.Ext(header.Filename) != ".pdf" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Only PDF files are allowed"})
return
}
// Generate unique filename
filename := fmt.Sprintf("%d%s", time.Now().Unix(), filepath.Ext(header.Filename))
filePath := filepath.Join(config.AppConfig.SheetsDirectory, filename)
// Save file
out, err := os.Create(filePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
// Get file size
fileInfo, err := out.Stat()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get file info"})
return
}
fileHash, err := utils.FileHashFromUpload(out)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed calculating hash"})
return
}
uuid, err := GenerateNonexistentSheetUuid()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed generating sheet uuid"})
return
}
// Create database record
sheet := models.Sheet{
Uuid: *uuid,
Title: title,
Description: description,
FilePath: filePath,
FileSize: fileInfo.Size(),
FileHash: fileHash,
ComposerUuid: composer.Uuid,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := database.DB.Create(&sheet).Error; err != nil {
// Clean up file if database insert fails
os.Remove(filePath)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save sheet metadata"})
return
}
c.JSON(http.StatusCreated, gin.H{
"message": "Sheet uploaded successfully",
"sheet": sheet,
})
}
func ListSheets(c *gin.Context) {
var sheets []models.Sheet
if err := database.DB.Preload("Composer").Find(&sheets).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch sheets"})
return
}
c.JSON(http.StatusOK, gin.H{"sheets": sheets})
}
func DownloadSheet(c *gin.Context) {
uuid, err := uuid.Parse(c.Param("uuid"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid sheet uuid"})
return
}
var sheet models.Sheet
if err := database.DB.First(&sheet, uuid).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Sheet not found"})
return
}
if _, err := os.Stat(sheet.FilePath); os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
return
}
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(sheet.FilePath)))
c.Header("Content-Type", "application/pdf")
c.File(sheet.FilePath)
}
func GenerateNonexistentSheetUuid() (*uuid.UUID, error) {
for i := 0; i < 10; i++ {
uuid := uuid.New()
var exists bool
err := database.DB.Model(&models.Sheet{}).
Select("count(*) > 0").
Where("uuid = ?", uuid).
Find(&exists).
Error
if err != nil {
return nil, err
}
if !exists {
return &uuid, nil
}
}
return nil, errors.New("Somehow unable to generate new uuid for sheet.")
}

73
src/main.go Normal file
View File

@@ -0,0 +1,73 @@
package main
import (
"log"
"os"
"sheetless-server/config"
"sheetless-server/database"
"sheetless-server/routes"
"sheetless-server/sync"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
config.Load()
if err := os.MkdirAll(config.AppConfig.SheetsDirectory, 0755); err != nil {
panic("Failed to create sheets directory: " + err.Error())
}
if err := os.MkdirAll(config.AppConfig.ConfigDirectory, 0755); err != nil {
panic("Failed to create config directory: " + err.Error())
}
gin.SetMode(config.AppConfig.Server.Mode)
database.InitDatabase()
// Start sync runner
go func() {
ticker := time.NewTicker(config.AppConfig.Sync.Interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := sync.SyncSheets(); err != nil {
log.Printf("Sync error: %v", err)
}
}
}
}()
router := gin.Default()
corsConfig := cors.DefaultConfig()
corsConfig.AllowOrigins = []string{"https://sheets.julian-mutter.de"}
corsConfig.AllowHeaders = []string{
"Origin",
"X-Requested-With",
"Content-Type",
"Accept",
"Authorization",
}
corsConfig.AllowMethods = []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
}
corsConfig.AllowCredentials = true
router.Use(cors.New(corsConfig))
routes.SetupRoutes(router)
log.Printf("Server starting on port %s...", config.AppConfig.Server.Port)
if err := router.Run(config.AppConfig.Server.Hostname + ":" + config.AppConfig.Server.Port); err != nil {
log.Fatal("Failed to start server:", err)
}
}

49
src/middleware/auth.go Normal file
View File

@@ -0,0 +1,49 @@
package middleware
import (
"net/http"
"sheetless-server/config"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
// Extract token from "Bearer <token>" format
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
c.Abort()
return
}
// Parse and validate token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(config.AppConfig.JWT.Secret), nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// Extract claims
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if userID, ok := claims["user_id"].(float64); ok {
c.Set("user_id", uint(userID))
}
}
c.Next()
}
}

17
src/models/composer.go Normal file
View File

@@ -0,0 +1,17 @@
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Composer struct {
Uuid uuid.UUID `json:"uuid" gorm:"type:uuid;primaryKey"`
Name string `json:"name" gorm:"not null"`
Bio string `json:"bio"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

22
src/models/sheet.go Normal file
View File

@@ -0,0 +1,22 @@
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Sheet struct {
Uuid uuid.UUID `json:"uuid" gorm:"type:uuid;primaryKey"`
Title string `json:"title" gorm:"not null"`
Description string `json:"description"`
FilePath string `json:"file_path" gorm:"not null"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
ComposerUuid uuid.UUID `json:"composer_uuid"`
Composer Composer `json:"composer" gorm:"foreignKey:ComposerUuid"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

17
src/models/user.go Normal file
View File

@@ -0,0 +1,17 @@
package models
import (
"time"
"gorm.io/gorm"
)
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
Username string `json:"username" gorm:"unique;not null"`
Email string `json:"email" gorm:"unique;not null"`
Password string `json:"-" gorm:"not null"` // Don't include in JSON responses
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

36
src/routes/routes.go Normal file
View File

@@ -0,0 +1,36 @@
package routes
import (
"sheetless-server/handlers"
"sheetless-server/middleware"
"github.com/gin-gonic/gin"
)
func SetupRoutes(r *gin.Engine) {
// Public routes
auth := r.Group("/auth")
{
// auth.POST("/register", handlers.Register)
auth.POST("/login", handlers.Login)
}
// Protected routes
api := r.Group("/api")
api.Use(middleware.AuthMiddleware())
{
sheets := api.Group("/sheets")
{
sheets.POST("/upload", handlers.UploadSheet)
sheets.GET("/list", handlers.ListSheets)
sheets.GET("/get/:uuid", handlers.DownloadSheet)
}
composers := api.Group("/composers")
{
composers.POST("/add", handlers.AddComposer)
composers.GET("/list", handlers.ListComposers)
composers.GET("/get/:uuid", handlers.GetComposer)
}
}
}

118
src/sync/sync.go Normal file
View File

@@ -0,0 +1,118 @@
package sync
import (
"log"
"os"
"path/filepath"
"sheetless-server/config"
"sheetless-server/database"
"sheetless-server/handlers"
"sheetless-server/models"
"sheetless-server/utils"
"strings"
"time"
)
// TODO: delete sheets
// TODO: if name is automatic, update when filename changed
func SyncSheets() error {
log.Println("Running library sync")
syncStartTime := time.Now()
// Get all sheets
var sheets []models.Sheet
if err := database.DB.Find(&sheets).Error; err != nil {
return err
}
// Maps
pathsInDb := make(map[string]*models.Sheet)
hashToSheets := make(map[string][]*models.Sheet)
for i := range sheets {
sheet := &sheets[i]
pathsInDb[sheet.FilePath] = sheet
hashToSheets[sheet.FileHash] = append(hashToSheets[sheet.FileHash], sheet)
}
numFilesWithNewHash := 0
numRenamedFiles := 0
numNewFiles := 0
// Walk sheets directory recursively for PDF files
err := filepath.Walk(config.AppConfig.SheetsDirectory, func(filePath string, info os.FileInfo, walkErr error) error {
if walkErr != nil {
return walkErr
}
// Skip directories and non-PDF files
if info.IsDir() || filepath.Ext(filePath) != ".pdf" {
return nil
}
hash, err := utils.FileHash(filePath)
if err != nil {
log.Printf("Error hashing file %s: %v", filePath, err)
return nil
}
existingSheet, exists := pathsInDb[filePath]
if exists {
if existingSheet.FileHash != hash {
// Case 1: File has been altered -> update hash
existingSheet.FileHash = hash
existingSheet.UpdatedAt = time.Now()
if err := database.DB.Save(existingSheet).Error; err != nil {
log.Printf("Error updating sheet hash for %s: %v", filePath, err)
} else {
numFilesWithNewHash++
}
}
} else {
sheetsWithHash, hasHash := hashToSheets[hash]
if hasHash {
for _, s := range sheetsWithHash {
if _, err := os.Stat(s.FilePath); os.IsNotExist(err) {
// Case 2: File has been renamed or moved -> update path
s.FilePath = filePath
s.UpdatedAt = time.Now()
if err := database.DB.Save(s).Error; err != nil {
log.Printf("Error updating sheet path for %s: %v", filePath, err)
} else {
numRenamedFiles++
}
break
}
}
} else {
// Case 3: New sheets file -> Add to database
uuid, err := handlers.GenerateNonexistentSheetUuid()
if err != nil {
log.Printf("Error generating uuid: %v", err)
return nil
}
newSheet := models.Sheet{
Uuid: *uuid,
Title: strings.TrimSuffix(filepath.Base(filePath), ".pdf"), // use filename as title
FilePath: filePath,
FileSize: info.Size(),
FileHash: hash,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := database.DB.Create(&newSheet).Error; err != nil {
log.Printf("Error creating new sheet for %s: %v", filePath, err)
} else {
numNewFiles++
}
}
}
return nil
})
if numFilesWithNewHash != 0 || numRenamedFiles != 0 || numNewFiles != 0 {
log.Printf("Library sync succesfully run.\nChanged hashes: %d, renamed files: %d, new files: %d", numFilesWithNewHash, numRenamedFiles, numNewFiles)
}
log.Printf("Sync took %s", time.Since(syncStartTime))
return err
}

39
src/utils/filehash.go Normal file
View File

@@ -0,0 +1,39 @@
package utils
import (
"encoding/binary"
"hash/fnv"
"io"
"mime/multipart"
"os"
)
func FileHashFromUpload(file multipart.File) (string, error) {
h := fnv.New64a()
if _, err := io.Copy(h, file); err != nil {
return "", err
}
return u64ToString(h.Sum64()), nil
}
func FileHash(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := fnv.New64a()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return u64ToString(h.Sum64()), nil
}
func u64ToString(x uint64) string {
var b [8]byte
binary.LittleEndian.PutUint64(b[:], x)
return string(b[:])
}