60 Commits

Author SHA1 Message Date
45072a0e37 bump: v0.0.11 -> v0.0.12 2025-04-16 03:32:37 -04:00
095c477745 feat: dockerhub action 2025-04-16 03:31:38 -04:00
a25ff41363 fix: workflow dispatch formatting 2025-04-16 02:55:42 -04:00
1b780af78d feat: update workflow dispatch 2025-04-16 02:54:15 -04:00
7d36ea5925 fix: weird npm cli bug 2025-04-16 02:51:36 -04:00
e38719c292 feat: update workflow 2025-04-16 02:40:37 -04:00
beef83e02e fix: break out linting into seperate steps 2025-04-16 01:46:49 -04:00
b98a53eed7 fix: use trevstack cachix 2025-04-16 01:20:31 -04:00
481758e33b feat: fix nix update command 2025-04-16 01:19:56 -04:00
a9506ab67b build(nix): updated nix hashes 2025-04-16 01:18:41 -04:00
967e2650ad feat: sqlc, nix formatting 2025-04-16 00:58:44 -04:00
32f85fd0be bump: v0.0.10 -> v0.0.11 2025-04-10 19:16:35 -04:00
f9772bce47 feat: migrations 2025-04-10 19:15:21 -04:00
1667b78a0a build(nix): updated nix hashes 2025-04-10 19:14:39 -04:00
b741e5f1a2 build(server): updated go dependencies 2025-04-10 19:13:34 -04:00
439adecf0e build(client): updated npm dependencies 2025-04-10 19:13:31 -04:00
e9c44cbc94 feat: bob 2025-04-10 00:59:28 -04:00
dfd6789aa9 build(nix): updated nix hashes 2025-04-10 00:13:56 -04:00
8d36962bef build(server): updated go dependencies 2025-04-10 00:08:42 -04:00
35a2f0a918 build(client): updated npm dependencies 2025-04-10 00:08:36 -04:00
dd0995b241 WIP: stuff 2025-04-05 14:27:36 -04:00
93bc18022a WIP: passkey auth 2025-03-23 14:33:25 -04:00
f05e745d05 feat: shallow routing 2025-03-19 03:25:58 -04:00
8b494430a5 fix: daterangepicker key 2025-03-19 02:20:39 -04:00
d2238bdf9b fix: daterangepicker key 2025-03-19 02:12:27 -04:00
dc3106b4a4 bump: v0.0.9 -> v0.0.10 2025-03-19 00:46:21 -04:00
bc0e8c55e3 revert: use npm ci 2025-03-19 00:43:10 -04:00
124ddc20df fix: use nix packages for linting 2025-03-19 00:35:56 -04:00
218da3aef8 build(nix): updated nix hashes 2025-03-19 00:35:35 -04:00
e18457bacd build(client): updated npm dependencies 2025-03-19 00:34:26 -04:00
afb85cec88 build(nix): updated nix hashes 2025-03-19 00:33:28 -04:00
4e96ee38ca build(client): updated npm dependencies 2025-03-19 00:32:16 -04:00
89129f3495 bump: v0.0.8 -> v0.0.9 2025-03-18 23:27:02 -04:00
f8fb729c03 fix: use cachix for release workflow as well 2025-03-18 23:22:47 -04:00
b906e614ba fix: use cachix because github cache sucks 2025-03-18 23:18:30 -04:00
645faf398e fix: rely entirely on nix packages 2025-03-18 22:53:05 -04:00
add5afb17c fix: use legaly peer deps? 2025-03-18 22:38:33 -04:00
ab4ccc3d46 build(nix): updated nix hashes 2025-03-18 22:35:51 -04:00
ed7489f53d build(client): updated npm dependencies 2025-03-18 22:34:36 -04:00
94366907d8 fix: install npm packages before linting 2025-03-18 22:32:02 -04:00
ef11ac81a3 feat: lint workflow 2025-03-18 22:26:01 -04:00
73e7c563e0 bump: v0.0.7 -> v0.0.8 2025-03-18 22:14:11 -04:00
cd3da0aa8f feat: go caching 2025-03-18 22:12:56 -04:00
6706330252 bump: v0.0.6 -> v0.0.7 2025-03-18 22:07:05 -04:00
2b03164307 feat: workflow caching 2025-03-18 22:05:36 -04:00
0ffc1cd7f9 bump: v0.0.5 -> v0.0.6 2025-03-18 21:53:16 -04:00
c418792653 fix: select all build files 2025-03-18 21:52:00 -04:00
8956317197 bump: v0.0.4 -> v0.0.5 2025-03-18 21:42:25 -04:00
2361602b62 fix: use different release action 2025-03-18 21:40:43 -04:00
eba0067e1e bump: 0.0.3 -> 0.0.4 2025-03-18 21:25:42 -04:00
8d78f79fe2 fix: use nix develop in build action 2025-03-18 21:24:19 -04:00
5328e5b4a1 bump: 0.0.2 -> 0.0.3 2025-03-18 21:23:13 -04:00
81855d079f feat: release workflow 2025-03-18 21:21:16 -04:00
e857a14fd7 fix: add git dep 2025-03-18 19:25:18 -04:00
5e5a2cbaaa refactor: seperate default from trevstack in nix packages 2025-03-18 19:13:15 -04:00
267d293927 feat: linting 2025-03-18 19:02:50 -04:00
d8de02f789 refactor: move handlers into versioned dirs 2025-03-18 18:25:37 -04:00
be0981f7b7 feat: auth redirect 2025-03-18 17:46:54 -04:00
86b74e0ebc fix: conditional client build 2025-03-18 17:41:29 -04:00
21cd91156c fix: select dropdown transition 2025-03-18 17:05:21 -04:00
100 changed files with 3900 additions and 2436 deletions

View File

@ -1,13 +1,14 @@
.direnv
.env
build
result
/docker-compose.*
/result
/.direnv/
/build/
# Client
/client/node_modules
/client/.svelte-kit
/client/node_modules/
/client/.svelte-kit/
# Server
/server/client
/server/tmp
/server/internal/handlers/client/client
/server/client/
/server/tmp/
/server/build/

1
.envrc
View File

@ -1 +1,2 @@
use flake
watch_file .scripts/*

54
.github/workflows/lint.yaml vendored Normal file
View File

@ -0,0 +1,54 @@
name: Lint Workflow
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Nix
uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
- name: Use Cachix
uses: cachix/cachix-action@v16
with:
name: trevstack
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
- name: Install NPM Packages
working-directory: ./client
run: npm i && npm ci # https://github.com/npm/cli/issues/6787#issuecomment-2128344748
- uses: nicknovitski/nix-develop@v1
- run: npx prettier --check .
working-directory: ./client
- run: npx eslint .
working-directory: ./client
- run: npx svelte-check
working-directory: ./client
- run: revive -config revive.toml -set_exit_status ./...
working-directory: ./server
- run: sqlfluff lint
working-directory: ./server
- run: buf lint
- run: nix fmt -- flake.nix --check
- run: nix flake check --all-systems

76
.github/workflows/release.yaml vendored Normal file
View File

@ -0,0 +1,76 @@
name: Release Workflow
on:
push:
tags:
- '*'
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Nix
uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
- name: Use Cachix
uses: cachix/cachix-action@v16
with:
name: trevstack
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
- name: Build
run: nix develop --command trevstack-build
- name: Create Release
uses: softprops/action-gh-release@v2
with:
files: |-
build/**
# https://docs.docker.com/build/ci/github-actions/manage-tags-labels/
package:
runs-on: ubuntu-latest
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
# list of Docker images to use as base name for tags
images: |
spotdemo4/trevstack
# generate Docker tags based on the following events/attributes
tags: |
type=schedule
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=sha
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

39
.github/workflows/update.yaml vendored Normal file
View File

@ -0,0 +1,39 @@
name: Update Workflow
on:
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
update:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Nix
uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
- name: Use Cachix
uses: cachix/cachix-action@v16
with:
name: trevstack
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
- name: Install NPM Packages
working-directory: ./client
run: npm i && npm ci # https://github.com/npm/cli/issues/6787#issuecomment-2128344748
- name: Update
run: nix develop --command trevstack-update
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
delete-branch: true
title: Bump deps

16
.gitignore vendored
View File

@ -1,13 +1,5 @@
.direnv
.env
build
result
# Client
/client/node_modules
/client/.svelte-kit
# Server
/server/client
/server/tmp
/server/internal/handlers/client/client
/docker-compose.*
/result
/.direnv/
/build/

24
.scripts/build.sh Executable file
View File

@ -0,0 +1,24 @@
#!/usr/bin/env bash
git_root=$(git rev-parse --show-toplevel)
url=$(git config --get remote.origin.url)
name=$(basename -s .git "${url}")
git_version=$(git describe --tags --abbrev=0)
version=${git_version#v}
echo "building client"
cd "${git_root}"
nix build .#trevstack-client
cp -a result/. server/client
chmod -R u+w server/client
echo "building server"
cd "${git_root}/server"
echo "Building ${name}-windows-amd64-${version}.exe"
GOOS=windows GOARCH=amd64 go build -o "./build/${name}-windows-amd64-${version}.exe" .
echo "Building ${name}-linux-amd64-${version}"
GOOS=linux GOARCH=amd64 go build -o "./build/${name}-linux-amd64-${version}" .
echo "Building ${name}-linux-amd64-${version}"
GOOS=linux GOARCH=arm64 go build -o "./build/${name}-linux-arm64-${version}" .
echo "Building ${name}-linux-arm-${version}"
GOOS=linux GOARCH=arm go build -o "./build/${name}-linux-arm-${version}" .

22
.scripts/bump.sh Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env bash
git_root=$(git rev-parse --show-toplevel)
git_version=$(git describe --tags --abbrev=0)
version=${git_version#v}
next_version=$(echo "${version}" | awk -F. -v OFS=. '{$NF += 1 ; print}')
echo "bumping client"
cd "${git_root}/client"
npm version "${next_version}"
git add package-lock.json
git add package.json
echo "bumping nix"
cd "${git_root}"
nix-update --flake --version "${next_version}" default
git add flake.nix
git commit -m "bump: v${version} -> v${next_version}"
git push origin main
git tag -a "v${next_version}" -m "bump: v${version} -> v${next_version}"
git push origin "v${next_version}"

23
.scripts/lint.sh Executable file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env bash
git_root=$(git rev-parse --show-toplevel)
echo "linting client"
cd "${git_root}/client"
npx prettier --check .
npx eslint .
npx svelte-check
echo "linting server"
cd "${git_root}/server"
revive -config revive.toml -set_exit_status ./...
sqlfluff lint
echo "linting protobuf"
cd "${git_root}"
buf lint
echo "linting nix"
cd "${git_root}"
nix fmt -- flake.nix --check
nix flake check --all-systems

35
.scripts/update.sh Executable file
View File

@ -0,0 +1,35 @@
#!/usr/bin/env bash
git_root=$(git rev-parse --show-toplevel)
updated=false
echo "updating client"
cd "${git_root}/client"
npm update --save
if ! git diff --exit-code package.json package-lock.json; then
git add package-lock.json
git add package.json
git commit -m "build(client): updated npm dependencies"
updated=true
fi
echo "updating server"
cd "${git_root}/server"
go get -u
go mod tidy
if ! git diff --exit-code go.mod go.sum; then
git add go.mod
git add go.sum
git commit -m "build(go): updated go dependencies"
updated=true
fi
if [ "${updated}" = true ]; then
echo "updating nix"
cd "${git_root}"
nix-update --flake --version=skip --subpackage trevstack-client trevstack
git add flake.nix
git commit -m "build(nix): updated nix hashes"
else
echo "nothing to update"
fi

79
.treli.yaml Normal file
View File

@ -0,0 +1,79 @@
apps:
buf:
color: "#cba6f7"
exts:
- proto
onstart: buf lint
onchange: buf lint && buf generate
eslint:
color: "#fab387"
dir: client
exts:
- js
- ts
- svelte
onstart: npx eslint .
onchange: npx eslint .
golang:
color: "#89dceb"
dir: server
exts:
- go
onstart: go build -o ./tmp/app -tags dev && ./tmp/app
onchange: go build -o ./tmp/app -tags dev && ./tmp/app
nix:
color: "#74c7ec"
exts:
- nix
onstart: nix fmt
onchange: nix fmt
prettier:
color: "#fab387"
dir: client
exts:
- js
- ts
- svelte
onstart: npx prettier --check .
onchange: npx prettier --check . || npx prettier --write .
revive:
color: "#89dceb"
dir: server
exts:
- go
onstart: revive -config revive.toml -set_exit_status ./...
onchange: revive -config revive.toml -set_exit_status ./...
sqlc:
color: "#a6e3a1"
dir: server
exts:
- sql
onstart: sqlc vet
onchange: sqlc vet && sqlc generate
sqlfluff:
color: "#a6e3a1"
dir: server/db
exts:
- sql
onstart: sqlfluff lint
onchange: sqlfluff lint
svelte:
color: "#fab387"
dir: client
exts:
- svelte
onstart: npx svelte-check
onchange: npx svelte-check
vite:
color: "#fab387"
dir: client
onstart: npx vite dev

7
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"go.lintTool": "revive",
"go.lintFlags": [
"--config=server/revive.toml"
],
"sqlfluff.config": "server/db/.sqlfluff",
}

View File

@ -4,24 +4,24 @@ managed:
enabled: true
override:
- file_option: go_package_prefix
value: github.com/spotdemo4/trevstack/server/internal/services
value: github.com/spotdemo4/trevstack/server/internal/connect
plugins:
- local: protoc-gen-go
out: server/internal/services
out: server/internal/connect
opt: paths=source_relative
- local: protoc-gen-connect-go
out: server/internal/services
out: server/internal/connect
opt: paths=source_relative
- local: protoc-gen-es
out: client/src/lib/services
out: client/src/lib/connect
opt: target=ts
- local: protoc-gen-connect-openapi
out: client/static/openapi
strategy: all
opt:
- base=base.openapi.yaml
- base=openapi.base.yaml
- path=openapi.yaml

2
client/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/node_modules/
/.svelte-kit/

View File

@ -2,3 +2,14 @@
package-lock.json
pnpm-lock.yaml
yarn.lock
# Build output
build
.svelte-kit
node_modules
# Static
static
# Generated
src/lib/connect

View File

@ -3,10 +3,7 @@
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": [
"prettier-plugin-svelte",
"prettier-plugin-tailwindcss"
],
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [
{
"files": "*.svelte",

View File

@ -6,7 +6,7 @@ import globals from 'globals';
import { fileURLToPath } from 'node:url';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
const gitignorePath = fileURLToPath(new URL('./.prettierignore', import.meta.url));
export default ts.config(
includeIgnoreFile(gitignorePath),

1217
client/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{
"name": "trevstack",
"private": true,
"version": "0.0.2",
"version": "0.0.12",
"type": "module",
"scripts": {
"dev": "vite dev",
@ -16,31 +16,33 @@
"devDependencies": {
"@connectrpc/connect": "^2.0.2",
"@connectrpc/connect-web": "^2.0.2",
"@eslint/compat": "^1.2.7",
"@eslint/compat": "^1.2.8",
"@eslint/js": "^9.18.0",
"@lucide/svelte": "^0.479.0",
"@scalar/api-reference": "^1.28.5",
"@scalar/api-reference": "^1.28.19",
"@simplewebauthn/browser": "^13.1.0",
"@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/kit": "^2.20.1",
"@sveltejs/kit": "^2.20.7",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"@tailwindcss/vite": "^4.0.14",
"bits-ui": "^1.3.13",
"@tailwindcss/vite": "^4.1.4",
"bits-ui": "^1.3.19",
"cbor2": "^1.12.0",
"clsx": "^2.1.1",
"eslint": "^9.22.0",
"eslint-config-prettier": "^10.1.1",
"eslint-plugin-svelte": "^3.3.2",
"eslint": "^9.24.0",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-svelte": "^3.5.1",
"globals": "^16.0.0",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"svelte": "^5.23.2",
"svelte-check": "^4.1.5",
"svelte": "^5.27.0",
"svelte-check": "^4.1.6",
"svelte-sonner": "^0.3.28",
"tailwind-merge": "^3.0.2",
"tailwind-merge": "^3.2.0",
"tailwindcss": "^4.0.13",
"tw-animate-css": "^1.2.3",
"typescript": "^5.8.2",
"typescript-eslint": "^8.26.1",
"vite": "^6.2.2"
"tw-animate-css": "^1.2.5",
"typescript": "^5.8.3",
"typescript-eslint": "^8.30.1",
"vite": "^6.2.6"
}
}

View File

@ -1,24 +1,24 @@
@import "tailwindcss";
@import "tw-animate-css";
@import 'tailwindcss';
@import 'tw-animate-css';
@theme {
--color-crust: #11111b;
--color-mantle: #181825;
--color-base: #1e1e2e;
--color-crust: #11111b;
--color-mantle: #181825;
--color-base: #1e1e2e;
--color-surface-0: #313244;
--color-surface-1: #45475a;
--color-surface-2: #585b70;
--color-surface-0: #313244;
--color-surface-1: #45475a;
--color-surface-2: #585b70;
--color-overlay-0: #6c7086;
--color-overlay-1: #7f849c;
--color-overlay-2: #9399b2;
--color-overlay-0: #6c7086;
--color-overlay-1: #7f849c;
--color-overlay-2: #9399b2;
--color-subtext-0: #a6adc8;
--color-subtext-1: #bac2de;
--color-subtext-0: #a6adc8;
--color-subtext-1: #bac2de;
--color-text: #cdd6f4;
--color-text: #cdd6f4;
--color-sky: #89dceb;
--color-red: #f38ba8;
}
--color-sky: #89dceb;
--color-red: #f38ba8;
}

View File

@ -8,7 +8,7 @@
<title>TrevStack</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="tap" class="min-h-screen bg-base text-text">
<body data-sveltekit-preload-data="tap" class="bg-base text-text min-h-screen">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@ -12,16 +12,16 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file item/v1/item.proto.
*/
export const file_item_v1_item: GenFile = /*@__PURE__*/
fileDesc("ChJpdGVtL3YxL2l0ZW0ucHJvdG8SB2l0ZW0udjEinAEKBEl0ZW0SDwoCaWQYASABKA1IAIgBARIMCgRuYW1lGAIgASgJEhMKC2Rlc2NyaXB0aW9uGAMgASgJEg0KBXByaWNlGAQgASgCEhAKCHF1YW50aXR5GAUgASgNEi4KBWFkZGVkGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEgBiAEBQgUKA19pZEIICgZfYWRkZWQiHAoOR2V0SXRlbVJlcXVlc3QSCgoCaWQYASABKA0iLgoPR2V0SXRlbVJlc3BvbnNlEhsKBGl0ZW0YASABKAsyDS5pdGVtLnYxLkl0ZW0i3wEKD0dldEl0ZW1zUmVxdWVzdBIuCgVzdGFydBgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBIAIgBARIsCgNlbmQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wSAGIAQESEwoGZmlsdGVyGAMgASgJSAKIAQESEgoFbGltaXQYBCABKA1IA4gBARITCgZvZmZzZXQYBSABKA1IBIgBAUIICgZfc3RhcnRCBgoEX2VuZEIJCgdfZmlsdGVyQggKBl9saW1pdEIJCgdfb2Zmc2V0Ij8KEEdldEl0ZW1zUmVzcG9uc2USHAoFaXRlbXMYASADKAsyDS5pdGVtLnYxLkl0ZW0SDQoFY291bnQYAiABKAQiMAoRQ3JlYXRlSXRlbVJlcXVlc3QSGwoEaXRlbRgBIAEoCzINLml0ZW0udjEuSXRlbSIxChJDcmVhdGVJdGVtUmVzcG9uc2USGwoEaXRlbRgBIAEoCzINLml0ZW0udjEuSXRlbSIwChFVcGRhdGVJdGVtUmVxdWVzdBIbCgRpdGVtGAEgASgLMg0uaXRlbS52MS5JdGVtIjEKElVwZGF0ZUl0ZW1SZXNwb25zZRIbCgRpdGVtGAEgASgLMg0uaXRlbS52MS5JdGVtIh8KEURlbGV0ZUl0ZW1SZXF1ZXN0EgoKAmlkGAEgASgNIhQKEkRlbGV0ZUl0ZW1SZXNwb25zZTLrAgoLSXRlbVNlcnZpY2USPgoHR2V0SXRlbRIXLml0ZW0udjEuR2V0SXRlbVJlcXVlc3QaGC5pdGVtLnYxLkdldEl0ZW1SZXNwb25zZSIAEkEKCEdldEl0ZW1zEhguaXRlbS52MS5HZXRJdGVtc1JlcXVlc3QaGS5pdGVtLnYxLkdldEl0ZW1zUmVzcG9uc2UiABJHCgpDcmVhdGVJdGVtEhouaXRlbS52MS5DcmVhdGVJdGVtUmVxdWVzdBobLml0ZW0udjEuQ3JlYXRlSXRlbVJlc3BvbnNlIgASRwoKVXBkYXRlSXRlbRIaLml0ZW0udjEuVXBkYXRlSXRlbVJlcXVlc3QaGy5pdGVtLnYxLlVwZGF0ZUl0ZW1SZXNwb25zZSIAEkcKCkRlbGV0ZUl0ZW0SGi5pdGVtLnYxLkRlbGV0ZUl0ZW1SZXF1ZXN0GhsuaXRlbS52MS5EZWxldGVJdGVtUmVzcG9uc2UiAEKdAQoLY29tLml0ZW0udjFCCUl0ZW1Qcm90b1ABWkZnaXRodWIuY29tL3Nwb3RkZW1vNC90cmV2c3RhY2svc2VydmVyL2ludGVybmFsL3NlcnZpY2VzL2l0ZW0vdjE7aXRlbXYxogIDSVhYqgIHSXRlbS5WMcoCB0l0ZW1cVjHiAhNJdGVtXFYxXEdQQk1ldGFkYXRh6gIISXRlbTo6VjFiBnByb3RvMw", [file_google_protobuf_timestamp]);
fileDesc("ChJpdGVtL3YxL2l0ZW0ucHJvdG8SB2l0ZW0udjEigQEKBEl0ZW0SCgoCaWQYASABKAMSDAoEbmFtZRgCIAEoCRIpCgVhZGRlZBgDIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASEwoLZGVzY3JpcHRpb24YBCABKAkSDQoFcHJpY2UYBSABKAISEAoIcXVhbnRpdHkYBiABKAUiHAoOR2V0SXRlbVJlcXVlc3QSCgoCaWQYASABKAMiLgoPR2V0SXRlbVJlc3BvbnNlEhsKBGl0ZW0YASABKAsyDS5pdGVtLnYxLkl0ZW0i3wEKD0dldEl0ZW1zUmVxdWVzdBIuCgVzdGFydBgBIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBIAIgBARIsCgNlbmQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wSAGIAQESEwoGZmlsdGVyGAMgASgJSAKIAQESEgoFbGltaXQYBCABKAVIA4gBARITCgZvZmZzZXQYBSABKAVIBIgBAUIICgZfc3RhcnRCBgoEX2VuZEIJCgdfZmlsdGVyQggKBl9saW1pdEIJCgdfb2Zmc2V0Ij8KEEdldEl0ZW1zUmVzcG9uc2USHAoFaXRlbXMYASADKAsyDS5pdGVtLnYxLkl0ZW0SDQoFY291bnQYAiABKAMiVwoRQ3JlYXRlSXRlbVJlcXVlc3QSDAoEbmFtZRgBIAEoCRITCgtkZXNjcmlwdGlvbhgCIAEoCRINCgVwcmljZRgDIAEoAhIQCghxdWFudGl0eRgEIAEoBSJLChJDcmVhdGVJdGVtUmVzcG9uc2USCgoCaWQYASABKAMSKQoFYWRkZWQYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIqcBChFVcGRhdGVJdGVtUmVxdWVzdBIKCgJpZBgBIAEoAxIRCgRuYW1lGAIgASgJSACIAQESGAoLZGVzY3JpcHRpb24YAyABKAlIAYgBARISCgVwcmljZRgEIAEoAkgCiAEBEhUKCHF1YW50aXR5GAUgASgFSAOIAQFCBwoFX25hbWVCDgoMX2Rlc2NyaXB0aW9uQggKBl9wcmljZUILCglfcXVhbnRpdHkiFAoSVXBkYXRlSXRlbVJlc3BvbnNlIh8KEURlbGV0ZUl0ZW1SZXF1ZXN0EgoKAmlkGAEgASgDIhQKEkRlbGV0ZUl0ZW1SZXNwb25zZTLrAgoLSXRlbVNlcnZpY2USPgoHR2V0SXRlbRIXLml0ZW0udjEuR2V0SXRlbVJlcXVlc3QaGC5pdGVtLnYxLkdldEl0ZW1SZXNwb25zZSIAEkEKCEdldEl0ZW1zEhguaXRlbS52MS5HZXRJdGVtc1JlcXVlc3QaGS5pdGVtLnYxLkdldEl0ZW1zUmVzcG9uc2UiABJHCgpDcmVhdGVJdGVtEhouaXRlbS52MS5DcmVhdGVJdGVtUmVxdWVzdBobLml0ZW0udjEuQ3JlYXRlSXRlbVJlc3BvbnNlIgASRwoKVXBkYXRlSXRlbRIaLml0ZW0udjEuVXBkYXRlSXRlbVJlcXVlc3QaGy5pdGVtLnYxLlVwZGF0ZUl0ZW1SZXNwb25zZSIAEkcKCkRlbGV0ZUl0ZW0SGi5pdGVtLnYxLkRlbGV0ZUl0ZW1SZXF1ZXN0GhsuaXRlbS52MS5EZWxldGVJdGVtUmVzcG9uc2UiAEKcAQoLY29tLml0ZW0udjFCCUl0ZW1Qcm90b1ABWkVnaXRodWIuY29tL3Nwb3RkZW1vNC90cmV2c3RhY2svc2VydmVyL2ludGVybmFsL2Nvbm5lY3QvaXRlbS92MTtpdGVtdjGiAgNJWFiqAgdJdGVtLlYxygIHSXRlbVxWMeICE0l0ZW1cVjFcR1BCTWV0YWRhdGHqAghJdGVtOjpWMWIGcHJvdG8z", [file_google_protobuf_timestamp]);
/**
* @generated from message item.v1.Item
*/
export type Item = Message<"item.v1.Item"> & {
/**
* @generated from field: optional uint32 id = 1;
* @generated from field: int64 id = 1;
*/
id?: number;
id: bigint;
/**
* @generated from field: string name = 2;
@ -29,24 +29,24 @@ export type Item = Message<"item.v1.Item"> & {
name: string;
/**
* @generated from field: string description = 3;
* @generated from field: google.protobuf.Timestamp added = 3;
*/
added?: Timestamp;
/**
* @generated from field: string description = 4;
*/
description: string;
/**
* @generated from field: float price = 4;
* @generated from field: float price = 5;
*/
price: number;
/**
* @generated from field: uint32 quantity = 5;
* @generated from field: int32 quantity = 6;
*/
quantity: number;
/**
* @generated from field: optional google.protobuf.Timestamp added = 6;
*/
added?: Timestamp;
};
/**
@ -61,9 +61,9 @@ export const ItemSchema: GenMessage<Item> = /*@__PURE__*/
*/
export type GetItemRequest = Message<"item.v1.GetItemRequest"> & {
/**
* @generated from field: uint32 id = 1;
* @generated from field: int64 id = 1;
*/
id: number;
id: bigint;
};
/**
@ -110,12 +110,12 @@ export type GetItemsRequest = Message<"item.v1.GetItemsRequest"> & {
filter?: string;
/**
* @generated from field: optional uint32 limit = 4;
* @generated from field: optional int32 limit = 4;
*/
limit?: number;
/**
* @generated from field: optional uint32 offset = 5;
* @generated from field: optional int32 offset = 5;
*/
offset?: number;
};
@ -137,7 +137,7 @@ export type GetItemsResponse = Message<"item.v1.GetItemsResponse"> & {
items: Item[];
/**
* @generated from field: uint64 count = 2;
* @generated from field: int64 count = 2;
*/
count: bigint;
};
@ -154,9 +154,24 @@ export const GetItemsResponseSchema: GenMessage<GetItemsResponse> = /*@__PURE__*
*/
export type CreateItemRequest = Message<"item.v1.CreateItemRequest"> & {
/**
* @generated from field: item.v1.Item item = 1;
* @generated from field: string name = 1;
*/
item?: Item;
name: string;
/**
* @generated from field: string description = 2;
*/
description: string;
/**
* @generated from field: float price = 3;
*/
price: number;
/**
* @generated from field: int32 quantity = 4;
*/
quantity: number;
};
/**
@ -171,9 +186,14 @@ export const CreateItemRequestSchema: GenMessage<CreateItemRequest> = /*@__PURE_
*/
export type CreateItemResponse = Message<"item.v1.CreateItemResponse"> & {
/**
* @generated from field: item.v1.Item item = 1;
* @generated from field: int64 id = 1;
*/
item?: Item;
id: bigint;
/**
* @generated from field: google.protobuf.Timestamp added = 2;
*/
added?: Timestamp;
};
/**
@ -188,9 +208,29 @@ export const CreateItemResponseSchema: GenMessage<CreateItemResponse> = /*@__PUR
*/
export type UpdateItemRequest = Message<"item.v1.UpdateItemRequest"> & {
/**
* @generated from field: item.v1.Item item = 1;
* @generated from field: int64 id = 1;
*/
item?: Item;
id: bigint;
/**
* @generated from field: optional string name = 2;
*/
name?: string;
/**
* @generated from field: optional string description = 3;
*/
description?: string;
/**
* @generated from field: optional float price = 4;
*/
price?: number;
/**
* @generated from field: optional int32 quantity = 5;
*/
quantity?: number;
};
/**
@ -204,10 +244,6 @@ export const UpdateItemRequestSchema: GenMessage<UpdateItemRequest> = /*@__PURE_
* @generated from message item.v1.UpdateItemResponse
*/
export type UpdateItemResponse = Message<"item.v1.UpdateItemResponse"> & {
/**
* @generated from field: item.v1.Item item = 1;
*/
item?: Item;
};
/**
@ -222,9 +258,9 @@ export const UpdateItemResponseSchema: GenMessage<UpdateItemResponse> = /*@__PUR
*/
export type DeleteItemRequest = Message<"item.v1.DeleteItemRequest"> & {
/**
* @generated from field: uint32 id = 1;
* @generated from field: int64 id = 1;
*/
id: number;
id: bigint;
};
/**

View File

@ -10,7 +10,7 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file user/v1/auth.proto.
*/
export const file_user_v1_auth: GenFile = /*@__PURE__*/
fileDesc("ChJ1c2VyL3YxL2F1dGgucHJvdG8SB3VzZXIudjEiMgoMTG9naW5SZXF1ZXN0EhAKCHVzZXJuYW1lGAEgASgJEhAKCHBhc3N3b3JkGAIgASgJIh4KDUxvZ2luUmVzcG9uc2USDQoFdG9rZW4YASABKAkiTQoNU2lnblVwUmVxdWVzdBIQCgh1c2VybmFtZRgBIAEoCRIQCghwYXNzd29yZBgCIAEoCRIYChBjb25maXJtX3Bhc3N3b3JkGAMgASgJIhAKDlNpZ25VcFJlc3BvbnNlIg8KDUxvZ291dFJlcXVlc3QiEAoOTG9nb3V0UmVzcG9uc2UywQEKC0F1dGhTZXJ2aWNlEjgKBUxvZ2luEhUudXNlci52MS5Mb2dpblJlcXVlc3QaFi51c2VyLnYxLkxvZ2luUmVzcG9uc2UiABI7CgZTaWduVXASFi51c2VyLnYxLlNpZ25VcFJlcXVlc3QaFy51c2VyLnYxLlNpZ25VcFJlc3BvbnNlIgASOwoGTG9nb3V0EhYudXNlci52MS5Mb2dvdXRSZXF1ZXN0GhcudXNlci52MS5Mb2dvdXRSZXNwb25zZSIAQp0BCgtjb20udXNlci52MUIJQXV0aFByb3RvUAFaRmdpdGh1Yi5jb20vc3BvdGRlbW80L3RyZXZzdGFjay9zZXJ2ZXIvaW50ZXJuYWwvc2VydmljZXMvdXNlci92MTt1c2VydjGiAgNVWFiqAgdVc2VyLlYxygIHVXNlclxWMeICE1VzZXJcVjFcR1BCTWV0YWRhdGHqAghVc2VyOjpWMWIGcHJvdG8z");
fileDesc("ChJ1c2VyL3YxL2F1dGgucHJvdG8SB3VzZXIudjEiMgoMTG9naW5SZXF1ZXN0EhAKCHVzZXJuYW1lGAEgASgJEhAKCHBhc3N3b3JkGAIgASgJIh4KDUxvZ2luUmVzcG9uc2USDQoFdG9rZW4YASABKAkiTQoNU2lnblVwUmVxdWVzdBIQCgh1c2VybmFtZRgBIAEoCRIQCghwYXNzd29yZBgCIAEoCRIYChBjb25maXJtX3Bhc3N3b3JkGAMgASgJIhAKDlNpZ25VcFJlc3BvbnNlIg8KDUxvZ291dFJlcXVlc3QiEAoOTG9nb3V0UmVzcG9uc2UywQEKC0F1dGhTZXJ2aWNlEjgKBUxvZ2luEhUudXNlci52MS5Mb2dpblJlcXVlc3QaFi51c2VyLnYxLkxvZ2luUmVzcG9uc2UiABI7CgZTaWduVXASFi51c2VyLnYxLlNpZ25VcFJlcXVlc3QaFy51c2VyLnYxLlNpZ25VcFJlc3BvbnNlIgASOwoGTG9nb3V0EhYudXNlci52MS5Mb2dvdXRSZXF1ZXN0GhcudXNlci52MS5Mb2dvdXRSZXNwb25zZSIAQpwBCgtjb20udXNlci52MUIJQXV0aFByb3RvUAFaRWdpdGh1Yi5jb20vc3BvdGRlbW80L3RyZXZzdGFjay9zZXJ2ZXIvaW50ZXJuYWwvY29ubmVjdC91c2VyL3YxO3VzZXJ2MaICA1VYWKoCB1VzZXIuVjHKAgdVc2VyXFYx4gITVXNlclxWMVxHUEJNZXRhZGF0YeoCCFVzZXI6OlYxYgZwcm90bzM");
/**
* @generated from message user.v1.LoginRequest

View File

@ -10,16 +10,16 @@ import type { Message } from "@bufbuild/protobuf";
* Describes the file user/v1/user.proto.
*/
export const file_user_v1_user: GenFile = /*@__PURE__*/
fileDesc("ChJ1c2VyL3YxL3VzZXIucHJvdG8SB3VzZXIudjEiVgoEVXNlchIKCgJpZBgBIAEoDRIQCgh1c2VybmFtZRgCIAEoCRIcCg9wcm9maWxlX3BpY3R1cmUYAyABKAlIAIgBAUISChBfcHJvZmlsZV9waWN0dXJlIhAKDkdldFVzZXJSZXF1ZXN0Ii4KD0dldFVzZXJSZXNwb25zZRIbCgR1c2VyGAEgASgLMg0udXNlci52MS5Vc2VyIl0KFVVwZGF0ZVBhc3N3b3JkUmVxdWVzdBIUCgxvbGRfcGFzc3dvcmQYASABKAkSFAoMbmV3X3Bhc3N3b3JkGAIgASgJEhgKEGNvbmZpcm1fcGFzc3dvcmQYAyABKAkiNQoWVXBkYXRlUGFzc3dvcmRSZXNwb25zZRIbCgR1c2VyGAEgASgLMg0udXNlci52MS5Vc2VyIj4KEEdldEFQSUtleVJlcXVlc3QSEAoIcGFzc3dvcmQYASABKAkSGAoQY29uZmlybV9wYXNzd29yZBgCIAEoCSIgChFHZXRBUElLZXlSZXNwb25zZRILCgNrZXkYASABKAkiPgobVXBkYXRlUHJvZmlsZVBpY3R1cmVSZXF1ZXN0EhEKCWZpbGVfbmFtZRgBIAEoCRIMCgRkYXRhGAIgASgMIjsKHFVwZGF0ZVByb2ZpbGVQaWN0dXJlUmVzcG9uc2USGwoEdXNlchgBIAEoCzINLnVzZXIudjEuVXNlcjLPAgoLVXNlclNlcnZpY2USPgoHR2V0VXNlchIXLnVzZXIudjEuR2V0VXNlclJlcXVlc3QaGC51c2VyLnYxLkdldFVzZXJSZXNwb25zZSIAElMKDlVwZGF0ZVBhc3N3b3JkEh4udXNlci52MS5VcGRhdGVQYXNzd29yZFJlcXVlc3QaHy51c2VyLnYxLlVwZGF0ZVBhc3N3b3JkUmVzcG9uc2UiABJECglHZXRBUElLZXkSGS51c2VyLnYxLkdldEFQSUtleVJlcXVlc3QaGi51c2VyLnYxLkdldEFQSUtleVJlc3BvbnNlIgASZQoUVXBkYXRlUHJvZmlsZVBpY3R1cmUSJC51c2VyLnYxLlVwZGF0ZVByb2ZpbGVQaWN0dXJlUmVxdWVzdBolLnVzZXIudjEuVXBkYXRlUHJvZmlsZVBpY3R1cmVSZXNwb25zZSIAQp0BCgtjb20udXNlci52MUIJVXNlclByb3RvUAFaRmdpdGh1Yi5jb20vc3BvdGRlbW80L3RyZXZzdGFjay9zZXJ2ZXIvaW50ZXJuYWwvc2VydmljZXMvdXNlci92MTt1c2VydjGiAgNVWFiqAgdVc2VyLlYxygIHVXNlclxWMeICE1VzZXJcVjFcR1BCTWV0YWRhdGHqAghVc2VyOjpWMWIGcHJvdG8z");
fileDesc("ChJ1c2VyL3YxL3VzZXIucHJvdG8SB3VzZXIudjEiXAoEVXNlchIKCgJpZBgBIAEoAxIQCgh1c2VybmFtZRgCIAEoCRIfChJwcm9maWxlX3BpY3R1cmVfaWQYAyABKANIAIgBAUIVChNfcHJvZmlsZV9waWN0dXJlX2lkIhAKDkdldFVzZXJSZXF1ZXN0Ii4KD0dldFVzZXJSZXNwb25zZRIbCgR1c2VyGAEgASgLMg0udXNlci52MS5Vc2VyIl0KFVVwZGF0ZVBhc3N3b3JkUmVxdWVzdBIUCgxvbGRfcGFzc3dvcmQYASABKAkSFAoMbmV3X3Bhc3N3b3JkGAIgASgJEhgKEGNvbmZpcm1fcGFzc3dvcmQYAyABKAkiNQoWVXBkYXRlUGFzc3dvcmRSZXNwb25zZRIbCgR1c2VyGAEgASgLMg0udXNlci52MS5Vc2VyIj4KEEdldEFQSUtleVJlcXVlc3QSEAoIcGFzc3dvcmQYASABKAkSGAoQY29uZmlybV9wYXNzd29yZBgCIAEoCSIgChFHZXRBUElLZXlSZXNwb25zZRILCgNrZXkYASABKAkiPgobVXBkYXRlUHJvZmlsZVBpY3R1cmVSZXF1ZXN0EhEKCWZpbGVfbmFtZRgBIAEoCRIMCgRkYXRhGAIgASgMIjsKHFVwZGF0ZVByb2ZpbGVQaWN0dXJlUmVzcG9uc2USGwoEdXNlchgBIAEoCzINLnVzZXIudjEuVXNlcjLPAgoLVXNlclNlcnZpY2USPgoHR2V0VXNlchIXLnVzZXIudjEuR2V0VXNlclJlcXVlc3QaGC51c2VyLnYxLkdldFVzZXJSZXNwb25zZSIAElMKDlVwZGF0ZVBhc3N3b3JkEh4udXNlci52MS5VcGRhdGVQYXNzd29yZFJlcXVlc3QaHy51c2VyLnYxLlVwZGF0ZVBhc3N3b3JkUmVzcG9uc2UiABJECglHZXRBUElLZXkSGS51c2VyLnYxLkdldEFQSUtleVJlcXVlc3QaGi51c2VyLnYxLkdldEFQSUtleVJlc3BvbnNlIgASZQoUVXBkYXRlUHJvZmlsZVBpY3R1cmUSJC51c2VyLnYxLlVwZGF0ZVByb2ZpbGVQaWN0dXJlUmVxdWVzdBolLnVzZXIudjEuVXBkYXRlUHJvZmlsZVBpY3R1cmVSZXNwb25zZSIAQpwBCgtjb20udXNlci52MUIJVXNlclByb3RvUAFaRWdpdGh1Yi5jb20vc3BvdGRlbW80L3RyZXZzdGFjay9zZXJ2ZXIvaW50ZXJuYWwvY29ubmVjdC91c2VyL3YxO3VzZXJ2MaICA1VYWKoCB1VzZXIuVjHKAgdVc2VyXFYx4gITVXNlclxWMVxHUEJNZXRhZGF0YeoCCFVzZXI6OlYxYgZwcm90bzM");
/**
* @generated from message user.v1.User
*/
export type User = Message<"user.v1.User"> & {
/**
* @generated from field: uint32 id = 1;
* @generated from field: int64 id = 1;
*/
id: number;
id: bigint;
/**
* @generated from field: string username = 2;
@ -27,9 +27,9 @@ export type User = Message<"user.v1.User"> & {
username: string;
/**
* @generated from field: optional string profile_picture = 3;
* @generated from field: optional int64 profile_picture_id = 3;
*/
profilePicture?: string;
profilePictureId?: bigint;
};
/**

View File

@ -1 +0,0 @@
// place files you want to import through the `$lib` alias in this folder.

View File

@ -1,5 +1,5 @@
import type { User } from "./services/user/v1/user_pb"
import type { User } from './connect/user/v1/user_pb';
export let userState: { user: User | undefined } = $state({
export const userState: { user: User | undefined } = $state({
user: undefined
});
});

View File

@ -1,27 +1,27 @@
import { createConnectTransport } from "@connectrpc/connect-web"
import { Code, ConnectError, createClient, type Interceptor } from "@connectrpc/connect"
import { AuthService } from "$lib/services/user/v1/auth_pb";
import { UserService } from "$lib/services/user/v1/user_pb";
import { ItemService } from "$lib/services/item/v1/item_pb";
import { goto } from "$app/navigation";
import { createConnectTransport } from '@connectrpc/connect-web';
import { Code, ConnectError, createClient, type Interceptor } from '@connectrpc/connect';
import { AuthService } from '$lib/connect/user/v1/auth_pb';
import { UserService } from '$lib/connect/user/v1/user_pb';
import { ItemService } from '$lib/connect/item/v1/item_pb';
import { goto } from '$app/navigation';
const redirector: Interceptor = (next) => async (req) => {
try {
return await next(req);
} catch (e) {
const error = ConnectError.from(e);
if (error.code === Code.Unauthenticated) {
await goto('/auth');
}
throw e;
}
try {
return await next(req);
} catch (e) {
const error = ConnectError.from(e);
if (error.code === Code.Unauthenticated) {
await goto('/auth');
}
throw e;
}
};
const transport = createConnectTransport({
baseUrl: `${window.location.origin}/grpc`,
interceptors: [redirector],
baseUrl: `${window.location.origin}/grpc`,
interceptors: [redirector]
});
export const AuthClient = createClient(AuthService, transport);
export const UserClient = createClient(UserService, transport);
export const ItemClient = createClient(ItemService, transport);
export const ItemClient = createClient(ItemService, transport);

View File

@ -5,7 +5,7 @@
<Avatar.Root class="flex h-full w-full items-center justify-center">
<Avatar.Image
src={userState.user?.profilePicture}
src={userState.user?.profilePictureId ? '/file/' + userState.user.profilePictureId : null}
alt={`${userState.user?.username}'s avatar`}
class="rounded-full"
/>

View File

@ -1,9 +1,10 @@
<script lang="ts">
import { Button } from 'bits-ui';
import { cn } from '$lib/utils';
import type { MouseEventHandler } from 'svelte/elements';
import type { Snippet } from 'svelte';
type me = MouseEvent & { currentTarget: EventTarget & HTMLButtonElement };
let {
className,
type,
@ -12,7 +13,7 @@
}: {
className?: string;
type?: 'submit' | 'reset' | 'button' | null;
onclick?: () => MouseEventHandler<HTMLButtonElement> | null | undefined;
onclick?: (e: me) => void;
children?: Snippet<[]>;
} = $props();
</script>
@ -20,10 +21,12 @@
<Button.Root
{type}
class={cn(
'bg-sky text-crust flex justify-center items-center hover:brightness-120 focus:outline-sky w-fit cursor-pointer rounded p-2 px-4 text-sm font-medium transition-all focus:outline-2 focus:outline-offset-1',
'bg-sky text-crust focus:outline-sky flex w-fit cursor-pointer items-center justify-center rounded p-2 px-4 text-sm font-medium transition-all hover:brightness-120 focus:outline-2 focus:outline-offset-1',
className
)}
{onclick}
onclick={(e: me) => {
onclick?.(e);
}}
>
{@render children?.()}
</Button.Root>

View File

@ -42,22 +42,22 @@
<div
class="bg-mantle border-surface-0 hover:border-surface-2 flex items-center rounded border pl-2 text-sm drop-shadow-md transition-all"
>
<div class="grow flex items-center justify-center">
{#each ['start', 'end'] as const as type}
<div class="flex grow items-center justify-center">
{#each ['start', 'end'] as const as type (type)}
<DateRangePicker.Input {type}>
{#snippet children({ segments })}
{#each segments as { part, value }}
{#each segments as seg (seg)}
<div class="inline-block select-none">
{#if part === 'literal'}
<DateRangePicker.Segment {part} class="text-overlay-0 p-1">
{value}
{#if seg.part === 'literal'}
<DateRangePicker.Segment part={seg.part} class="text-overlay-0 p-1">
{seg.value}
</DateRangePicker.Segment>
{:else}
<DateRangePicker.Segment
{part}
part={seg.part}
class="aria-[valuetext=Empty]:text-overlay-0 hover:bg-surface-0 focus:bg-surface-0 focus:outline-sky rounded p-0.5 transition-all focus:outline focus:outline-offset-1"
>
{value}
{seg.value}
</DateRangePicker.Segment>
{/if}
</div>
@ -72,7 +72,7 @@
{/each}
</div>
<DateRangePicker.Trigger
class="text-overlay-2 hover:bg-surface-0 grow flex justify-center items-center focus:outline-sky ml-1 cursor-pointer p-2 transition-all focus:outline focus:outline-offset-1"
class="text-overlay-2 hover:bg-surface-0 focus:outline-sky ml-1 flex grow cursor-pointer items-center justify-center p-2 transition-all focus:outline focus:outline-offset-1"
>
<Calendar size="20" />
</DateRangePicker.Trigger>
@ -114,21 +114,21 @@
>
<ArrowLeft />
</DateRangePicker.PrevButton>
<DateRangePicker.Heading class="select-none font-medium" />
<DateRangePicker.Heading class="font-medium select-none" />
<DateRangePicker.NextButton
class="hover:bg-surface-0 inline-flex size-10 cursor-pointer items-center justify-center rounded transition-all active:scale-[0.98]"
>
<ArrowRight />
</DateRangePicker.NextButton>
</DateRangePicker.Header>
<div class="flex flex-col space-y-4 pt-4 sm:flex-row sm:space-x-4 sm:space-y-0">
{#each months as month}
<DateRangePicker.Grid class="w-full border-collapse select-none space-y-1">
<div class="flex flex-col space-y-4 pt-4 sm:flex-row sm:space-y-0 sm:space-x-4">
{#each months as month, i (i)}
<DateRangePicker.Grid class="w-full border-collapse space-y-1 select-none">
<DateRangePicker.GridHead>
<DateRangePicker.GridRow class="mb-1 flex w-full justify-between">
{#each weekdays as day}
{#each weekdays as day, i (i)}
<DateRangePicker.HeadCell
class="text-overlay-0 font-normal! w-10 rounded text-xs"
class="text-overlay-0 w-10 rounded text-xs font-normal!"
>
{day.slice(0, 2)}
</DateRangePicker.HeadCell>
@ -136,19 +136,19 @@
</DateRangePicker.GridRow>
</DateRangePicker.GridHead>
<DateRangePicker.GridBody>
{#each month.weeks as weekDates}
{#each month.weeks as weekDates, i (i)}
<DateRangePicker.GridRow class="flex w-full">
{#each weekDates as date}
{#each weekDates as date, i (i)}
<DateRangePicker.Cell
{date}
month={month.value}
class="p-0! relative m-0 size-10 overflow-visible text-center text-sm focus-within:relative focus-within:z-20"
class="relative m-0 size-10 overflow-visible p-0! text-center text-sm focus-within:relative focus-within:z-20"
>
<DateRangePicker.Day
class={'hover:border-sky focus-visible:ring-foreground! data-selected:rounded-none data-selection-end:rounded-r data-selection-start:rounded-l data-highlighted:bg-surface-0 data-selected:bg-surface-1 data-selection-end:bg-surface-2 data-selection-start:bg-surface-2 data-disabled:text-text/30 data-unavailable:text-overlay-0 data-disabled:pointer-events-none data-outside-month:pointer-events-none data-highlighted:rounded-none data-unavailable:line-through group relative inline-flex size-10 items-center justify-center overflow-visible whitespace-nowrap rounded border border-transparent bg-transparent p-0 text-sm font-normal transition-all'}
class="hover:border-sky focus-visible:ring-foreground! data-highlighted:bg-surface-0 data-selected:bg-surface-1 data-selection-end:bg-surface-2 data-selection-start:bg-surface-2 data-disabled:text-text/30 data-unavailable:text-overlay-0 group relative inline-flex size-10 items-center justify-center overflow-visible rounded border border-transparent bg-transparent p-0 text-sm font-normal whitespace-nowrap transition-all data-disabled:pointer-events-none data-highlighted:rounded-none data-outside-month:pointer-events-none data-selected:rounded-none data-selection-end:rounded-r data-selection-start:rounded-l data-unavailable:line-through"
>
<div
class="bg-sky group-data-selected:bg-background group-data-today:block absolute top-[5px] hidden size-1 rounded-full transition-all"
class="bg-sky group-data-selected:bg-background absolute top-[5px] hidden size-1 rounded-full transition-all group-data-today:block"
></div>
{date.day}
</DateRangePicker.Day>

View File

@ -2,7 +2,8 @@
import { X } from '@lucide/svelte';
import { Dialog } from 'bits-ui';
import { fade } from 'svelte/transition';
import type { Snippet } from 'svelte';
import { type Snippet } from 'svelte';
import { pushState } from '$app/navigation';
let {
trigger,
@ -17,7 +18,24 @@
} = $props();
</script>
<Dialog.Root bind:open>
<svelte:window
onpopstate={() => {
if (open) {
open = false;
}
}}
/>
<Dialog.Root
bind:open
onOpenChange={(e) => {
if (e) {
pushState('', '#modal');
} else {
history.back();
}
}}
>
<Dialog.Trigger>
{#snippet child({ props })}
{@render trigger(props)}
@ -48,7 +66,7 @@
}}
>
<div
class="bg-mantle border-surface-0 fixed inset-0 left-[50%] top-[50%] z-50 size-fit w-96 -translate-x-1/2 -translate-y-1/2 transform overflow-y-auto rounded-xl border pb-1 drop-shadow-md"
class="bg-mantle border-surface-0 fixed inset-0 top-[50%] left-[50%] z-50 size-fit w-96 -translate-x-1/2 -translate-y-1/2 transform overflow-y-auto rounded-xl border pb-1 drop-shadow-md"
>
<div class="border-surface-0 flex justify-between border-b p-2">
<h1 class="grow truncate p-1 text-center text-xl font-bold">

View File

@ -2,6 +2,8 @@
import { cn } from '$lib/utils';
import { ChevronLeft, ChevronRight } from '@lucide/svelte';
import { Pagination } from 'bits-ui';
import { pushState, replaceState } from '$app/navigation';
import { onMount, tick } from 'svelte';
let {
count = $bindable(),
@ -16,15 +18,36 @@
className?: string;
onchange?: (e: number) => void;
} = $props();
let page: number = $state(1);
onMount(async () => {
await tick();
replaceState('', `${page}`);
});
</script>
<svelte:window
onpopstate={(e) => {
const lastPage: number = Number(e.state['sveltekit:states']);
if (!isNaN(lastPage)) {
page = lastPage;
offset = (lastPage - 1) * limit;
window.scrollTo(0, 0);
onchange?.(lastPage);
}
}}
/>
{#key count && limit}
<Pagination.Root
{count}
bind:page
perPage={limit}
onPageChange={(e) => {
offset = (e - 1) * limit;
window.scrollTo(0, 0);
window.scrollTo(0, 0);
pushState('', `${e}`);
onchange?.(e);
}}
>
@ -38,11 +61,11 @@
<div class="flex items-center gap-2">
{#each pages as page (page.key)}
{#if page.type === 'ellipsis'}
<div class="select-none font-medium">...</div>
<div class="font-medium select-none">...</div>
{:else}
<Pagination.Page
{page}
class="hover:bg-surface-0 data-selected:bg-surface-0 data-selected:text-background inline-flex size-10 cursor-pointer select-none items-center justify-center rounded bg-transparent font-medium transition-all disabled:cursor-not-allowed disabled:opacity-50 hover:disabled:bg-transparent"
class="hover:bg-surface-0 data-selected:bg-surface-0 data-selected:text-background inline-flex size-10 cursor-pointer items-center justify-center rounded bg-transparent font-medium transition-all select-none disabled:cursor-not-allowed disabled:opacity-50 hover:disabled:bg-transparent"
>
{page.value}
</Pagination.Page>

View File

@ -2,19 +2,20 @@
import { cn } from '$lib/utils';
import { Check, ChevronsDown, ChevronsUp, ChevronsUpDown, X } from '@lucide/svelte';
import { Select } from 'bits-ui';
import { fade } from 'svelte/transition';
let {
value = $bindable('10'),
placeholder = 'Select an item',
items = [],
defaultValue = '',
defaultValue = '',
className,
onchange
}: {
value?: string;
placeholder?: string;
items: { value: string; label: string; disabled?: boolean }[];
defaultValue?: string;
defaultValue?: string;
className?: string;
onchange?: (e: string) => void;
} = $props();
@ -30,42 +31,53 @@
>
<Select.Root type="single" {items} bind:value onValueChange={onchange}>
<Select.Trigger
class="focus:outline-sky data-placeholder:text-overlay-0 gap-2 inline-flex grow cursor-pointer select-none items-center justify-between rounded-l py-2 pl-2 text-sm transition-colors focus:outline focus:outline-offset-1"
class="focus:outline-sky data-placeholder:text-overlay-0 inline-flex grow cursor-pointer items-center justify-between gap-2 rounded-l py-2 pl-2 text-sm transition-colors select-none focus:outline focus:outline-offset-1"
aria-label={placeholder}
>
{selectedLabel}
<ChevronsUpDown class="text-overlay-0" size="20" />
</Select.Trigger>
<Select.Portal>
<Select.Content
class="focus-override border-surface-0 bg-mantle shadow-popover data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 outline-hidden z-50 select-none rounded border p-1"
sideOffset={10}
>
<Select.ScrollUpButton class="flex w-full items-center justify-center">
<ChevronsUp size="20" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each items as item, i (i + item.value)}
<Select.Item
class="data-disabled:cursor-not-allowed data-highlighted:bg-surface-0 outline-hidden data-disabled:opacity-50 flex h-10 w-full cursor-pointer select-none items-center gap-4 rounded px-5 py-3 text-sm capitalize"
value={item.value}
label={item.label}
disabled={item.disabled}
>
{#snippet children({ selected })}
{item.label}
{#if selected}
<div class="ml-auto">
<Check size="20" />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton class="flex w-full items-center justify-center">
<ChevronsDown size="20" />
</Select.ScrollDownButton>
<Select.Content forceMount>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div
{...props}
class="border-surface-0 bg-mantle shadow-popover z-50 mt-1 rounded border p-1 outline-hidden select-none"
transition:fade={{
duration: 100
}}
>
<Select.ScrollUpButton class="flex w-full items-center justify-center">
<ChevronsUp size="20" />
</Select.ScrollUpButton>
<Select.Viewport class="p-1">
{#each items as item, i (i + item.value)}
<Select.Item
class="data-highlighted:bg-surface-0 flex h-10 w-full cursor-pointer items-center gap-4 rounded px-5 py-3 text-sm capitalize outline-hidden select-none data-disabled:cursor-not-allowed data-disabled:opacity-50"
value={item.value}
label={item.label}
disabled={item.disabled}
>
{#snippet children({ selected })}
{item.label}
{#if selected}
<div class="ml-auto">
<Check size="20" />
</div>
{/if}
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
<Select.ScrollDownButton class="flex w-full items-center justify-center">
<ChevronsDown size="20" />
</Select.ScrollDownButton>
</div>
</div>
{/if}
{/snippet}
</Select.Content>
</Select.Portal>
</Select.Root>
@ -74,7 +86,7 @@
type="button"
onclick={() => {
value = defaultValue;
onchange?.(value);
onchange?.(value);
}}
>
<X size="20" />

View File

@ -1,5 +1,5 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));

119
client/src/lib/webauthn.ts Normal file
View File

@ -0,0 +1,119 @@
import { decode } from 'cbor2';
import { page } from '$app/state';
interface CreateCredential extends Credential {
response: AuthenticatorAttestationResponse;
}
interface AttestationObject {
authData: Uint8Array;
fmt: string;
}
interface DecodedPublicKeyObject {
[key: number]: number | Uint8Array;
}
export async function createPasskey(username: string, userid: number, challenge: string) {
const challengeBuffer = Uint8Array.from(challenge, (c) => c.charCodeAt(0));
const idBuffer = Uint8Array.from(userid.toString(), (c) => c.charCodeAt(0));
const credential = (await navigator.credentials.create({
publicKey: {
challenge: challengeBuffer,
rp: { id: page.url.hostname, name: 'TrevStack' },
user: {
id: idBuffer,
name: username,
displayName: username
},
pubKeyCredParams: [
{
type: 'public-key',
alg: -7
},
{
type: 'public-key',
alg: -257
}
],
timeout: 60000,
attestation: 'none'
}
})) as CreateCredential | null;
if (!credential) {
throw new Error('Could not create passkey');
}
console.log(credential.id);
//console.log(credential.type);
const utf8Decoder = new TextDecoder('utf-8');
const decodedClientData = utf8Decoder.decode(credential.response.clientDataJSON);
const clientDataObj = JSON.parse(decodedClientData);
console.log(clientDataObj);
const attestationObject = new Uint8Array(credential.response.attestationObject);
const decodedAttestationObject = decode(attestationObject) as AttestationObject;
const { authData } = decodedAttestationObject;
// get the length of the credential ID
const dataView = new DataView(new ArrayBuffer(2));
const idLenBytes = authData.slice(53, 55);
idLenBytes.forEach((value, index) => dataView.setUint8(index, value));
const credentialIdLength = dataView.getUint16(0);
// get the credential ID
// const credentialId = authData.slice(55, 55 + credentialIdLength);
// get the public key object
const publicKeyBytes = authData.slice(55 + credentialIdLength);
console.log(publicKeyBytes);
// the publicKeyBytes are encoded again as CBOR
const publicKeyObject = new Uint8Array(publicKeyBytes.buffer);
const decodedPublicKeyObject = decode(publicKeyObject) as DecodedPublicKeyObject;
console.log(decodedPublicKeyObject);
return {
id: credential.id,
publicKey: publicKeyBytes,
algorithm: decodedPublicKeyObject[3]
};
}
interface GetCredential extends Credential {
response: AuthenticatorAssertionResponse;
}
export async function getPasskey(passkeyids: string[], challenge: string) {
const challengeBuffer = Uint8Array.from(challenge, (c) => c.charCodeAt(0));
const credential = (await navigator.credentials.get({
publicKey: {
challenge: challengeBuffer,
allowCredentials: passkeyids.map((passkeyid) => {
return {
id: Uint8Array.from(passkeyid, (c) => c.charCodeAt(0)),
type: 'public-key'
};
}),
timeout: 60000
}
})) as GetCredential | null;
if (!credential) {
throw new Error('Could not get passkey');
}
const signature = credential.response.signature;
return {
signature
};
}

View File

@ -98,14 +98,14 @@
>
<NavigationMenu.Root orientation="vertical">
<NavigationMenu.List
class="flex w-full flex-col gap-2 overflow-y-auto overflow-x-hidden p-2"
class="flex w-full flex-col gap-2 overflow-x-hidden overflow-y-auto p-2"
>
{#each menuItems as item}
{#each menuItems as item (item.name)}
{@const Icon = item.icon}
<NavigationMenu.Item>
<NavigationMenu.Link
class={cn(
'hover:bg-surface-0 flex select-none gap-2 whitespace-nowrap rounded-lg p-2 transition-all',
'hover:bg-surface-0 flex gap-2 rounded-lg p-2 whitespace-nowrap transition-all select-none',
page.url.pathname === item.href && 'bg-surface-0'
)}
href={item.href}
@ -126,7 +126,7 @@
<div class="border-surface-0 flex flex-col gap-2 border-t p-2">
<a
href="/settings"
class="hover:bg-surface-0 flex select-none items-center gap-2 rounded-lg p-2 transition-all"
class="hover:bg-surface-0 flex items-center gap-2 rounded-lg p-2 transition-all select-none"
onclick={() => {
if (sidebarOpen) {
sidebarOpen = false;
@ -138,7 +138,7 @@
</a>
<button
class="hover:bg-surface-0 flex w-full cursor-pointer items-center gap-2 whitespace-nowrap rounded-lg p-2 transition-all"
class="hover:bg-surface-0 flex w-full cursor-pointer items-center gap-2 rounded-lg p-2 whitespace-nowrap transition-all"
onclick={logout}
>
<LogOut size="20" />
@ -152,7 +152,7 @@
</Dialog.Portal>
</Dialog.Root>
<a href="/" class="flex select-none items-center gap-2 text-2xl font-bold tracking-wider">
<a href="/" class="flex items-center gap-2 text-2xl font-bold tracking-wider select-none">
TrevStack
<LayoutGrid />
</a>
@ -160,11 +160,11 @@
<NavigationMenu.Root class="hidden md:block">
<NavigationMenu.List class="flex gap-2">
{#each menuItems as item}
{#each menuItems as item (item.name)}
<NavigationMenu.Item>
<NavigationMenu.Link
class={cn(
'hover:bg-surface-0 flex select-none gap-2 rounded-lg p-1 px-2 transition-all',
'hover:bg-surface-0 flex gap-2 rounded-lg p-1 px-2 transition-all select-none',
page.url.pathname === item.href && 'bg-surface-0'
)}
href={item.href}
@ -179,7 +179,7 @@
<Popover.Root bind:open={popupOpen}>
<Popover.Trigger
class="outline-surface-2 hover:brightness-120 bg-text text-crust h-9 w-9 cursor-pointer rounded-full text-sm outline outline-offset-2 transition-all"
class="outline-surface-2 bg-text text-crust h-9 w-9 cursor-pointer rounded-full text-sm outline outline-offset-2 transition-all hover:brightness-120"
>
<Avatar />
</Popover.Trigger>

View File

@ -10,7 +10,7 @@
import Input from '$lib/ui/Input.svelte';
import Select from '$lib/ui/Select.svelte';
import { SvelteMap } from 'svelte/reactivity';
import type { Item } from '$lib/services/item/v1/item_pb';
import type { Item } from '$lib/connect/item/v1/item_pb';
import Pagination from '$lib/ui/Pagination.svelte';
// Config
@ -26,8 +26,8 @@
// Open
let addedOpen = $state(false);
let deletesOpen: SvelteMap<number, boolean> = new SvelteMap();
let editsOpen: SvelteMap<number, boolean> = new SvelteMap();
let deletesOpen: SvelteMap<bigint, boolean> = new SvelteMap();
let editsOpen: SvelteMap<bigint, boolean> = new SvelteMap();
async function getItems() {
return await ItemClient.getItems({
@ -50,12 +50,7 @@
</script>
<div class="mx-4 my-2 flex flex-wrap items-center justify-center gap-2">
<Input
bind:value={filter}
className="bg-mantle"
placeholder="Filter"
onchange={updateItems}
/>
<Input bind:value={filter} className="bg-mantle" placeholder="Filter" onchange={updateItems} />
<Select
items={[
{
@ -118,21 +113,17 @@
const quantity = formData.get('quantity')?.toString();
try {
const response = await ItemClient.updateItem({
item: {
id: item.id,
name: name,
description: description,
price: parseFloat(price ?? '0'),
quantity: parseInt(quantity ?? '0')
}
await ItemClient.updateItem({
id: item.id,
name: name,
description: description,
price: price ? parseFloat(price) : undefined,
quantity: quantity ? parseInt(quantity) : undefined
});
if (response.item && item.id) {
toast.success(`item "${name}" saved`);
editsOpen.set(item.id, false);
await updateItems();
}
toast.success(`item "${name}" saved`);
editsOpen.set(item.id, false);
await updateItems();
} catch (err) {
const error = ConnectError.from(err);
toast.error(error.rawMessage);
@ -238,7 +229,7 @@
<td class="w-8"></td>
</tr>
{:then items}
{#each items as item}
{#each items as item (item.id)}
<tr class="border-surface-0 border-b">
<td class="px-6 py-3">
{item.added ? timestampDate(item.added).toLocaleString() : ''}
@ -287,7 +278,7 @@
</div>
</div>
{:then items}
{#each items as item}
{#each items as item (item.id)}
<div
class="border-surface-0 bg-mantle flex w-full flex-wrap gap-6 rounded border p-5 drop-shadow-md"
>
@ -313,7 +304,7 @@
<span class="text-subtext-0 text-sm">Quantity</span>
<span class="truncate">{item.quantity}</span>
</div>
<div class="flex justify-end ml-auto gap-2">
<div class="ml-auto flex justify-end gap-2">
{@render editModal(item)}
{@render deleteModal(item)}
</div>
@ -322,7 +313,7 @@
{/await}
</div>
<div class="mx-4 mb-4 mt-2 flex justify-end sm:mt-1">
<div class="mx-4 mt-2 mb-4 flex justify-end sm:mt-1">
<Modal bind:open={addedOpen}>
{#snippet trigger(props)}
<Button {...props} className="bg-sky">
@ -346,21 +337,17 @@
const quantity = formData.get('quantity')?.toString();
try {
const response = await ItemClient.createItem({
item: {
name: name,
description: description,
price: parseFloat(price ?? '0'),
quantity: parseInt(quantity ?? '0')
}
await ItemClient.createItem({
name: name,
description: description,
price: parseFloat(price ?? '0'),
quantity: parseInt(quantity ?? '0')
});
if (response.item) {
form.reset();
toast.success(`item "${name}" added`);
addedOpen = false;
await updateItems();
}
form.reset();
toast.success(`item "${name}" added`);
addedOpen = false;
await updateItems();
} catch (err) {
const error = ConnectError.from(err);
toast.error(error.rawMessage);

View File

@ -17,7 +17,7 @@
<div class="m-auto flex w-96 flex-col gap-4 p-4">
<div class="flex items-center justify-center gap-4">
<div
class="outline-surface-2 bg-text text-crust h-9 w-9 select-none rounded-full text-sm outline outline-offset-2"
class="outline-surface-2 bg-text text-crust h-9 w-9 rounded-full text-sm outline outline-offset-2 select-none"
>
<Avatar />
</div>
@ -26,7 +26,7 @@
<Separator.Root class="bg-surface-0 h-px" />
<div class="flex justify-around gap-2">
<div class="flex flex-wrap justify-around gap-2">
<Modal>
{#snippet trigger(props)}
<Button {...props} className="bg-text">Generate API Key</Button>
@ -133,6 +133,15 @@
</form>
{/snippet}
</Modal>
<Button
className="bg-text"
onclick={async () => {
if (userState.user) {
//await createPasskey(userState.user.username, userState.user.id, "what");
}
}}>Register Device</Button
>
</div>
<form

View File

@ -5,10 +5,12 @@
let { children } = $props();
</script>
<Toaster toastOptions={{
classes: {
toast: '!bg-mantle !text-text !border-surface-0',
}
}} />
<Toaster
toastOptions={{
classes: {
toast: '!bg-mantle !text-text !border-surface-0'
}
}}
/>
{@render children()}

View File

@ -1,3 +1,3 @@
export const prerender = true;
export const ssr = false;
export const trailingSlash = 'always';
export const trailingSlash = 'always';

View File

@ -7,6 +7,7 @@
import { toast } from 'svelte-sonner';
import Button from '$lib/ui/Button.svelte';
import Input from '$lib/ui/Input.svelte';
import { page } from '$app/state';
let tab = $state('login');
</script>
@ -41,6 +42,7 @@
const formData = new FormData(e.target as HTMLFormElement);
const username = formData.get('login-username')?.toString();
const password = formData.get('login-password')?.toString();
const redir = page.url.searchParams.get('redir') || '/';
try {
const response = await AuthClient.login({
@ -49,7 +51,7 @@
});
if (response.token && username) {
goto('/');
goto(redir);
}
} catch (err) {
const error = ConnectError.from(err);
@ -103,11 +105,11 @@
</div>
<div class="flex flex-col gap-1">
<label for="signup-password" class="text-sm">Password</label>
<Input name="signup-password" />
<Input name="signup-password" type="password" />
</div>
<div class="flex flex-col gap-1">
<label for="signup-confirm-password" class="text-sm">Confirm Password</label>
<Input name="signup-confirm-password" />
<Input name="signup-confirm-password" type="password" />
</div>
<Button type="submit">Submit</Button>
</div>

View File

@ -5,76 +5,76 @@ import { build, files, version } from '$service-worker';
const CACHE = `cache-${version}`;
const ASSETS = [
...build, // the app itself
...files // everything in `static`
...build, // the app itself
...files // everything in `static`
];
self.addEventListener('install', (event) => {
// Create a new cache and add all files to it
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}
// Create a new cache and add all files to it
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}
event.waitUntil(addFilesToCache());
event.waitUntil(addFilesToCache());
});
self.addEventListener('activate', (event) => {
// Remove previous cached data from disk
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}
// Remove previous cached data from disk
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}
event.waitUntil(deleteOldCaches());
event.waitUntil(deleteOldCaches());
});
self.addEventListener('fetch', (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET') return;
// ignore POST requests etc
if (event.request.method !== 'GET') return;
async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE);
async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE);
// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
const response = await cache.match(url.pathname);
// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
const response = await cache.match(url.pathname);
if (response) {
return response;
}
}
if (response) {
return response;
}
}
// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);
// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);
// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
if (response.status === 200) {
cache.put(event.request, response.clone());
}
if (response.status === 200) {
cache.put(event.request, response.clone());
}
return response;
} catch (err) {
const response = await cache.match(event.request);
return response;
} catch (err) {
const response = await cache.match(event.request);
if (response) {
return response;
}
if (response) {
return response;
}
// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}
// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}
event.respondWith(respond());
});
event.respondWith(respond());
});

View File

@ -5,7 +5,7 @@
"display": "standalone",
"start_url": "/",
"background_color": "#181825",
"theme_color": "#89dceb",
"theme_color": "#11111b",
"icons": [
{
"src": "icon.png",

View File

@ -111,25 +111,45 @@ components:
item.v1.CreateItemRequest:
type: object
properties:
item:
title: item
$ref: '#/components/schemas/item.v1.Item'
name:
type: string
title: name
description:
type: string
title: description
price:
type: number
title: price
format: float
quantity:
type: integer
title: quantity
format: int32
title: CreateItemRequest
additionalProperties: false
item.v1.CreateItemResponse:
type: object
properties:
item:
title: item
$ref: '#/components/schemas/item.v1.Item'
id:
type:
- integer
- string
title: id
format: int64
added:
title: added
$ref: '#/components/schemas/google.protobuf.Timestamp'
title: CreateItemResponse
additionalProperties: false
item.v1.DeleteItemRequest:
type: object
properties:
id:
type: integer
type:
- integer
- string
title: id
format: int64
title: DeleteItemRequest
additionalProperties: false
item.v1.DeleteItemResponse:
@ -140,8 +160,11 @@ components:
type: object
properties:
id:
type: integer
type:
- integer
- string
title: id
format: int64
title: GetItemRequest
additionalProperties: false
item.v1.GetItemResponse:
@ -170,10 +193,12 @@ components:
limit:
type: integer
title: limit
format: int32
nullable: true
offset:
type: integer
title: offset
format: int32
nullable: true
title: GetItemsRequest
additionalProperties: false
@ -197,12 +222,17 @@ components:
type: object
properties:
id:
type: integer
type:
- integer
- string
title: id
nullable: true
format: int64
name:
type: string
title: name
added:
title: added
$ref: '#/components/schemas/google.protobuf.Timestamp'
description:
type: string
title: description
@ -213,26 +243,40 @@ components:
quantity:
type: integer
title: quantity
added:
title: added
nullable: true
$ref: '#/components/schemas/google.protobuf.Timestamp'
format: int32
title: Item
additionalProperties: false
item.v1.UpdateItemRequest:
type: object
properties:
item:
title: item
$ref: '#/components/schemas/item.v1.Item'
id:
type:
- integer
- string
title: id
format: int64
name:
type: string
title: name
nullable: true
description:
type: string
title: description
nullable: true
price:
type: number
title: price
format: float
nullable: true
quantity:
type: integer
title: quantity
format: int32
nullable: true
title: UpdateItemRequest
additionalProperties: false
item.v1.UpdateItemResponse:
type: object
properties:
item:
title: item
$ref: '#/components/schemas/item.v1.Item'
title: UpdateItemResponse
additionalProperties: false
connect-protocol-version:
@ -414,14 +458,20 @@ components:
type: object
properties:
id:
type: integer
type:
- integer
- string
title: id
format: int64
username:
type: string
title: username
profilePicture:
type: string
title: profile_picture
profilePictureId:
type:
- integer
- string
title: profile_picture_id
format: int64
nullable: true
title: User
additionalProperties: false

View File

@ -1,23 +1,20 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import tailwindcss from '@tailwindcss/vite'
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
tailwindcss(),
sveltekit()
],
plugins: [tailwindcss(), sveltekit()],
server: {
proxy: {
'/grpc': {
target: 'http://localhost:8080',
changeOrigin: true,
changeOrigin: true
},
'/file': {
target: 'http://localhost:8080',
changeOrigin: true,
},
changeOrigin: true
}
},
host: '0.0.0.0',
host: '0.0.0.0'
}
});

View File

@ -1,43 +0,0 @@
services:
trevstack:
container_name: trevstack
build:
context: .
ports:
- "${PORT}:${PORT}"
environment:
- DB_TYPE=postgres
- DB_USER=${DB_USER}
- DB_PASS=${DB_PASS}
- DB_HOST=trevstack-db
- DB_PORT=5432
- DB_NAME=${DB_NAME}
- PORT=${PORT}
- KEY=${KEY}
depends_on:
trevstack-db:
condition: service_healthy
links:
- trevstack-db
restart: unless-stopped
trevstack-db:
container_name: trevstack-db
image: postgres
environment:
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASS}
- POSTGRES_DB=${DB_NAME}
volumes:
- trevstackdata:/var/lib/postgresql/data
healthcheck:
test: "pg_isready -U postgres"
interval: 5s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
trevstackdata:
name: trevstackdata
external: true

84
flake.lock generated
View File

@ -1,50 +1,28 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"gitignore": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1709087332,
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "gitignore.nix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1741513245,
"narHash": "sha256-7rTAMNTY1xoBwz0h7ZMtEcd8LELk9R5TzBPoHuhNSCk=",
"lastModified": 1744463964,
"narHash": "sha256-LWqduOgLHCFxiTNYi3Uj5Lgz0SR+Xhw3kr/3Xd0GPTM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "e3e32b642a31e6714ec1b712de8c91a3352ce7e1",
"rev": "2631b0b7abcea6e640ce31cd78ea58910d31e650",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1743583204,
"narHash": "sha256-F7n4+KOIfWrwoQjXrL2wD9RhFYLs2/GGe/MQY1sSdlE=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "2c8d3f48d33929642c1c12cd243df4cc7d2ce434",
"type": "github"
},
"original": {
@ -56,23 +34,25 @@
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"gitignore": "gitignore",
"nixpkgs": "nixpkgs"
"nixpkgs": "nixpkgs",
"treli": "treli"
}
},
"systems": {
"treli": {
"inputs": {
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"lastModified": 1744776944,
"narHash": "sha256-wdmVDDyz6aZpFai2P0PBb2sMRBTgnaURylJw8wis6ks=",
"owner": "spotdemo4",
"repo": "treli",
"rev": "eefe10c1ba62a577592ff25e6e5b274215c1d8db",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"owner": "spotdemo4",
"repo": "treli",
"type": "github"
}
}

255
flake.nix
View File

@ -1,188 +1,115 @@
{
description = "A trevstack development environment";
description = "A template for trevstack";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
gitignore = {
url = "github:hercules-ci/gitignore.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
treli.url = "github:spotdemo4/treli";
};
outputs = { self, nixpkgs, flake-utils, gitignore }:
flake-utils.lib.eachDefaultSystem (system:
outputs = {
nixpkgs,
treli,
...
}: let
pname = "trevstack";
version = "0.0.12";
let
pname = "trevstack";
version = "0.0.2";
supportedSystems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forSystem = f:
nixpkgs.lib.genAttrs supportedSystems (
system:
f {
inherit system;
pkgs = import nixpkgs {
inherit system;
};
}
);
in {
devShells = forSystem ({pkgs, ...}: {
default = pkgs.mkShell {
packages = with pkgs;
[
git
nix-update
treli.packages."${system}".default
pkgs = import nixpkgs {
inherit system;
config.allowUnfree = true;
};
protoc-gen-connect-openapi = pkgs.buildGoModule {
name = "protoc-gen-connect-openapi";
src = pkgs.fetchFromGitHub {
owner = "sudorandom";
repo = "protoc-gen-connect-openapi";
rev = "v0.16.1";
sha256 = "sha256-3XBQCc9H9N/AZm/8J5bJRgBhVtoZKFvbdTB+glHxYdA=";
};
vendorHash = "sha256-CIiG/XhV8xxjYY0sZcSvIFcJ1Wh8LyDDwqem2cSSwBA=";
nativeCheckInputs = with pkgs; [ less ];
};
client = pkgs.buildNpmPackage {
pname = "${pname}-client";
inherit version;
src = gitignore.lib.gitignoreSource ./client;
npmDepsHash = "sha256-53n7y10JA4unu1lsMZyxN4rQnV9CtKGySRdEsBCy75U=";
nodejs = pkgs.nodejs_22;
npmFlags = [ "--legacy-peer-deps" ];
installPhase = ''
cp -r build "$out"
chmod -R u+w "$out"
'';
};
in
{
devShells.default = pkgs.mkShell {
packages = with pkgs; [
# Go backend
# Server
go
gotools
gopls
air
# Protobuf middleware
revive
sqlc
# database
sqlite
dbmate
sqlfluff
# Protobuf
buf
protoc-gen-go
protoc-gen-connect-go
protoc-gen-es
protoc-gen-connect-openapi
inotify-tools
(buildGoModule {
name = "protoc-gen-connect-openapi";
src = pkgs.fetchFromGitHub {
owner = "sudorandom";
repo = "protoc-gen-connect-openapi";
rev = "v0.16.1";
sha256 = "sha256-3XBQCc9H9N/AZm/8J5bJRgBhVtoZKFvbdTB+glHxYdA=";
};
vendorHash = "sha256-CIiG/XhV8xxjYY0sZcSvIFcJ1Wh8LyDDwqem2cSSwBA=";
nativeCheckInputs = with pkgs; [less];
})
# Svelte frontend
# Client
nodejs_22
]
# Use .scripts
++ map (
x: (
pkgs.writeShellApplication {
name = "${pname}-${(lib.nameFromURL (baseNameOf x) ".")}";
text = builtins.readFile x;
}
)
) (pkgs.lib.filesystem.listFilesRecursive ./.scripts);
};
});
# Nix
nix-update
formatter = forSystem ({pkgs, ...}: pkgs.alejandra);
# Helper scripts
(writeShellApplication {
name = "ts-run";
packages = forSystem ({pkgs, ...}: rec {
default = trevstack;
text = ''
git_root=$(git rev-parse --show-toplevel)
trevstack-client = pkgs.buildNpmPackage {
pname = "${pname}-client";
inherit version;
src = ./client;
npmDepsHash = "sha256-o+ANqVBYztpQNAFTThSHdS+euteIGijUTZSXp2DlkDU=";
nodejs = pkgs.nodejs_22;
(cd "''${git_root}/server" && air) &
P1=$!
installPhase = ''
cp -r build "$out"
chmod -R u+w "$out"
'';
};
(cd "''${git_root}/client" && npm run dev) &
P2=$!
trevstack = pkgs.buildGoModule {
inherit trevstack-client pname version;
src = ./server;
vendorHash = "sha256-yU+d3bKpMYVkZ9Etqe3cSDtFqswZYZK01d6vxDt/a5U=";
(cd "''${git_root}" && ts-pbwatch) &
P3=$!
trap 'kill $P1 $P2 $P3' SIGINT SIGTERM
wait $P1
wait $P2
wait $P3
kill $P1 $P2 $P3
'';
})
(writeShellApplication {
name = "ts-pbwatch";
text = ''
inotifywait -mre close_write,moved_to,create proto | while read -r _ _ basename;
do
echo "file changed: $basename"
if buf lint ; then
buf generate
fi
echo "regenerated proto services"
done
'';
})
(writeShellApplication {
name = "ts-update";
text = ''
git_root=$(git rev-parse --show-toplevel)
cd "''${git_root}/client"
npm update --save
if ! git diff --exit-code package.json package-lock.json; then
git add package-lock.json
git add package.json
git commit -m "build(client): updated npm dependencies"
fi
cd "''${git_root}/server"
go get -u
go mod tidy
if ! git diff --exit-code go.mod go.sum; then
git add go.mod
git add go.sum
git commit -m "build(server): updated go dependencies"
fi
cd "''${git_root}"
nix-update --flake --version=skip --subpackage client default
if ! git diff --exit-code flake.nix; then
git add flake.nix
git commit -m "build(nix): updated nix hashes"
fi
'';
})
(writeShellApplication {
name = "ts-release";
text = ''
git_root=$(git rev-parse --show-toplevel)
version=$(git describe --abbrev=0)
version_no_v="''${version:1}"
next_version=$(echo "''${version}" | awk -F. -v OFS=. '{$NF += 1 ; print}')
next_version_no_v=$(echo "''${version_no_v}" | awk -F. -v OFS=. '{$NF += 1 ; print}')
cd "''${git_root}/client"
npm version "''${next_version_no_v}"
git add package-lock.json
git add package.json
cd "''${git_root}"
nix-update --flake --version "''${next_version_no_v}" --subpackage client default
git add flake.nix
git commit -m "release: ''${version} -> ''${next_version}"
git push origin main
git tag -a "''${next_version}" -m "release: ''${version} -> ''${next_version}"
git push origin "''${next_version}"
'';
})
];
};
packages.default = pkgs.buildGoModule {
inherit client pname version;
src = gitignore.lib.gitignoreSource ./server;
vendorHash = "sha256-sANPwYLGwMcWyMR7Veho81aAMfIQpVzZS5Q9eveR8o8=";
preBuild = ''
cp -r ${client} internal/handlers/client/client
'';
};
}
);
preBuild = ''
cp -r ${trevstack-client} client
'';
};
});
};
}

View File

@ -5,12 +5,12 @@ package item.v1;
import "google/protobuf/timestamp.proto";
message Item {
optional uint32 id = 1;
int64 id = 1;
string name = 2;
string description = 3;
float price = 4;
uint32 quantity = 5;
optional google.protobuf.Timestamp added = 6;
google.protobuf.Timestamp added = 3;
string description = 4;
float price = 5;
int32 quantity = 6;
}
service ItemService {
@ -22,7 +22,7 @@ service ItemService {
}
message GetItemRequest {
uint32 id = 1;
int64 id = 1;
}
message GetItemResponse {
Item item = 1;
@ -32,29 +32,35 @@ message GetItemsRequest {
optional google.protobuf.Timestamp start = 1;
optional google.protobuf.Timestamp end = 2;
optional string filter = 3;
optional uint32 limit = 4;
optional uint32 offset = 5;
optional int32 limit = 4;
optional int32 offset = 5;
}
message GetItemsResponse {
repeated Item items = 1;
uint64 count = 2;
int64 count = 2;
}
message CreateItemRequest {
Item item = 1;
string name = 1;
string description = 2;
float price = 3;
int32 quantity = 4;
}
message CreateItemResponse {
Item item = 1;
int64 id = 1;
google.protobuf.Timestamp added = 2;
}
message UpdateItemRequest {
Item item = 1;
}
message UpdateItemResponse {
Item item = 1;
int64 id = 1;
optional string name = 2;
optional string description = 3;
optional float price = 4;
optional int32 quantity = 5;
}
message UpdateItemResponse {}
message DeleteItemRequest {
uint32 id = 1;
int64 id = 1;
}
message DeleteItemResponse {}

View File

@ -6,6 +6,9 @@ service AuthService {
rpc Login (LoginRequest) returns (LoginResponse) {}
rpc SignUp (SignUpRequest) returns (SignUpResponse) {}
rpc Logout (LogoutRequest) returns (LogoutResponse) {}
// rpc GetPasskeyIDs (GetPasskeyIDsRequest) returns (GetPasskeyIDsResponse) {}
// rpc BeginPasskeyLogin (BeginPasskeyLoginRequest) returns (BeginPasskeyLoginResponse) {}
// rpc FinishPasskeyLogin (FinishPasskeyLoginRequest) returns (FinishPasskeyLoginResponse) {}
}
message LoginRequest {
@ -18,10 +21,23 @@ message LoginResponse {
message SignUpRequest {
string username = 1;
string password = 2;
string password = 2;
string confirm_password = 3;
}
message SignUpResponse {}
message LogoutRequest {}
message LogoutResponse {}
message LogoutResponse {}
// message GetPasskeyIDsRequest {
// string username = 1;
// }
// message GetPasskeyIDsResponse {
// repeated string passkey_ids = 1;
// }
// message BeginPasskeyLoginRequest {}
// message BeginPasskeyLoginResponse {}
// message FinishPasskeyLoginRequest {}
// message FinishPasskeyLoginResponse {}

View File

@ -3,9 +3,9 @@ syntax = "proto3";
package user.v1;
message User {
uint32 id = 1;
int64 id = 1;
string username = 2;
optional string profile_picture = 3;
optional int64 profile_picture_id = 3;
}
service UserService {
@ -13,6 +13,8 @@ service UserService {
rpc UpdatePassword (UpdatePasswordRequest) returns (UpdatePasswordResponse) {}
rpc GetAPIKey (GetAPIKeyRequest) returns (GetAPIKeyResponse) {}
rpc UpdateProfilePicture (UpdateProfilePictureRequest) returns (UpdateProfilePictureResponse) {}
// rpc BeginPasskeyRegistration (BeginPasskeyRegistrationRequest) returns (BeginPasskeyRegistrationResponse) {}
// rpc FinishPasskeyRegistration (FinishPasskeyRegistrationRequest) returns (FinishPasskeyRegistrationResponse) {}
}
message GetUserRequest {}
@ -33,7 +35,7 @@ message GetAPIKeyRequest {
string password = 1;
string confirm_password = 2;
}
message GetAPIKeyResponse {
message GetAPIKeyResponse {
string key = 1;
}
@ -44,3 +46,9 @@ message UpdateProfilePictureRequest {
message UpdateProfilePictureResponse {
User user = 1;
}
// message BeginPasskeyRegistrationRequest {}
// message BeginPasskeyRegistrationResponse {}
// message FinishPasskeyRegistrationRequest {}
// message FinishPasskeyRegistrationResponse {}

View File

@ -1,52 +0,0 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
args_bin = []
bin = "./tmp/main"
cmd = "go build -o ./tmp/main ."
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
main_only = false
silent = false
time = false
[misc]
clean_on_exit = false
[proxy]
app_port = 0
enabled = false
proxy_port = 0
[screen]
clear_on_rebuild = false
keep_scroll = true

3
server/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/client/
/tmp/
/build/

16
server/bobgen.yaml Normal file
View File

@ -0,0 +1,16 @@
wipe: true
replacements:
- match:
db_type: "INTEGER"
replace: "int64"
- match:
db_type: "INTEGER"
nullable: true
replace: "int64"
sql:
dialect: sqlite
dir: db
output: internal/models

2
server/db/.sqlfluff Normal file
View File

@ -0,0 +1,2 @@
[sqlfluff]
dialect = sqlite

View File

@ -0,0 +1 @@
/schema.sql

View File

@ -0,0 +1,35 @@
-- migrate:up
CREATE TABLE user (
id INTEGER PRIMARY KEY NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL,
profile_picture_id INTEGER,
FOREIGN KEY (profile_picture_id) REFERENCES file (id)
);
CREATE TABLE file (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
data BLOB NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (id)
);
CREATE TABLE item (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
added DATETIME NOT NULL,
description TEXT NOT NULL,
price REAL NOT NULL,
quantity INTEGER NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (id)
);
-- migrate:down
DROP TABLE user;
DROP TABLE file;
DROP TABLE item;

View File

@ -0,0 +1,41 @@
-- name: GetFile :one
SELECT
id,
name,
data,
user_id
FROM file
WHERE
id = @id
AND
user_id = @user_id
LIMIT 1;
-- name: InsertFile :one
INSERT INTO file (
name,
data,
user_id
) VALUES (
@name,
@data,
@user_id
)
RETURNING id;
-- name: UpdateFile :exec
UPDATE file
SET
name = COALESCE(sqlc.narg('name'), name),
data = COALESCE(sqlc.narg('data'), data)
WHERE
id = @id
AND
user_id = @user_id;
-- name: DeleteFile :exec
DELETE FROM file
WHERE
id = @id
AND
user_id = @user_id;

View File

@ -0,0 +1,92 @@
-- name: GetItem :one
SELECT
id,
name,
added,
description,
price,
quantity,
user_id
FROM item
WHERE
id = @id
AND
user_id = @user_id
LIMIT 1;
-- name: GetItems :many
SELECT
id,
name,
added,
description,
price,
quantity,
user_id
FROM item
WHERE
user_id = @user_id
AND
(
(name LIKE sqlc.narg('name') OR sqlc.narg('name') IS NULL)
AND
(added >= sqlc.narg('start') OR sqlc.narg('start') IS NULL)
AND
(added <= sqlc.narg('end') OR sqlc.narg('end') IS NULL)
)
LIMIT
@limit
OFFSET
@offset;
-- name: GetItemsCount :one
SELECT COUNT(id)
FROM item
WHERE
user_id = @user_id
AND
(
(name LIKE sqlc.narg('name') OR sqlc.narg('name') IS NULL)
AND
(added >= sqlc.narg('start') OR sqlc.narg('start') IS NULL)
AND
(added <= sqlc.narg('end') OR sqlc.narg('end') IS NULL)
)
LIMIT 1;
-- name: InsertItem :one
INSERT INTO item (
name,
added,
description,
price,
quantity,
user_id
) VALUES (
@name,
@added,
@description,
@price,
@quantity,
@user_id
)
RETURNING id;
-- name: UpdateItem :exec
UPDATE item
SET
name = COALESCE(sqlc.narg('name'), name),
description = COALESCE(sqlc.narg('description'), description),
price = COALESCE(sqlc.narg('price'), price),
quantity = COALESCE(sqlc.narg('quantity'), quantity)
WHERE
id = @id
AND
user_id = @user_id;
-- name: DeleteItem :exec
DELETE FROM item
WHERE
id = @id
AND
user_id = @user_id;

View File

@ -0,0 +1,46 @@
-- name: GetUser :one
SELECT
id,
username,
password,
profile_picture_id
FROM user
WHERE
id = @id
LIMIT 1;
-- name: GetUserbyUsername :one
SELECT
id,
username,
password,
profile_picture_id
FROM user
WHERE
username = @username
LIMIT 1;
-- name: InsertUser :one
INSERT INTO user (
username,
password
) VALUES (
@username,
@password
)
RETURNING id;
-- name: UpdateUser :exec
UPDATE user
SET
username = COALESCE(sqlc.narg('username'), username),
password = COALESCE(sqlc.narg('password'), password),
profile_picture_id = COALESCE(
sqlc.narg('profile_picture_id'),
profile_picture_id
)
WHERE id = @id;
-- name: DeleteUser :exec
DELETE FROM user
WHERE id = @id;

31
server/db/schema.sql Normal file
View File

@ -0,0 +1,31 @@
CREATE TABLE IF NOT EXISTS "schema_migrations" (version varchar(128) primary key);
CREATE TABLE user (
id INTEGER PRIMARY KEY NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL,
profile_picture_id INTEGER,
FOREIGN KEY (profile_picture_id) REFERENCES file (id)
);
CREATE TABLE file (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
data BLOB NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (id)
);
CREATE TABLE item (
id INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
added DATETIME NOT NULL,
description TEXT NOT NULL,
price REAL NOT NULL,
quantity INTEGER NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (id)
);
-- Dbmate schema migrations
INSERT INTO "schema_migrations" (version) VALUES
('20250410195416');

View File

@ -1,41 +1,33 @@
module github.com/spotdemo4/trevstack/server
go 1.23.6
go 1.24.1
require (
connectrpc.com/connect v1.18.1
connectrpc.com/cors v0.1.0
github.com/glebarez/sqlite v1.11.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/amacneil/dbmate/v2 v2.26.0
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/joho/godotenv v1.5.1
github.com/rs/cors v1.11.1
golang.org/x/crypto v0.36.0
golang.org/x/net v0.37.0
github.com/spotdemo4/dbmate-sqlite-modernc v0.0.2
golang.org/x/crypto v0.37.0
golang.org/x/net v0.39.0
golang.org/x/time v0.11.0
google.golang.org/protobuf v1.36.5
gorm.io/driver/postgres v1.5.11
gorm.io/gorm v1.25.12
google.golang.org/protobuf v1.36.6
modernc.org/sqlite v1.37.0
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.2 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.23.0 // indirect
modernc.org/libc v1.61.13 // indirect
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/sys v0.32.0 // indirect
golang.org/x/text v0.24.0 // indirect
modernc.org/libc v1.62.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.9.0 // indirect
modernc.org/sqlite v1.36.1 // indirect
modernc.org/memory v1.9.1 // indirect
)

View File

@ -2,39 +2,32 @@ connectrpc.com/connect v1.18.1 h1:PAg7CjSAGvscaf6YZKUefjoih5Z/qYkyaTrBW8xvYPw=
connectrpc.com/connect v1.18.1/go.mod h1:0292hj1rnx8oFrStN7cB4jjVBeqs+Yx5yDIC2prWDO8=
connectrpc.com/cors v0.1.0 h1:f3gTXJyDZPrDIZCQ567jxfD9PAIpopHiRDnJRt3QuOQ=
connectrpc.com/cors v0.1.0/go.mod h1:v8SJZCPfHtGH1zsm+Ttajpozd4cYIUryl4dFB6QEpfg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/amacneil/dbmate/v2 v2.26.0 h1:74ykEWh0V41BU3wesgmTowMn/2x9rUfIxIG+Q+vuUm0=
github.com/amacneil/dbmate/v2 v2.26.0/go.mod h1:cnjZKm5x/gKMLPfExXbEDUUQi1Sv5UqY3AIgbnxql84=
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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
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/go-sql-driver/mysql v1.9.0 h1:Y0zIbQXhQKmQgTp44Y1dp3wTXcn804QoTptLZT1vtvo=
github.com/go-sql-driver/mysql v1.9.0/go.mod h1:pDetrLJeA3oMujJuvXc8RJoasr589B6A9fwzD3QMrqw=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
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.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@ -43,60 +36,55 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
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/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
github.com/spotdemo4/dbmate-sqlite-modernc v0.0.2 h1:537TA0HvjoWJxPzAhP+t2Gt82NpxGhCdmDsJpta7sdc=
github.com/spotdemo4/dbmate-sqlite-modernc v0.0.2/go.mod h1:JwuvDDgb1VLGyHgSsQN3I+dx6QkEGk86o6Yc8vxzG/4=
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/zenizh/go-capturer v0.0.0-20211219060012-52ea6c8fed04 h1:qXafrlZL1WsJW5OokjraLLRURHiw0OzKHD/RNdspp4w=
github.com/zenizh/go-capturer v0.0.0-20211219060012-52ea6c8fed04/go.mod h1:FiwNQxz6hGoNFBC4nIx+CxZhI3nne5RmIOlT/MXcSD4=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
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/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
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=
golang.org/x/tools v0.32.0 h1:Q7N1vhpkQv7ybVzLFtTjvQya2ewbwNDZzUgfXGqtMWU=
golang.org/x/tools v0.32.0/go.mod h1:ZxrU41P/wAbZD8EDa6dDCa6XfpkhJ7HFMjHJXfBDu8s=
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/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0=
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo=
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo=
modernc.org/cc/v4 v4.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic=
modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU=
modernc.org/ccgo/v4 v4.25.1/go.mod h1:njjuAYiPflywOOrm3B7kCB444ONP5pAVr8PIEoE0uDw=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw=
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s=
modernc.org/libc v1.62.1/go.mod h1:iXhATfJQLjG3NWy56a6WVU73lWOcdYVxsvwCgoPljuo=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.9.0 h1:smV8d5mrOAvj5QIYbc2XLSRWvAIyPI+kQHqxZaxEqCM=
modernc.org/memory v1.9.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.36.1 h1:bDa8BJUH4lg6EGkLbahKe/8QqoF8p9gArSc6fTqYhyQ=
modernc.org/sqlite v1.36.1/go.mod h1:7MPwH7Z6bREicF9ZVUR78P1IKuxfZ8mRIDHD0iD+8TU=
modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI=
modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=

View File

@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc-gen-go v1.36.6
// protoc (unknown)
// source: item/v1/item.proto
@ -24,12 +24,12 @@ const (
type Item struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id *uint32 `protobuf:"varint,1,opt,name=id,proto3,oneof" json:"id,omitempty"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
Price float32 `protobuf:"fixed32,4,opt,name=price,proto3" json:"price,omitempty"`
Quantity uint32 `protobuf:"varint,5,opt,name=quantity,proto3" json:"quantity,omitempty"`
Added *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=added,proto3,oneof" json:"added,omitempty"`
Added *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=added,proto3" json:"added,omitempty"`
Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"`
Price float32 `protobuf:"fixed32,5,opt,name=price,proto3" json:"price,omitempty"`
Quantity int32 `protobuf:"varint,6,opt,name=quantity,proto3" json:"quantity,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -64,9 +64,9 @@ func (*Item) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{0}
}
func (x *Item) GetId() uint32 {
if x != nil && x.Id != nil {
return *x.Id
func (x *Item) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
@ -78,6 +78,13 @@ func (x *Item) GetName() string {
return ""
}
func (x *Item) GetAdded() *timestamppb.Timestamp {
if x != nil {
return x.Added
}
return nil
}
func (x *Item) GetDescription() string {
if x != nil {
return x.Description
@ -92,23 +99,16 @@ func (x *Item) GetPrice() float32 {
return 0
}
func (x *Item) GetQuantity() uint32 {
func (x *Item) GetQuantity() int32 {
if x != nil {
return x.Quantity
}
return 0
}
func (x *Item) GetAdded() *timestamppb.Timestamp {
if x != nil {
return x.Added
}
return nil
}
type GetItemRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -143,7 +143,7 @@ func (*GetItemRequest) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{1}
}
func (x *GetItemRequest) GetId() uint32 {
func (x *GetItemRequest) GetId() int64 {
if x != nil {
return x.Id
}
@ -199,8 +199,8 @@ type GetItemsRequest struct {
Start *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=start,proto3,oneof" json:"start,omitempty"`
End *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=end,proto3,oneof" json:"end,omitempty"`
Filter *string `protobuf:"bytes,3,opt,name=filter,proto3,oneof" json:"filter,omitempty"`
Limit *uint32 `protobuf:"varint,4,opt,name=limit,proto3,oneof" json:"limit,omitempty"`
Offset *uint32 `protobuf:"varint,5,opt,name=offset,proto3,oneof" json:"offset,omitempty"`
Limit *int32 `protobuf:"varint,4,opt,name=limit,proto3,oneof" json:"limit,omitempty"`
Offset *int32 `protobuf:"varint,5,opt,name=offset,proto3,oneof" json:"offset,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -256,14 +256,14 @@ func (x *GetItemsRequest) GetFilter() string {
return ""
}
func (x *GetItemsRequest) GetLimit() uint32 {
func (x *GetItemsRequest) GetLimit() int32 {
if x != nil && x.Limit != nil {
return *x.Limit
}
return 0
}
func (x *GetItemsRequest) GetOffset() uint32 {
func (x *GetItemsRequest) GetOffset() int32 {
if x != nil && x.Offset != nil {
return *x.Offset
}
@ -273,7 +273,7 @@ func (x *GetItemsRequest) GetOffset() uint32 {
type GetItemsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Items []*Item `protobuf:"bytes,1,rep,name=items,proto3" json:"items,omitempty"`
Count uint64 `protobuf:"varint,2,opt,name=count,proto3" json:"count,omitempty"`
Count int64 `protobuf:"varint,2,opt,name=count,proto3" json:"count,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -315,7 +315,7 @@ func (x *GetItemsResponse) GetItems() []*Item {
return nil
}
func (x *GetItemsResponse) GetCount() uint64 {
func (x *GetItemsResponse) GetCount() int64 {
if x != nil {
return x.Count
}
@ -324,7 +324,10 @@ func (x *GetItemsResponse) GetCount() uint64 {
type CreateItemRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Item *Item `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`
Price float32 `protobuf:"fixed32,3,opt,name=price,proto3" json:"price,omitempty"`
Quantity int32 `protobuf:"varint,4,opt,name=quantity,proto3" json:"quantity,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -359,16 +362,38 @@ func (*CreateItemRequest) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{5}
}
func (x *CreateItemRequest) GetItem() *Item {
func (x *CreateItemRequest) GetName() string {
if x != nil {
return x.Item
return x.Name
}
return nil
return ""
}
func (x *CreateItemRequest) GetDescription() string {
if x != nil {
return x.Description
}
return ""
}
func (x *CreateItemRequest) GetPrice() float32 {
if x != nil {
return x.Price
}
return 0
}
func (x *CreateItemRequest) GetQuantity() int32 {
if x != nil {
return x.Quantity
}
return 0
}
type CreateItemResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Item *Item `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Added *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=added,proto3" json:"added,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -403,16 +428,27 @@ func (*CreateItemResponse) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{6}
}
func (x *CreateItemResponse) GetItem() *Item {
func (x *CreateItemResponse) GetId() int64 {
if x != nil {
return x.Item
return x.Id
}
return 0
}
func (x *CreateItemResponse) GetAdded() *timestamppb.Timestamp {
if x != nil {
return x.Added
}
return nil
}
type UpdateItemRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Item *Item `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name *string `protobuf:"bytes,2,opt,name=name,proto3,oneof" json:"name,omitempty"`
Description *string `protobuf:"bytes,3,opt,name=description,proto3,oneof" json:"description,omitempty"`
Price *float32 `protobuf:"fixed32,4,opt,name=price,proto3,oneof" json:"price,omitempty"`
Quantity *int32 `protobuf:"varint,5,opt,name=quantity,proto3,oneof" json:"quantity,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -447,16 +483,43 @@ func (*UpdateItemRequest) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{7}
}
func (x *UpdateItemRequest) GetItem() *Item {
func (x *UpdateItemRequest) GetId() int64 {
if x != nil {
return x.Item
return x.Id
}
return nil
return 0
}
func (x *UpdateItemRequest) GetName() string {
if x != nil && x.Name != nil {
return *x.Name
}
return ""
}
func (x *UpdateItemRequest) GetDescription() string {
if x != nil && x.Description != nil {
return *x.Description
}
return ""
}
func (x *UpdateItemRequest) GetPrice() float32 {
if x != nil && x.Price != nil {
return *x.Price
}
return 0
}
func (x *UpdateItemRequest) GetQuantity() int32 {
if x != nil && x.Quantity != nil {
return *x.Quantity
}
return 0
}
type UpdateItemResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Item *Item `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -491,16 +554,9 @@ func (*UpdateItemResponse) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{8}
}
func (x *UpdateItemResponse) GetItem() *Item {
if x != nil {
return x.Item
}
return nil
}
type DeleteItemRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@ -535,7 +591,7 @@ func (*DeleteItemRequest) Descriptor() ([]byte, []int) {
return file_item_v1_item_proto_rawDescGZIP(), []int{9}
}
func (x *DeleteItemRequest) GetId() uint32 {
func (x *DeleteItemRequest) GetId() int64 {
if x != nil {
return x.Id
}
@ -580,103 +636,66 @@ func (*DeleteItemResponse) Descriptor() ([]byte, []int) {
var File_item_v1_item_proto protoreflect.FileDescriptor
var file_item_v1_item_proto_rawDesc = string([]byte{
0x0a, 0x12, 0x69, 0x74, 0x65, 0x6d, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x1a, 0x1f, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcb,
0x01, 0x0a, 0x04, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x13, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
0x01, 0x28, 0x0d, 0x48, 0x00, 0x52, 0x02, 0x69, 0x64, 0x88, 0x01, 0x01, 0x12, 0x12, 0x0a, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65,
0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18,
0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28,
0x02, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x71, 0x75, 0x61, 0x6e,
0x74, 0x69, 0x74, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x71, 0x75, 0x61, 0x6e,
0x74, 0x69, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x05, 0x61, 0x64, 0x64, 0x65, 0x64, 0x18, 0x06, 0x20,
0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x48,
0x01, 0x52, 0x05, 0x61, 0x64, 0x64, 0x65, 0x64, 0x88, 0x01, 0x01, 0x42, 0x05, 0x0a, 0x03, 0x5f,
0x69, 0x64, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x61, 0x64, 0x64, 0x65, 0x64, 0x22, 0x20, 0x0a, 0x0e,
0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e,
0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x02, 0x69, 0x64, 0x22, 0x34,
0x0a, 0x0f, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x12, 0x21, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32,
0x0d, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x04,
0x69, 0x74, 0x65, 0x6d, 0x22, 0x82, 0x02, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d,
0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x35, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72,
0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74,
0x61, 0x6d, 0x70, 0x48, 0x00, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x88, 0x01, 0x01, 0x12,
0x31, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54,
0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x48, 0x01, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x88,
0x01, 0x01, 0x12, 0x1b, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01,
0x28, 0x09, 0x48, 0x02, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x88, 0x01, 0x01, 0x12,
0x19, 0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x48, 0x03,
0x52, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x88, 0x01, 0x01, 0x12, 0x1b, 0x0a, 0x06, 0x6f, 0x66,
0x66, 0x73, 0x65, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x48, 0x04, 0x52, 0x06, 0x6f, 0x66,
0x66, 0x73, 0x65, 0x74, 0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72,
0x74, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x65, 0x6e, 0x64, 0x42, 0x09, 0x0a, 0x07, 0x5f, 0x66, 0x69,
0x6c, 0x74, 0x65, 0x72, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x42, 0x09,
0x0a, 0x07, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x22, 0x4d, 0x0a, 0x10, 0x47, 0x65, 0x74,
0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x23, 0x0a,
0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x69,
0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x05, 0x69, 0x74, 0x65,
0x6d, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28,
0x04, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x36, 0x0a, 0x11, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x21, 0x0a,
0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x69, 0x74,
0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d,
0x22, 0x37, 0x0a, 0x12, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x21, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x01,
0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49,
0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x36, 0x0a, 0x11, 0x55, 0x70, 0x64,
0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x21,
0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x69,
0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65,
0x6d, 0x22, 0x37, 0x0a, 0x12, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x21, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18,
0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e,
0x49, 0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x23, 0x0a, 0x11, 0x44, 0x65,
0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12,
0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x02, 0x69, 0x64, 0x22,
0x14, 0x0a, 0x12, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xeb, 0x02, 0x0a, 0x0b, 0x49, 0x74, 0x65, 0x6d, 0x53, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3e, 0x0a, 0x07, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d,
0x12, 0x17, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74,
0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x69, 0x74, 0x65, 0x6d,
0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x41, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d,
0x73, 0x12, 0x18, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x49,
0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, 0x69, 0x74,
0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x47, 0x0a, 0x0a, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1a, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31,
0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x72, 0x65,
0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,
0x00, 0x12, 0x47, 0x0a, 0x0a, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12,
0x1a, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65,
0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x69, 0x74,
0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x47, 0x0a, 0x0a, 0x44, 0x65,
0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1a, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e,
0x76, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44,
0x65, 0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x22, 0x00, 0x42, 0x9d, 0x01, 0x0a, 0x0b, 0x63, 0x6f, 0x6d, 0x2e, 0x69, 0x74, 0x65, 0x6d,
0x2e, 0x76, 0x31, 0x42, 0x09, 0x49, 0x74, 0x65, 0x6d, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01,
0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x70, 0x6f,
0x74, 0x64, 0x65, 0x6d, 0x6f, 0x34, 0x2f, 0x74, 0x72, 0x65, 0x76, 0x73, 0x74, 0x61, 0x63, 0x6b,
0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c,
0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x2f, 0x76,
0x31, 0x3b, 0x69, 0x74, 0x65, 0x6d, 0x76, 0x31, 0xa2, 0x02, 0x03, 0x49, 0x58, 0x58, 0xaa, 0x02,
0x07, 0x49, 0x74, 0x65, 0x6d, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x07, 0x49, 0x74, 0x65, 0x6d, 0x5c,
0x56, 0x31, 0xe2, 0x02, 0x13, 0x49, 0x74, 0x65, 0x6d, 0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42,
0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x08, 0x49, 0x74, 0x65, 0x6d, 0x3a,
0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
})
const file_item_v1_item_proto_rawDesc = "" +
"\n" +
"\x12item/v1/item.proto\x12\aitem.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xb0\x01\n" +
"\x04Item\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x120\n" +
"\x05added\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x05added\x12 \n" +
"\vdescription\x18\x04 \x01(\tR\vdescription\x12\x14\n" +
"\x05price\x18\x05 \x01(\x02R\x05price\x12\x1a\n" +
"\bquantity\x18\x06 \x01(\x05R\bquantity\" \n" +
"\x0eGetItemRequest\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\"4\n" +
"\x0fGetItemResponse\x12!\n" +
"\x04item\x18\x01 \x01(\v2\r.item.v1.ItemR\x04item\"\x82\x02\n" +
"\x0fGetItemsRequest\x125\n" +
"\x05start\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampH\x00R\x05start\x88\x01\x01\x121\n" +
"\x03end\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampH\x01R\x03end\x88\x01\x01\x12\x1b\n" +
"\x06filter\x18\x03 \x01(\tH\x02R\x06filter\x88\x01\x01\x12\x19\n" +
"\x05limit\x18\x04 \x01(\x05H\x03R\x05limit\x88\x01\x01\x12\x1b\n" +
"\x06offset\x18\x05 \x01(\x05H\x04R\x06offset\x88\x01\x01B\b\n" +
"\x06_startB\x06\n" +
"\x04_endB\t\n" +
"\a_filterB\b\n" +
"\x06_limitB\t\n" +
"\a_offset\"M\n" +
"\x10GetItemsResponse\x12#\n" +
"\x05items\x18\x01 \x03(\v2\r.item.v1.ItemR\x05items\x12\x14\n" +
"\x05count\x18\x02 \x01(\x03R\x05count\"{\n" +
"\x11CreateItemRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12 \n" +
"\vdescription\x18\x02 \x01(\tR\vdescription\x12\x14\n" +
"\x05price\x18\x03 \x01(\x02R\x05price\x12\x1a\n" +
"\bquantity\x18\x04 \x01(\x05R\bquantity\"V\n" +
"\x12CreateItemResponse\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x120\n" +
"\x05added\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x05added\"\xcf\x01\n" +
"\x11UpdateItemRequest\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x17\n" +
"\x04name\x18\x02 \x01(\tH\x00R\x04name\x88\x01\x01\x12%\n" +
"\vdescription\x18\x03 \x01(\tH\x01R\vdescription\x88\x01\x01\x12\x19\n" +
"\x05price\x18\x04 \x01(\x02H\x02R\x05price\x88\x01\x01\x12\x1f\n" +
"\bquantity\x18\x05 \x01(\x05H\x03R\bquantity\x88\x01\x01B\a\n" +
"\x05_nameB\x0e\n" +
"\f_descriptionB\b\n" +
"\x06_priceB\v\n" +
"\t_quantity\"\x14\n" +
"\x12UpdateItemResponse\"#\n" +
"\x11DeleteItemRequest\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\"\x14\n" +
"\x12DeleteItemResponse2\xeb\x02\n" +
"\vItemService\x12>\n" +
"\aGetItem\x12\x17.item.v1.GetItemRequest\x1a\x18.item.v1.GetItemResponse\"\x00\x12A\n" +
"\bGetItems\x12\x18.item.v1.GetItemsRequest\x1a\x19.item.v1.GetItemsResponse\"\x00\x12G\n" +
"\n" +
"CreateItem\x12\x1a.item.v1.CreateItemRequest\x1a\x1b.item.v1.CreateItemResponse\"\x00\x12G\n" +
"\n" +
"UpdateItem\x12\x1a.item.v1.UpdateItemRequest\x1a\x1b.item.v1.UpdateItemResponse\"\x00\x12G\n" +
"\n" +
"DeleteItem\x12\x1a.item.v1.DeleteItemRequest\x1a\x1b.item.v1.DeleteItemResponse\"\x00B\x9c\x01\n" +
"\vcom.item.v1B\tItemProtoP\x01ZEgithub.com/spotdemo4/trevstack/server/internal/connect/item/v1;itemv1\xa2\x02\x03IXX\xaa\x02\aItem.V1\xca\x02\aItem\\V1\xe2\x02\x13Item\\V1\\GPBMetadata\xea\x02\bItem::V1b\x06proto3"
var (
file_item_v1_item_proto_rawDescOnce sync.Once
@ -711,25 +730,22 @@ var file_item_v1_item_proto_depIdxs = []int32{
11, // 2: item.v1.GetItemsRequest.start:type_name -> google.protobuf.Timestamp
11, // 3: item.v1.GetItemsRequest.end:type_name -> google.protobuf.Timestamp
0, // 4: item.v1.GetItemsResponse.items:type_name -> item.v1.Item
0, // 5: item.v1.CreateItemRequest.item:type_name -> item.v1.Item
0, // 6: item.v1.CreateItemResponse.item:type_name -> item.v1.Item
0, // 7: item.v1.UpdateItemRequest.item:type_name -> item.v1.Item
0, // 8: item.v1.UpdateItemResponse.item:type_name -> item.v1.Item
1, // 9: item.v1.ItemService.GetItem:input_type -> item.v1.GetItemRequest
3, // 10: item.v1.ItemService.GetItems:input_type -> item.v1.GetItemsRequest
5, // 11: item.v1.ItemService.CreateItem:input_type -> item.v1.CreateItemRequest
7, // 12: item.v1.ItemService.UpdateItem:input_type -> item.v1.UpdateItemRequest
9, // 13: item.v1.ItemService.DeleteItem:input_type -> item.v1.DeleteItemRequest
2, // 14: item.v1.ItemService.GetItem:output_type -> item.v1.GetItemResponse
4, // 15: item.v1.ItemService.GetItems:output_type -> item.v1.GetItemsResponse
6, // 16: item.v1.ItemService.CreateItem:output_type -> item.v1.CreateItemResponse
8, // 17: item.v1.ItemService.UpdateItem:output_type -> item.v1.UpdateItemResponse
10, // 18: item.v1.ItemService.DeleteItem:output_type -> item.v1.DeleteItemResponse
14, // [14:19] is the sub-list for method output_type
9, // [9:14] is the sub-list for method input_type
9, // [9:9] is the sub-list for extension type_name
9, // [9:9] is the sub-list for extension extendee
0, // [0:9] is the sub-list for field type_name
11, // 5: item.v1.CreateItemResponse.added:type_name -> google.protobuf.Timestamp
1, // 6: item.v1.ItemService.GetItem:input_type -> item.v1.GetItemRequest
3, // 7: item.v1.ItemService.GetItems:input_type -> item.v1.GetItemsRequest
5, // 8: item.v1.ItemService.CreateItem:input_type -> item.v1.CreateItemRequest
7, // 9: item.v1.ItemService.UpdateItem:input_type -> item.v1.UpdateItemRequest
9, // 10: item.v1.ItemService.DeleteItem:input_type -> item.v1.DeleteItemRequest
2, // 11: item.v1.ItemService.GetItem:output_type -> item.v1.GetItemResponse
4, // 12: item.v1.ItemService.GetItems:output_type -> item.v1.GetItemsResponse
6, // 13: item.v1.ItemService.CreateItem:output_type -> item.v1.CreateItemResponse
8, // 14: item.v1.ItemService.UpdateItem:output_type -> item.v1.UpdateItemResponse
10, // 15: item.v1.ItemService.DeleteItem:output_type -> item.v1.DeleteItemResponse
11, // [11:16] is the sub-list for method output_type
6, // [6:11] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
}
func init() { file_item_v1_item_proto_init() }
@ -737,8 +753,8 @@ func file_item_v1_item_proto_init() {
if File_item_v1_item_proto != nil {
return
}
file_item_v1_item_proto_msgTypes[0].OneofWrappers = []any{}
file_item_v1_item_proto_msgTypes[3].OneofWrappers = []any{}
file_item_v1_item_proto_msgTypes[7].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{

View File

@ -8,7 +8,7 @@ import (
connect "connectrpc.com/connect"
context "context"
errors "errors"
v1 "github.com/spotdemo4/trevstack/server/internal/services/item/v1"
v1 "github.com/spotdemo4/trevstack/server/internal/connect/item/v1"
http "net/http"
strings "strings"
)

View File

@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc-gen-go v1.36.6
// protoc (unknown)
// source: user/v1/auth.proto
@ -287,51 +287,26 @@ func (*LogoutResponse) Descriptor() ([]byte, []int) {
var File_user_v1_auth_proto protoreflect.FileDescriptor
var file_user_v1_auth_proto_rawDesc = string([]byte{
0x0a, 0x12, 0x75, 0x73, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x22, 0x46, 0x0a,
0x0c, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a,
0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x25, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18,
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x72, 0x0a, 0x0d,
0x53, 0x69, 0x67, 0x6e, 0x55, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a,
0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d,
0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
0x0f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64,
0x22, 0x10, 0x0a, 0x0e, 0x53, 0x69, 0x67, 0x6e, 0x55, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x22, 0x0f, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x22, 0x10, 0x0a, 0x0e, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xc1, 0x01, 0x0a, 0x0b, 0x41, 0x75, 0x74, 0x68, 0x53, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x38, 0x0a, 0x05, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x15,
0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e,
0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12,
0x3b, 0x0a, 0x06, 0x53, 0x69, 0x67, 0x6e, 0x55, 0x70, 0x12, 0x16, 0x2e, 0x75, 0x73, 0x65, 0x72,
0x2e, 0x76, 0x31, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x55, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x17, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x69, 0x67, 0x6e,
0x55, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x3b, 0x0a, 0x06,
0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x12, 0x16, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31,
0x2e, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17,
0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x6f, 0x75, 0x74, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x9d, 0x01, 0x0a, 0x0b, 0x63, 0x6f,
0x6d, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x42, 0x09, 0x41, 0x75, 0x74, 0x68, 0x50,
0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x73, 0x70, 0x6f, 0x74, 0x64, 0x65, 0x6d, 0x6f, 0x34, 0x2f, 0x74, 0x72, 0x65,
0x76, 0x73, 0x74, 0x61, 0x63, 0x6b, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x69, 0x6e,
0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f,
0x75, 0x73, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x3b, 0x75, 0x73, 0x65, 0x72, 0x76, 0x31, 0xa2, 0x02,
0x03, 0x55, 0x58, 0x58, 0xaa, 0x02, 0x07, 0x55, 0x73, 0x65, 0x72, 0x2e, 0x56, 0x31, 0xca, 0x02,
0x07, 0x55, 0x73, 0x65, 0x72, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x13, 0x55, 0x73, 0x65, 0x72, 0x5c,
0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02,
0x08, 0x55, 0x73, 0x65, 0x72, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
})
const file_user_v1_auth_proto_rawDesc = "" +
"\n" +
"\x12user/v1/auth.proto\x12\auser.v1\"F\n" +
"\fLoginRequest\x12\x1a\n" +
"\busername\x18\x01 \x01(\tR\busername\x12\x1a\n" +
"\bpassword\x18\x02 \x01(\tR\bpassword\"%\n" +
"\rLoginResponse\x12\x14\n" +
"\x05token\x18\x01 \x01(\tR\x05token\"r\n" +
"\rSignUpRequest\x12\x1a\n" +
"\busername\x18\x01 \x01(\tR\busername\x12\x1a\n" +
"\bpassword\x18\x02 \x01(\tR\bpassword\x12)\n" +
"\x10confirm_password\x18\x03 \x01(\tR\x0fconfirmPassword\"\x10\n" +
"\x0eSignUpResponse\"\x0f\n" +
"\rLogoutRequest\"\x10\n" +
"\x0eLogoutResponse2\xc1\x01\n" +
"\vAuthService\x128\n" +
"\x05Login\x12\x15.user.v1.LoginRequest\x1a\x16.user.v1.LoginResponse\"\x00\x12;\n" +
"\x06SignUp\x12\x16.user.v1.SignUpRequest\x1a\x17.user.v1.SignUpResponse\"\x00\x12;\n" +
"\x06Logout\x12\x16.user.v1.LogoutRequest\x1a\x17.user.v1.LogoutResponse\"\x00B\x9c\x01\n" +
"\vcom.user.v1B\tAuthProtoP\x01ZEgithub.com/spotdemo4/trevstack/server/internal/connect/user/v1;userv1\xa2\x02\x03UXX\xaa\x02\aUser.V1\xca\x02\aUser\\V1\xe2\x02\x13User\\V1\\GPBMetadata\xea\x02\bUser::V1b\x06proto3"
var (
file_user_v1_auth_proto_rawDescOnce sync.Once

View File

@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.5
// protoc-gen-go v1.36.6
// protoc (unknown)
// source: user/v1/user.proto
@ -22,12 +22,12 @@ const (
)
type User struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
ProfilePicture *string `protobuf:"bytes,3,opt,name=profile_picture,json=profilePicture,proto3,oneof" json:"profile_picture,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
ProfilePictureId *int64 `protobuf:"varint,3,opt,name=profile_picture_id,json=profilePictureId,proto3,oneof" json:"profile_picture_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *User) Reset() {
@ -60,7 +60,7 @@ func (*User) Descriptor() ([]byte, []int) {
return file_user_v1_user_proto_rawDescGZIP(), []int{0}
}
func (x *User) GetId() uint32 {
func (x *User) GetId() int64 {
if x != nil {
return x.Id
}
@ -74,11 +74,11 @@ func (x *User) GetUsername() string {
return ""
}
func (x *User) GetProfilePicture() string {
if x != nil && x.ProfilePicture != nil {
return *x.ProfilePicture
func (x *User) GetProfilePictureId() int64 {
if x != nil && x.ProfilePictureId != nil {
return *x.ProfilePictureId
}
return ""
return 0
}
type GetUserRequest struct {
@ -459,84 +459,39 @@ func (x *UpdateProfilePictureResponse) GetUser() *User {
var File_user_v1_user_proto protoreflect.FileDescriptor
var file_user_v1_user_proto_rawDesc = string([]byte{
0x0a, 0x12, 0x75, 0x73, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x22, 0x74, 0x0a,
0x04, 0x55, 0x73, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0d, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d,
0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d,
0x65, 0x12, 0x2c, 0x0a, 0x0f, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x70, 0x69, 0x63,
0x74, 0x75, 0x72, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0e, 0x70, 0x72,
0x6f, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x88, 0x01, 0x01, 0x42,
0x12, 0x0a, 0x10, 0x5f, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x70, 0x69, 0x63, 0x74,
0x75, 0x72, 0x65, 0x22, 0x10, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x34, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x21, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72,
0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31,
0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x04, 0x75, 0x73, 0x65, 0x72, 0x22, 0x88, 0x01, 0x0a, 0x15,
0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x21, 0x0a, 0x0c, 0x6f, 0x6c, 0x64, 0x5f, 0x70, 0x61, 0x73,
0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6f, 0x6c, 0x64,
0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x65, 0x77, 0x5f,
0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b,
0x6e, 0x65, 0x77, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18,
0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x50, 0x61,
0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x3b, 0x0a, 0x16, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65,
0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
0x12, 0x21, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d,
0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x04, 0x75,
0x73, 0x65, 0x72, 0x22, 0x59, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77,
0x6f, 0x72, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77,
0x6f, 0x72, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x5f, 0x70,
0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x25,
0x0a, 0x11, 0x47, 0x65, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x4e, 0x0a, 0x1b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50,
0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d,
0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x4e, 0x61, 0x6d,
0x65, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52,
0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x41, 0x0a, 0x1c, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50,
0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x21, 0x0a, 0x04, 0x75, 0x73, 0x65, 0x72, 0x18, 0x01, 0x20,
0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x73,
0x65, 0x72, 0x52, 0x04, 0x75, 0x73, 0x65, 0x72, 0x32, 0xcf, 0x02, 0x0a, 0x0b, 0x55, 0x73, 0x65,
0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3e, 0x0a, 0x07, 0x47, 0x65, 0x74, 0x55,
0x73, 0x65, 0x72, 0x12, 0x17, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65,
0x74, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x75,
0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x53, 0x0a, 0x0e, 0x55, 0x70, 0x64, 0x61,
0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1e, 0x2e, 0x75, 0x73, 0x65,
0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77,
0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f, 0x2e, 0x75, 0x73, 0x65,
0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77,
0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x44, 0x0a,
0x09, 0x47, 0x65, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x12, 0x19, 0x2e, 0x75, 0x73, 0x65,
0x72, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1a, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e,
0x47, 0x65, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73,
0x65, 0x22, 0x00, 0x12, 0x65, 0x0a, 0x14, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f,
0x66, 0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x12, 0x24, 0x2e, 0x75, 0x73,
0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x25, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61,
0x74, 0x65, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x69, 0x63, 0x74, 0x75, 0x72, 0x65,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x9d, 0x01, 0x0a, 0x0b, 0x63,
0x6f, 0x6d, 0x2e, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x42, 0x09, 0x55, 0x73, 0x65, 0x72,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x70, 0x6f, 0x74, 0x64, 0x65, 0x6d, 0x6f, 0x34, 0x2f, 0x74, 0x72,
0x65, 0x76, 0x73, 0x74, 0x61, 0x63, 0x6b, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x69,
0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73,
0x2f, 0x75, 0x73, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x3b, 0x75, 0x73, 0x65, 0x72, 0x76, 0x31, 0xa2,
0x02, 0x03, 0x55, 0x58, 0x58, 0xaa, 0x02, 0x07, 0x55, 0x73, 0x65, 0x72, 0x2e, 0x56, 0x31, 0xca,
0x02, 0x07, 0x55, 0x73, 0x65, 0x72, 0x5c, 0x56, 0x31, 0xe2, 0x02, 0x13, 0x55, 0x73, 0x65, 0x72,
0x5c, 0x56, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea,
0x02, 0x08, 0x55, 0x73, 0x65, 0x72, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
})
const file_user_v1_user_proto_rawDesc = "" +
"\n" +
"\x12user/v1/user.proto\x12\auser.v1\"|\n" +
"\x04User\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x1a\n" +
"\busername\x18\x02 \x01(\tR\busername\x121\n" +
"\x12profile_picture_id\x18\x03 \x01(\x03H\x00R\x10profilePictureId\x88\x01\x01B\x15\n" +
"\x13_profile_picture_id\"\x10\n" +
"\x0eGetUserRequest\"4\n" +
"\x0fGetUserResponse\x12!\n" +
"\x04user\x18\x01 \x01(\v2\r.user.v1.UserR\x04user\"\x88\x01\n" +
"\x15UpdatePasswordRequest\x12!\n" +
"\fold_password\x18\x01 \x01(\tR\voldPassword\x12!\n" +
"\fnew_password\x18\x02 \x01(\tR\vnewPassword\x12)\n" +
"\x10confirm_password\x18\x03 \x01(\tR\x0fconfirmPassword\";\n" +
"\x16UpdatePasswordResponse\x12!\n" +
"\x04user\x18\x01 \x01(\v2\r.user.v1.UserR\x04user\"Y\n" +
"\x10GetAPIKeyRequest\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12)\n" +
"\x10confirm_password\x18\x02 \x01(\tR\x0fconfirmPassword\"%\n" +
"\x11GetAPIKeyResponse\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\"N\n" +
"\x1bUpdateProfilePictureRequest\x12\x1b\n" +
"\tfile_name\x18\x01 \x01(\tR\bfileName\x12\x12\n" +
"\x04data\x18\x02 \x01(\fR\x04data\"A\n" +
"\x1cUpdateProfilePictureResponse\x12!\n" +
"\x04user\x18\x01 \x01(\v2\r.user.v1.UserR\x04user2\xcf\x02\n" +
"\vUserService\x12>\n" +
"\aGetUser\x12\x17.user.v1.GetUserRequest\x1a\x18.user.v1.GetUserResponse\"\x00\x12S\n" +
"\x0eUpdatePassword\x12\x1e.user.v1.UpdatePasswordRequest\x1a\x1f.user.v1.UpdatePasswordResponse\"\x00\x12D\n" +
"\tGetAPIKey\x12\x19.user.v1.GetAPIKeyRequest\x1a\x1a.user.v1.GetAPIKeyResponse\"\x00\x12e\n" +
"\x14UpdateProfilePicture\x12$.user.v1.UpdateProfilePictureRequest\x1a%.user.v1.UpdateProfilePictureResponse\"\x00B\x9c\x01\n" +
"\vcom.user.v1B\tUserProtoP\x01ZEgithub.com/spotdemo4/trevstack/server/internal/connect/user/v1;userv1\xa2\x02\x03UXX\xaa\x02\aUser.V1\xca\x02\aUser\\V1\xe2\x02\x13User\\V1\\GPBMetadata\xea\x02\bUser::V1b\x06proto3"
var (
file_user_v1_user_proto_rawDescOnce sync.Once

View File

@ -8,7 +8,7 @@ import (
connect "connectrpc.com/connect"
context "context"
errors "errors"
v1 "github.com/spotdemo4/trevstack/server/internal/services/user/v1"
v1 "github.com/spotdemo4/trevstack/server/internal/connect/user/v1"
http "net/http"
strings "strings"
)

View File

@ -8,7 +8,7 @@ import (
connect "connectrpc.com/connect"
context "context"
errors "errors"
v1 "github.com/spotdemo4/trevstack/server/internal/services/user/v1"
v1 "github.com/spotdemo4/trevstack/server/internal/connect/user/v1"
http "net/http"
strings "strings"
)

View File

@ -1,22 +0,0 @@
package database
import (
"log"
"os"
"time"
"gorm.io/gorm/logger"
)
func NewLogger() logger.Interface {
return logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Silent, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
ParameterizedQueries: true, // Don't include params in the SQL log
Colorful: true, // Disable color
},
)
}

View File

@ -1,12 +1,39 @@
package database
import (
"github.com/spotdemo4/trevstack/server/internal/models"
"gorm.io/gorm"
"embed"
"log"
"net/url"
"github.com/amacneil/dbmate/v2/pkg/dbmate"
_ "github.com/spotdemo4/dbmate-sqlite-modernc/pkg/driver/sqlite" // Modernc sqlite
)
func Migrate(db *gorm.DB) error {
err := db.AutoMigrate(&models.User{}, &models.Item{}, &models.File{})
func Migrate(dsn string, dbFS *embed.FS) error {
if dbFS == nil {
return nil
}
dburl, err := url.Parse(dsn)
if err != nil {
return err
}
db := dbmate.New(dburl)
db.Driver()
db.FS = dbFS
log.Println("Migrations:")
migrations, err := db.FindMigrations()
if err != nil {
return err
}
for _, m := range migrations {
log.Println(m.Version, m.FilePath)
}
log.Println("\nApplying...")
err = db.CreateAndMigrate()
if err != nil {
return err
}

View File

@ -1,18 +0,0 @@
package database
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func NewPostgresConnection(user, pass, host, port, name string) (*gorm.DB, error) {
dsn := "host=" + host + " user=" + user + " password=" + pass + " dbname=" + name + " port=" + port + " sslmode=disable TimeZone=UTC"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: NewLogger(),
})
if err != nil {
return nil, err
}
return db, nil
}

View File

@ -1,35 +1,29 @@
package database
import (
"os"
"path/filepath"
"database/sql"
"errors"
"strings"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"github.com/spotdemo4/trevstack/server/internal/sqlc"
_ "modernc.org/sqlite" // Sqlite
)
func NewSQLiteConnection(name string) (*gorm.DB, error) {
// Find config diretory
configDir, err := os.UserConfigDir()
if err != nil {
return nil, err
func New(dsn string) (*sqlc.Queries, *sql.DB, error) {
// Validate dsn
sp := strings.Split(dsn, ":")
if len(sp) != 2 {
return nil, nil, errors.New("invalid dsn")
}
// Create database directory if not exists
settingsPath := filepath.Join(configDir, "trevstack")
err = os.MkdirAll(settingsPath, 0766)
// Open db
db, err := sql.Open("sqlite", sp[1])
if err != nil {
return nil, err
return nil, nil, err
}
// Open database
dbPath := filepath.Join(settingsPath, name)
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
Logger: NewLogger(),
})
if err != nil {
return nil, err
}
// Create new sqlc connection
sqlc := sqlc.New(db)
return db, nil
return sqlc, db, nil
}

View File

@ -1,131 +0,0 @@
package handlers
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/models"
userv1 "github.com/spotdemo4/trevstack/server/internal/services/user/v1"
"github.com/spotdemo4/trevstack/server/internal/services/user/v1/userv1connect"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type AuthHandler struct {
db *gorm.DB
key []byte
}
func (h *AuthHandler) Login(ctx context.Context, req *connect.Request[userv1.LoginRequest]) (*connect.Response[userv1.LoginResponse], error) {
// Validate
user := models.User{}
if err := h.db.First(&user, "username = ?", req.Msg.Username).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid username or password"))
}
return nil, connect.NewError(connect.CodeInternal, err)
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.Password)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid username or password"))
}
// Generate JWT
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "trevstack",
Subject: strconv.FormatUint(uint64(user.ID), 10),
IssuedAt: &jwt.NumericDate{
Time: time.Now(),
},
ExpiresAt: &jwt.NumericDate{
Time: time.Now().Add(time.Hour * 24),
},
})
ss, err := t.SignedString(h.key)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Create cookie
cookie := http.Cookie{
Name: "token",
Value: ss,
Path: "/",
MaxAge: 86400,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
res := connect.NewResponse(&userv1.LoginResponse{
Token: ss,
})
res.Header().Set("Set-Cookie", cookie.String())
return res, nil
}
func (h *AuthHandler) SignUp(ctx context.Context, req *connect.Request[userv1.SignUpRequest]) (*connect.Response[userv1.SignUpResponse], error) {
// Validate
if err := h.db.First(&models.User{}, "username = ?", req.Msg.Username).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, connect.NewError(connect.CodeInternal, err)
}
} else {
return nil, connect.NewError(connect.CodeAlreadyExists, errors.New("username already exists"))
}
if req.Msg.Password != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.Password), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Create user
user := models.User{
Username: req.Msg.Username,
Password: string(hash),
}
if err := h.db.Create(&user).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.SignUpResponse{})
return res, nil
}
func (h *AuthHandler) Logout(ctx context.Context, req *connect.Request[userv1.LogoutRequest]) (*connect.Response[userv1.LogoutResponse], error) {
// Clear cookie
cookie := http.Cookie{
Name: "token",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
res := connect.NewResponse(&userv1.LogoutResponse{})
res.Header().Set("Set-Cookie", cookie.String())
return res, nil
}
func NewAuthHandler(db *gorm.DB, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewRateLimitInterceptor(key))
return userv1connect.NewAuthServiceHandler(
&AuthHandler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -1,17 +1,23 @@
package client
import (
"embed"
"io/fs"
"net/http"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
)
var embedfs *http.FileSystem
func NewClientHandler(key string) http.Handler {
if embedfs != nil {
return interceptors.WithAuthRedirect(http.FileServer(*embedfs), key)
func NewClientHandler(key string, clientFS *embed.FS) http.Handler {
if clientFS == nil {
return http.NotFoundHandler()
}
return http.NotFoundHandler()
client, err := fs.Sub(clientFS, "client")
if err != nil {
return http.NotFoundHandler()
}
fs := http.FS(client)
return interceptors.WithAuthRedirect(http.FileServer(fs), key)
}

View File

@ -1,16 +0,0 @@
// go:build !dev
package client
import (
"embed"
"net/http"
)
//go:embed client
var eclient embed.FS
func init() {
fs := http.FS(eclient)
embedfs = &fs
}

View File

@ -1,18 +1,18 @@
package handlers
package file
import (
"database/sql"
"errors"
"log"
"net/http"
"strconv"
"strings"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/models"
"gorm.io/gorm"
"github.com/spotdemo4/trevstack/server/internal/sqlc"
)
type FileHandler struct {
db *gorm.DB
db *sqlc.Queries
key []byte
}
@ -23,39 +23,43 @@ func (h *FileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// Make sure this is a GET request
if r.Method != http.MethodGet {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
// Get the file id from the path
pathItems := strings.Split(r.URL.Path, "/")
if len(pathItems) < 3 {
http.Redirect(w, r, "/auth", http.StatusFound)
return
}
id := pathItems[2]
// Get the file from the database
file := models.File{}
if err := h.db.First(&file, "id = ? AND user_id = ?", id, userid).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
http.Error(w, "File not found", http.StatusNotFound)
return
}
log.Println(err)
id, err := strconv.Atoi(pathItems[2])
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Serve the file
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", http.DetectContentType(file.Data))
w.Write(file.Data)
return
} else {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
// Get the file from the database
file, err := h.db.GetFile(r.Context(), sqlc.GetFileParams{
ID: int64(id),
UserID: userid,
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, "Not Found", http.StatusNotFound)
}
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", http.DetectContentType(file.Data))
w.Write(file.Data)
}
func NewFileHandler(db *gorm.DB, key string) http.Handler {
func NewFileHandler(db *sqlc.Queries, key string) http.Handler {
return interceptors.WithAuthRedirect(
&FileHandler{
db: db,

View File

@ -1,171 +0,0 @@
package handlers
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"connectrpc.com/connect"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/models"
itemv1 "github.com/spotdemo4/trevstack/server/internal/services/item/v1"
"github.com/spotdemo4/trevstack/server/internal/services/item/v1/itemv1connect"
"gorm.io/gorm"
)
type ItemHandler struct {
db *gorm.DB
key []byte
}
func (h *ItemHandler) GetItem(ctx context.Context, req *connect.Request[itemv1.GetItemRequest]) (*connect.Response[itemv1.GetItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get item
item := models.Item{}
if err := h.db.First(&item, "id = ? AND user_id = ?", req.Msg.Id, userid).Error; err != nil {
return nil, connect.NewError(connect.CodeNotFound, err)
}
res := connect.NewResponse(&itemv1.GetItemResponse{
Item: item.ToConnectV1(),
})
return res, nil
}
func (h *ItemHandler) GetItems(ctx context.Context, req *connect.Request[itemv1.GetItemsRequest]) (*connect.Response[itemv1.GetItemsResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Filters
sql := h.db.Where("user_id = ?", userid)
if req.Msg.Start != nil {
sql = sql.Where("added >= ?", req.Msg.Start.AsTime())
}
if req.Msg.End != nil {
sql = sql.Where("added <= ?", req.Msg.End.AsTime())
}
if req.Msg.Filter != nil {
sql = sql.Where("name LIKE ?", fmt.Sprintf("%%%s%%", *req.Msg.Filter))
}
// Uncounted filters
sqlu := sql.Session(&gorm.Session{})
if req.Msg.Limit != nil {
sqlu = sqlu.Limit(int(*req.Msg.Limit))
}
if req.Msg.Offset != nil {
sqlu = sqlu.Offset(int(*req.Msg.Offset))
}
// Get items & count
items := []models.Item{}
var count int64
if err := sqlu.Order("added desc").Find(&items).Error; err != nil {
return nil, connect.NewError(connect.CodeNotFound, err)
}
if err := sql.Model(&items).Count(&count).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Convert to connect v1 items
resItems := []*itemv1.Item{}
for _, item := range items {
resItems = append(resItems, item.ToConnectV1())
}
res := connect.NewResponse(&itemv1.GetItemsResponse{
Items: resItems,
Count: uint64(count),
})
return res, nil
}
func (h *ItemHandler) CreateItem(ctx context.Context, req *connect.Request[itemv1.CreateItemRequest]) (*connect.Response[itemv1.CreateItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Create item
item := models.Item{
Name: req.Msg.Item.Name,
Description: req.Msg.Item.Description,
Price: req.Msg.Item.Price,
Quantity: int(req.Msg.Item.Quantity),
Added: time.Now(),
UserID: uint(userid),
}
if err := h.db.Create(&item).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.CreateItemResponse{
Item: item.ToConnectV1(),
})
return res, nil
}
func (h *ItemHandler) UpdateItem(ctx context.Context, req *connect.Request[itemv1.UpdateItemRequest]) (*connect.Response[itemv1.UpdateItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Validate
if req.Msg.Item.Id == nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("id is required"))
}
// Update item
item := models.Item{
ID: *req.Msg.Item.Id,
Name: req.Msg.Item.Name,
Description: req.Msg.Item.Description,
Price: req.Msg.Item.Price,
Quantity: int(req.Msg.Item.Quantity),
UserID: uint(userid),
}
if err := h.db.Where("id = ? AND user_id = ?", req.Msg.Item.Id, userid).Updates(&item).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.UpdateItemResponse{
Item: item.ToConnectV1(),
})
return res, nil
}
func (h *ItemHandler) DeleteItem(ctx context.Context, req *connect.Request[itemv1.DeleteItemRequest]) (*connect.Response[itemv1.DeleteItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Delete item
if err := h.db.Delete(&models.Item{}, "id = ? AND user_id = ?", req.Msg.Id, userid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.DeleteItemResponse{})
return res, nil
}
func NewItemHandler(db *gorm.DB, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewAuthInterceptor(key))
return itemv1connect.NewItemServiceHandler(
&ItemHandler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -0,0 +1,203 @@
package item
import (
"context"
"database/sql"
"errors"
"net/http"
"time"
"connectrpc.com/connect"
itemv1 "github.com/spotdemo4/trevstack/server/internal/connect/item/v1"
"github.com/spotdemo4/trevstack/server/internal/connect/item/v1/itemv1connect"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/sqlc"
"github.com/spotdemo4/trevstack/server/internal/util"
"google.golang.org/protobuf/types/known/timestamppb"
)
func itemToConnect(item sqlc.Item) *itemv1.Item {
timestamp := timestamppb.New(item.Added)
return &itemv1.Item{
Id: item.ID,
Name: item.Name,
Description: item.Description,
Price: float32(item.Price),
Quantity: int32(item.Quantity),
Added: timestamp,
}
}
type Handler struct {
db *sqlc.Queries
key []byte
}
func (h *Handler) GetItem(ctx context.Context, req *connect.Request[itemv1.GetItemRequest]) (*connect.Response[itemv1.GetItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get item
item, err := h.db.GetItem(ctx, sqlc.GetItemParams{
ID: req.Msg.Id,
UserID: userid,
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.GetItemResponse{
Item: itemToConnect(item),
})
return res, nil
}
func (h *Handler) GetItems(ctx context.Context, req *connect.Request[itemv1.GetItemsRequest]) (*connect.Response[itemv1.GetItemsResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Verify
offset := 0
if req.Msg.Offset != nil {
offset = int(*req.Msg.Offset)
}
limit := 10
if req.Msg.Limit != nil {
limit = int(*req.Msg.Limit)
}
// Get items
items, err := h.db.GetItems(ctx, sqlc.GetItemsParams{
UserID: userid,
Name: util.NullLike(req.Msg.Filter),
Start: util.NullTimestamp(req.Msg.Start),
End: util.NullTimestamp(req.Msg.End),
Offset: int64(offset),
Limit: int64(limit),
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
// Get items count
count, err := h.db.GetItemsCount(ctx, sqlc.GetItemsCountParams{
UserID: userid,
Name: util.NullLike(req.Msg.Filter),
Start: util.NullTimestamp(req.Msg.Start),
End: util.NullTimestamp(req.Msg.End),
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Convert to connect items
resItems := []*itemv1.Item{}
for _, item := range items {
resItems = append(resItems, itemToConnect(item))
}
res := connect.NewResponse(&itemv1.GetItemsResponse{
Items: resItems,
Count: count,
})
return res, nil
}
func (h *Handler) CreateItem(ctx context.Context, req *connect.Request[itemv1.CreateItemRequest]) (*connect.Response[itemv1.CreateItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
time := time.Now()
// Insert item
id, err := h.db.InsertItem(ctx, sqlc.InsertItemParams{
Name: req.Msg.Name,
Added: time,
Description: req.Msg.Description,
Price: float64(req.Msg.Price),
Quantity: int64(req.Msg.Quantity),
UserID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.CreateItemResponse{
Id: id,
Added: timestamppb.New(time),
})
return res, nil
}
func (h *Handler) UpdateItem(ctx context.Context, req *connect.Request[itemv1.UpdateItemRequest]) (*connect.Response[itemv1.UpdateItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Update item
err := h.db.UpdateItem(ctx, sqlc.UpdateItemParams{
// set
Name: req.Msg.Name,
Description: req.Msg.Description,
Price: util.NullFloat64(req.Msg.Price),
Quantity: util.NullInt64(req.Msg.Quantity),
// where
ID: req.Msg.Id,
UserID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.UpdateItemResponse{})
return res, nil
}
func (h *Handler) DeleteItem(ctx context.Context, req *connect.Request[itemv1.DeleteItemRequest]) (*connect.Response[itemv1.DeleteItemResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Delete item
err := h.db.DeleteItem(ctx, sqlc.DeleteItemParams{
ID: req.Msg.Id,
UserID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&itemv1.DeleteItemResponse{})
return res, nil
}
func NewHandler(db *sqlc.Queries, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewAuthInterceptor(key))
return itemv1connect.NewItemServiceHandler(
&Handler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -1,182 +0,0 @@
package handlers
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/models"
userv1 "github.com/spotdemo4/trevstack/server/internal/services/user/v1"
"github.com/spotdemo4/trevstack/server/internal/services/user/v1/userv1connect"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type UserHandler struct {
db *gorm.DB
key []byte
}
func (h *UserHandler) GetUser(ctx context.Context, req *connect.Request[userv1.GetUserRequest]) (*connect.Response[userv1.GetUserResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user := models.User{}
if err := h.db.Preload("ProfilePicture").First(&user, "id = ?", userid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.GetUserResponse{
User: user.ToConnectV1(),
})
return res, nil
}
func (h *UserHandler) UpdatePassword(ctx context.Context, req *connect.Request[userv1.UpdatePasswordRequest]) (*connect.Response[userv1.UpdatePasswordResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user := models.User{}
if err := h.db.First(&user, "id = ?", userid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Validate
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.OldPassword)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid password"))
}
if req.Msg.NewPassword != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.NewPassword), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Update password
if err := h.db.Model(&user).Update("password", string(hash)).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.UpdatePasswordResponse{})
return res, nil
}
func (h *UserHandler) GetAPIKey(ctx context.Context, req *connect.Request[userv1.GetAPIKeyRequest]) (*connect.Response[userv1.GetAPIKeyResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user := models.User{}
if err := h.db.First(&user, "id = ?", userid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Validate
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.Password)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid username or password"))
}
if req.Msg.Password != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Generate JWT
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "trevstack",
Subject: strconv.FormatUint(uint64(user.ID), 10),
IssuedAt: &jwt.NumericDate{
Time: time.Now(),
},
})
ss, err := t.SignedString(h.key)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.GetAPIKeyResponse{
Key: ss,
})
return res, nil
}
func (h *UserHandler) UpdateProfilePicture(ctx context.Context, req *connect.Request[userv1.UpdateProfilePictureRequest]) (*connect.Response[userv1.UpdateProfilePictureResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Validate file
fileType := http.DetectContentType(req.Msg.Data)
if fileType != "image/jpeg" && fileType != "image/png" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("invalid file type"))
}
// Save bytes into file
file := models.File{
Name: req.Msg.FileName,
Data: req.Msg.Data,
UserID: uint(userid),
}
if err := h.db.Create(&file).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Get user info
user := models.User{}
if err := h.db.First(&user, "id = ?", userid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Get old profile picture ID
var ppid *uint32
if user.ProfilePicture != nil {
ppid = &user.ProfilePicture.ID
}
// Update user profile picture
fid := uint(file.ID)
user.ProfilePictureID = &fid
user.ProfilePicture = &file
if err := h.db.Save(&user).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Delete old profile picture if exists
if ppid != nil {
if err := h.db.Delete(models.File{}, "id = ?", *ppid).Error; err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
}
res := connect.NewResponse(&userv1.UpdateProfilePictureResponse{
User: user.ToConnectV1(),
})
return res, nil
}
func NewUserHandler(db *gorm.DB, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewAuthInterceptor(key))
return userv1connect.NewUserServiceHandler(
&UserHandler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -0,0 +1,227 @@
package user
import (
"context"
"database/sql"
"errors"
"net/http"
"strconv"
"time"
_ "crypto/sha256" // Crypto
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
userv1 "github.com/spotdemo4/trevstack/server/internal/connect/user/v1"
"github.com/spotdemo4/trevstack/server/internal/connect/user/v1/userv1connect"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/sqlc"
"golang.org/x/crypto/bcrypt"
)
type AuthHandler struct {
db *sqlc.Queries
key []byte
}
func (h *AuthHandler) Login(ctx context.Context, req *connect.Request[userv1.LoginRequest]) (*connect.Response[userv1.LoginResponse], error) {
// Get user
user, err := h.db.GetUserbyUsername(ctx, req.Msg.Username)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodePermissionDenied, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
// Check password
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.Password)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid username or password"))
}
// Generate JWT
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "trevstack",
Subject: strconv.FormatInt(user.ID, 10),
IssuedAt: &jwt.NumericDate{
Time: time.Now(),
},
ExpiresAt: &jwt.NumericDate{
Time: time.Now().Add(time.Hour * 24),
},
})
ss, err := t.SignedString(h.key)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Create cookie
cookie := http.Cookie{
Name: "token",
Value: ss,
Path: "/",
MaxAge: 86400,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
res := connect.NewResponse(&userv1.LoginResponse{
Token: ss,
})
res.Header().Set("Set-Cookie", cookie.String())
return res, nil
}
func (h *AuthHandler) SignUp(ctx context.Context, req *connect.Request[userv1.SignUpRequest]) (*connect.Response[userv1.SignUpResponse], error) {
// Get user
_, err := h.db.GetUserbyUsername(ctx, req.Msg.Username)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeInternal, err)
}
} else {
return nil, connect.NewError(connect.CodeAlreadyExists, err)
}
// Check if confirmation passwords match
if req.Msg.Password != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.Password), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Create user
_, err = h.db.InsertUser(ctx, sqlc.InsertUserParams{
Username: req.Msg.Username,
Password: string(hash),
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.SignUpResponse{})
return res, nil
}
func (h *AuthHandler) Logout(_ context.Context, _ *connect.Request[userv1.LogoutRequest]) (*connect.Response[userv1.LogoutResponse], error) {
// Clear cookie
cookie := http.Cookie{
Name: "token",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
res := connect.NewResponse(&userv1.LogoutResponse{})
res.Header().Set("Set-Cookie", cookie.String())
return res, nil
}
// func (h *AuthHandler) GetPasskeyIDs(_ context.Context, req *connect.Request[userv1.GetPasskeyIDsRequest]) (*connect.Response[userv1.GetPasskeyIDsResponse], error) {
// // Get user
// user := models.User{}
// if err := h.db.Preload("Passkeys").First(&user, "username = ?", req.Msg.Username).Error; err != nil {
// return nil, connect.NewError(connect.CodeNotFound, err)
// }
// // Get IDs
// ids := []string{}
// for _, passkey := range user.Passkeys {
// ids = append(ids, passkey.ID)
// }
// return connect.NewResponse(&userv1.GetPasskeyIDsResponse{
// PasskeyIds: ids,
// }), nil
// }
// func (h *AuthHandler) PasskeyLogin(_ context.Context, req *connect.Request[userv1.PasskeyLoginRequest]) (*connect.Response[userv1.PasskeyLoginResponse], error) {
// // Get passkey
// passkey := models.Passkey{}
// if err := h.db.First(&passkey, "id = ?", req.Msg.Id).Error; err != nil {
// return nil, connect.NewError(connect.CodeNotFound, err)
// }
// // create a verifier from a trusted private key
// var verifier cose.Verifier
// var err error
// switch req.Msg.Algorithm {
// case -7:
// verifier, err = cose.NewVerifier(cose.AlgorithmES256, passkey.PublicKey)
// case -257:
// verifier, err = cose.NewVerifier(cose.AlgorithmRS256, passkey.PublicKey)
// default:
// return nil, connect.NewError(connect.CodeInternal, errors.New("decode algorithm not implemented"))
// }
// if err != nil {
// return nil, connect.NewError(connect.CodeInternal, err)
// }
// // create a sign message from a raw signature payload
// var msg cose.Sign1Message
// if err = msg.UnmarshalCBOR(req.Msg.Signature); err != nil {
// return nil, connect.NewError(connect.CodeInternal, err)
// }
// // Validate passkey
// err = msg.Verify(nil, verifier)
// if err != nil {
// return nil, connect.NewError(connect.CodeUnauthenticated, err)
// }
// // Generate JWT
// t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
// Issuer: "trevstack",
// Subject: strconv.FormatUint(uint64(passkey.UserID), 10),
// IssuedAt: &jwt.NumericDate{
// Time: time.Now(),
// },
// ExpiresAt: &jwt.NumericDate{
// Time: time.Now().Add(time.Hour * 24),
// },
// })
// ss, err := t.SignedString(h.key)
// if err != nil {
// return nil, connect.NewError(connect.CodeInternal, err)
// }
// // Create cookie
// cookie := http.Cookie{
// Name: "token",
// Value: ss,
// Path: "/",
// MaxAge: 86400,
// HttpOnly: true,
// Secure: true,
// SameSite: http.SameSiteStrictMode,
// }
// res := connect.NewResponse(&userv1.PasskeyLoginResponse{
// Token: ss,
// })
// res.Header().Set("Set-Cookie", cookie.String())
// return res, nil
// }
func NewAuthHandler(db *sqlc.Queries, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewRateLimitInterceptor(key))
return userv1connect.NewAuthServiceHandler(
&AuthHandler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -0,0 +1,275 @@
package user
import (
"context"
"database/sql"
"errors"
"net/http"
"strconv"
"time"
"connectrpc.com/connect"
"github.com/golang-jwt/jwt/v5"
userv1 "github.com/spotdemo4/trevstack/server/internal/connect/user/v1"
"github.com/spotdemo4/trevstack/server/internal/connect/user/v1/userv1connect"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
"github.com/spotdemo4/trevstack/server/internal/sqlc"
"github.com/spotdemo4/trevstack/server/internal/util"
"golang.org/x/crypto/bcrypt"
)
func userToConnect(item sqlc.User) *userv1.User {
return &userv1.User{
Id: item.ID,
Username: item.Username,
ProfilePictureId: item.ProfilePictureID,
}
}
type Handler struct {
db *sqlc.Queries
key []byte
}
func (h *Handler) GetUser(ctx context.Context, _ *connect.Request[userv1.GetUserRequest]) (*connect.Response[userv1.GetUserResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user, err := h.db.GetUser(ctx, userid)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.GetUserResponse{
User: userToConnect(user),
})
return res, nil
}
func (h *Handler) UpdatePassword(ctx context.Context, req *connect.Request[userv1.UpdatePasswordRequest]) (*connect.Response[userv1.UpdatePasswordResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user, err := h.db.GetUser(ctx, userid)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
// Validate
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.OldPassword)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid password"))
}
if req.Msg.NewPassword != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(req.Msg.NewPassword), bcrypt.DefaultCost)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Update password
err = h.db.UpdateUser(ctx, sqlc.UpdateUserParams{
Password: util.ToPointer(string(hash)),
ID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.UpdatePasswordResponse{})
return res, nil
}
func (h *Handler) GetAPIKey(ctx context.Context, req *connect.Request[userv1.GetAPIKeyRequest]) (*connect.Response[userv1.GetAPIKeyResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Get user
user, err := h.db.GetUser(ctx, userid)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
// Validate
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Msg.Password)); err != nil {
return nil, connect.NewError(connect.CodePermissionDenied, errors.New("invalid username or password"))
}
if req.Msg.Password != req.Msg.ConfirmPassword {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("passwords do not match"))
}
// Generate JWT
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Issuer: "trevstack",
Subject: strconv.FormatInt(user.ID, 10),
IssuedAt: &jwt.NumericDate{
Time: time.Now(),
},
})
ss, err := t.SignedString(h.key)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
res := connect.NewResponse(&userv1.GetAPIKeyResponse{
Key: ss,
})
return res, nil
}
func (h *Handler) UpdateProfilePicture(ctx context.Context, req *connect.Request[userv1.UpdateProfilePictureRequest]) (*connect.Response[userv1.UpdateProfilePictureResponse], error) {
userid, ok := interceptors.GetUserContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated"))
}
// Validate file
fileType := http.DetectContentType(req.Msg.Data)
if fileType != "image/jpeg" && fileType != "image/png" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("invalid file type"))
}
// Save bytes into file
fileID, err := h.db.InsertFile(ctx, sqlc.InsertFileParams{
Name: req.Msg.FileName,
Data: req.Msg.Data,
UserID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Get user
user, err := h.db.GetUser(ctx, userid)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return nil, connect.NewError(connect.CodeInternal, err)
}
// Update user profile picture
err = h.db.UpdateUser(ctx, sqlc.UpdateUserParams{
// set
ProfilePictureID: &fileID,
// where
ID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
// Delete old profile picture if exists
if user.ProfilePictureID != nil {
err = h.db.DeleteFile(ctx, sqlc.DeleteFileParams{
ID: *user.ProfilePictureID,
UserID: userid,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
}
res := connect.NewResponse(&userv1.UpdateProfilePictureResponse{
User: userToConnect(user),
})
return res, nil
}
// func (h *Handler) BeginPasskeyRegistration(ctx context.Context, req *connect.Request[userv1.BeginPasskeyRegistrationRequest]) (*connect.Response[userv1.BeginPasskeyRegistrationResponse], error) {
// // Get user ID from context
// userid, ok := interceptors.GetUserContext(ctx)
// if !ok {
// return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("user not authenticated"))
// }
// // Get user
// user := models.User{}
// if err := h.db.First(&user, "id = ?", userid).Error; err != nil {
// return nil, connect.NewError(connect.CodeInternal, err)
// }
// return connect.NewResponse(&userv1.BeginPasskeyRegistrationResponse{}), nil
// }
// func (h *Handler) FinishPasskeyRegistration(ctx context.Context, req *connect.Request[userv1.FinishPasskeyRegistrationRequest]) (*connect.Response[userv1.FinishPasskeyRegistrationResponse], error) {
// // Get user ID from context
// userid, ok := interceptors.GetUserContext(ctx)
// if !ok {
// return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("user not authenticated"))
// }
// // Get user
// user := models.User{}
// if err := h.db.First(&user, "id = ?", userid).Error; err != nil {
// return nil, connect.NewError(connect.CodeInternal, err)
// }
// return connect.NewResponse(&userv1.FinishPasskeyRegistrationResponse{}), nil
// }
// func BeginRegistration(ctx context.Context) error {
// userid, ok := interceptors.GetUserContext(ctx)
// if !ok {
// return nil
// }
// wconfig := &webauthn.Config{
// RPDisplayName: "Go Webauthn", // Display Name for your site
// RPID: "go-webauthn.local", // Generally the FQDN for your site
// RPOrigins: []string{"https://login.go-webauthn.local"}, // The origin URLs allowed for WebAuthn requests
// }
// webAuthn, err := webauthn.New(wconfig)
// if err != nil {
// return nil
// }
// var user webauthn.User
// user.WebAuthnCredentials()
// var cred webauthn.Credential
// cred.Verify()
// var test metadata.Provider
// test.
// options, session, err := webAuthn.BeginRegistration(user)
// return nil
// }
func NewHandler(db *sqlc.Queries, key string) (string, http.Handler) {
interceptors := connect.WithInterceptors(interceptors.NewAuthInterceptor(key))
return userv1connect.NewUserServiceHandler(
&Handler{
db: db,
key: []byte(key),
},
interceptors,
)
}

View File

@ -6,6 +6,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
@ -49,10 +50,7 @@ func WithAuthRedirect(next http.Handler, key string) http.Handler {
}
next.ServeHTTP(w, r)
case "_app":
next.ServeHTTP(w, r)
case "favicon.png":
case "_app", "favicon.png", "icon.png":
next.ServeHTTP(w, r)
default:
@ -62,22 +60,23 @@ func WithAuthRedirect(next http.Handler, key string) http.Handler {
}
// Redirect if not authenticated
http.Redirect(w, r, "/auth", http.StatusFound)
pathRedir := url.QueryEscape(r.URL.Path)
http.Redirect(w, r, fmt.Sprintf("/auth?redir=%s", pathRedir), http.StatusFound)
}
})
}
type authInterceptor struct {
type AuthInterceptor struct {
key string
}
func NewAuthInterceptor(key string) *authInterceptor {
return &authInterceptor{
func NewAuthInterceptor(key string) *AuthInterceptor {
return &AuthInterceptor{
key: key,
}
}
func (i *authInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
func (i *AuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
// Same as previous UnaryInterceptorFunc.
return connect.UnaryFunc(func(
ctx context.Context,
@ -121,7 +120,7 @@ func (i *authInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
})
}
func (*authInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
func (*AuthInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return connect.StreamingClientFunc(func(
ctx context.Context,
spec connect.Spec,
@ -130,7 +129,7 @@ func (*authInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) co
})
}
func (i *authInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
func (i *AuthInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
return connect.StreamingHandlerFunc(func(
ctx context.Context,
conn connect.StreamingHandlerConn,
@ -218,7 +217,7 @@ func validateToken(tokenString string, key string) (subject string, err error) {
// key is an unexported type for keys defined in this package.
// This prevents collisions with keys defined in other packages.
type key int
type key int64
// userKey is the key for user.User values in Contexts. It is
// unexported; clients use user.NewContext and user.FromContext
@ -232,11 +231,11 @@ func newUserContext(ctx context.Context, subject string) (context.Context, error
return nil, err
}
return context.WithValue(ctx, userKey, id), nil
return context.WithValue(ctx, userKey, int64(id)), nil
}
// getUserContext returns the User value stored in ctx, if any.
func GetUserContext(ctx context.Context) (int, bool) {
u, ok := ctx.Value(userKey).(int)
func GetUserContext(ctx context.Context) (int64, bool) {
u, ok := ctx.Value(userKey).(int64)
return u, ok
}

View File

@ -0,0 +1,19 @@
package interceptors
import (
"net/http"
connectcors "connectrpc.com/cors"
"github.com/rs/cors"
)
// WithCORS adds CORS support to a Connect HTTP handler.
func WithCORS(pattern string, h http.Handler) (string, http.Handler) {
middleware := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: connectcors.AllowedMethods(),
AllowedHeaders: connectcors.AllowedHeaders(),
ExposedHeaders: connectcors.ExposedHeaders(),
})
return pattern, middleware.Handler(h)
}

View File

@ -15,14 +15,14 @@ type visitor struct {
lastSeen time.Time
}
type ratelimitInterceptor struct {
type RatelimitInterceptor struct {
key string
visitors map[string]*visitor
mu sync.Mutex
}
func NewRateLimitInterceptor(key string) *ratelimitInterceptor {
rl := &ratelimitInterceptor{
func NewRateLimitInterceptor(key string) *RatelimitInterceptor {
rl := &RatelimitInterceptor{
key: key,
visitors: make(map[string]*visitor),
mu: sync.Mutex{},
@ -33,7 +33,7 @@ func NewRateLimitInterceptor(key string) *ratelimitInterceptor {
return rl
}
func (i *ratelimitInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
func (i *RatelimitInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
// Same as previous UnaryInterceptorFunc.
return connect.UnaryFunc(func(
ctx context.Context,
@ -46,7 +46,7 @@ func (i *ratelimitInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFu
// Get user agent
limiter := i.getVisitor(req.Header().Get("User-Agent"))
if limiter.Allow() == false {
if !limiter.Allow() {
return nil, connect.NewError(connect.CodeResourceExhausted, errors.New("rate limit exceeded"))
}
@ -54,7 +54,7 @@ func (i *ratelimitInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFu
})
}
func (*ratelimitInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
func (*RatelimitInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
return connect.StreamingClientFunc(func(
ctx context.Context,
spec connect.Spec,
@ -63,14 +63,14 @@ func (*ratelimitInterceptor) WrapStreamingClient(next connect.StreamingClientFun
})
}
func (i *ratelimitInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
func (i *RatelimitInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
return connect.StreamingHandlerFunc(func(
ctx context.Context,
conn connect.StreamingHandlerConn,
) error {
// Get user agent
limiter := i.getVisitor(conn.RequestHeader().Get("User-Agent"))
if limiter.Allow() == false {
if !limiter.Allow() {
return connect.NewError(connect.CodeResourceExhausted, errors.New("rate limit exceeded"))
}
@ -78,7 +78,7 @@ func (i *ratelimitInterceptor) WrapStreamingHandler(next connect.StreamingHandle
})
}
func (i *ratelimitInterceptor) getVisitor(userAgent string) *rate.Limiter {
func (i *RatelimitInterceptor) getVisitor(userAgent string) *rate.Limiter {
i.mu.Lock()
defer i.mu.Unlock()
@ -97,7 +97,7 @@ func (i *ratelimitInterceptor) getVisitor(userAgent string) *rate.Limiter {
// Every minute check the map for visitors that haven't been seen for
// more than 3 minutes and delete the entries.
func (i *ratelimitInterceptor) cleanupVisitors() {
func (i *RatelimitInterceptor) cleanupVisitors() {
for {
time.Sleep(time.Minute)

View File

@ -1,12 +0,0 @@
package models
type File struct {
ID uint32 `gorm:"primaryKey"`
Name string
Data []byte
// User
UserID uint
User User
}

View File

@ -1,33 +0,0 @@
package models
import (
"time"
itemv1 "github.com/spotdemo4/trevstack/server/internal/services/item/v1"
"google.golang.org/protobuf/types/known/timestamppb"
)
type Item struct {
ID uint32 `gorm:"primaryKey"`
Name string
Description string
Price float32
Quantity int
Added time.Time
// User
UserID uint
User User
}
func (i Item) ToConnectV1() *itemv1.Item {
return &itemv1.Item{
Id: &i.ID,
Name: i.Name,
Description: i.Description,
Price: i.Price,
Quantity: uint32(i.Quantity),
Added: timestamppb.New(i.Added),
}
}

View File

@ -1,32 +0,0 @@
package models
import (
"fmt"
userv1 "github.com/spotdemo4/trevstack/server/internal/services/user/v1"
)
type User struct {
ID uint32 `gorm:"primaryKey"`
Username string
Password string
// Profile picture
ProfilePictureID *uint
ProfilePicture *File
}
func (u User) ToConnectV1() *userv1.User {
var ppid *string
if u.ProfilePicture != nil {
id := fmt.Sprintf("/file/%d", u.ProfilePicture.ID)
ppid = &id
}
return &userv1.User{
Id: u.ID,
Username: u.Username,
ProfilePicture: ppid,
}
}

View File

@ -0,0 +1,31 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
package sqlc
import (
"context"
"database/sql"
)
type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
return &Queries{
db: tx,
}
}

View File

@ -0,0 +1,113 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: file.sql
package sqlc
import (
"context"
)
const deleteFile = `-- name: DeleteFile :exec
DELETE FROM file
WHERE
id = ?1
AND
user_id = ?2
`
type DeleteFileParams struct {
ID int64
UserID int64
}
func (q *Queries) DeleteFile(ctx context.Context, arg DeleteFileParams) error {
_, err := q.db.ExecContext(ctx, deleteFile, arg.ID, arg.UserID)
return err
}
const getFile = `-- name: GetFile :one
SELECT
id,
name,
data,
user_id
FROM file
WHERE
id = ?1
AND
user_id = ?2
LIMIT 1
`
type GetFileParams struct {
ID int64
UserID int64
}
func (q *Queries) GetFile(ctx context.Context, arg GetFileParams) (File, error) {
row := q.db.QueryRowContext(ctx, getFile, arg.ID, arg.UserID)
var i File
err := row.Scan(
&i.ID,
&i.Name,
&i.Data,
&i.UserID,
)
return i, err
}
const insertFile = `-- name: InsertFile :one
INSERT INTO file (
name,
data,
user_id
) VALUES (
?1,
?2,
?3
)
RETURNING id
`
type InsertFileParams struct {
Name string
Data []byte
UserID int64
}
func (q *Queries) InsertFile(ctx context.Context, arg InsertFileParams) (int64, error) {
row := q.db.QueryRowContext(ctx, insertFile, arg.Name, arg.Data, arg.UserID)
var id int64
err := row.Scan(&id)
return id, err
}
const updateFile = `-- name: UpdateFile :exec
UPDATE file
SET
name = COALESCE(?1, name),
data = COALESCE(?2, data)
WHERE
id = ?3
AND
user_id = ?4
`
type UpdateFileParams struct {
Name *string
Data []byte
ID int64
UserID int64
}
func (q *Queries) UpdateFile(ctx context.Context, arg UpdateFileParams) error {
_, err := q.db.ExecContext(ctx, updateFile,
arg.Name,
arg.Data,
arg.ID,
arg.UserID,
)
return err
}

View File

@ -0,0 +1,250 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: item.sql
package sqlc
import (
"context"
"time"
)
const deleteItem = `-- name: DeleteItem :exec
DELETE FROM item
WHERE
id = ?1
AND
user_id = ?2
`
type DeleteItemParams struct {
ID int64
UserID int64
}
func (q *Queries) DeleteItem(ctx context.Context, arg DeleteItemParams) error {
_, err := q.db.ExecContext(ctx, deleteItem, arg.ID, arg.UserID)
return err
}
const getItem = `-- name: GetItem :one
SELECT
id,
name,
added,
description,
price,
quantity,
user_id
FROM item
WHERE
id = ?1
AND
user_id = ?2
LIMIT 1
`
type GetItemParams struct {
ID int64
UserID int64
}
func (q *Queries) GetItem(ctx context.Context, arg GetItemParams) (Item, error) {
row := q.db.QueryRowContext(ctx, getItem, arg.ID, arg.UserID)
var i Item
err := row.Scan(
&i.ID,
&i.Name,
&i.Added,
&i.Description,
&i.Price,
&i.Quantity,
&i.UserID,
)
return i, err
}
const getItems = `-- name: GetItems :many
SELECT
id,
name,
added,
description,
price,
quantity,
user_id
FROM item
WHERE
user_id = ?1
AND
(
(name LIKE ?2 OR ?2 IS NULL)
AND
(added >= ?3 OR ?3 IS NULL)
AND
(added <= ?4 OR ?4 IS NULL)
)
LIMIT
?6
OFFSET
?5
`
type GetItemsParams struct {
UserID int64
Name *string
Start *time.Time
End *time.Time
Offset int64
Limit int64
}
func (q *Queries) GetItems(ctx context.Context, arg GetItemsParams) ([]Item, error) {
rows, err := q.db.QueryContext(ctx, getItems,
arg.UserID,
arg.Name,
arg.Start,
arg.End,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Item
for rows.Next() {
var i Item
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Added,
&i.Description,
&i.Price,
&i.Quantity,
&i.UserID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getItemsCount = `-- name: GetItemsCount :one
SELECT COUNT(id)
FROM item
WHERE
user_id = ?1
AND
(
(name LIKE ?2 OR ?2 IS NULL)
AND
(added >= ?3 OR ?3 IS NULL)
AND
(added <= ?4 OR ?4 IS NULL)
)
LIMIT 1
`
type GetItemsCountParams struct {
UserID int64
Name *string
Start *time.Time
End *time.Time
}
func (q *Queries) GetItemsCount(ctx context.Context, arg GetItemsCountParams) (int64, error) {
row := q.db.QueryRowContext(ctx, getItemsCount,
arg.UserID,
arg.Name,
arg.Start,
arg.End,
)
var count int64
err := row.Scan(&count)
return count, err
}
const insertItem = `-- name: InsertItem :one
INSERT INTO item (
name,
added,
description,
price,
quantity,
user_id
) VALUES (
?1,
?2,
?3,
?4,
?5,
?6
)
RETURNING id
`
type InsertItemParams struct {
Name string
Added time.Time
Description string
Price float64
Quantity int64
UserID int64
}
func (q *Queries) InsertItem(ctx context.Context, arg InsertItemParams) (int64, error) {
row := q.db.QueryRowContext(ctx, insertItem,
arg.Name,
arg.Added,
arg.Description,
arg.Price,
arg.Quantity,
arg.UserID,
)
var id int64
err := row.Scan(&id)
return id, err
}
const updateItem = `-- name: UpdateItem :exec
UPDATE item
SET
name = COALESCE(?1, name),
description = COALESCE(?2, description),
price = COALESCE(?3, price),
quantity = COALESCE(?4, quantity)
WHERE
id = ?5
AND
user_id = ?6
`
type UpdateItemParams struct {
Name *string
Description *string
Price *float64
Quantity *int64
ID int64
UserID int64
}
func (q *Queries) UpdateItem(ctx context.Context, arg UpdateItemParams) error {
_, err := q.db.ExecContext(ctx, updateItem,
arg.Name,
arg.Description,
arg.Price,
arg.Quantity,
arg.ID,
arg.UserID,
)
return err
}

View File

@ -0,0 +1,37 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
package sqlc
import (
"time"
)
type File struct {
ID int64
Name string
Data []byte
UserID int64
}
type Item struct {
ID int64
Name string
Added time.Time
Description string
Price float64
Quantity int64
UserID int64
}
type SchemaMigration struct {
Version string
}
type User struct {
ID int64
Username string
Password string
ProfilePictureID *int64
}

View File

@ -0,0 +1,120 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: user.sql
package sqlc
import (
"context"
)
const deleteUser = `-- name: DeleteUser :exec
DELETE FROM user
WHERE id = ?1
`
func (q *Queries) DeleteUser(ctx context.Context, id int64) error {
_, err := q.db.ExecContext(ctx, deleteUser, id)
return err
}
const getUser = `-- name: GetUser :one
SELECT
id,
username,
password,
profile_picture_id
FROM user
WHERE
id = ?1
LIMIT 1
`
func (q *Queries) GetUser(ctx context.Context, id int64) (User, error) {
row := q.db.QueryRowContext(ctx, getUser, id)
var i User
err := row.Scan(
&i.ID,
&i.Username,
&i.Password,
&i.ProfilePictureID,
)
return i, err
}
const getUserbyUsername = `-- name: GetUserbyUsername :one
SELECT
id,
username,
password,
profile_picture_id
FROM user
WHERE
username = ?1
LIMIT 1
`
func (q *Queries) GetUserbyUsername(ctx context.Context, username string) (User, error) {
row := q.db.QueryRowContext(ctx, getUserbyUsername, username)
var i User
err := row.Scan(
&i.ID,
&i.Username,
&i.Password,
&i.ProfilePictureID,
)
return i, err
}
const insertUser = `-- name: InsertUser :one
INSERT INTO user (
username,
password
) VALUES (
?1,
?2
)
RETURNING id
`
type InsertUserParams struct {
Username string
Password string
}
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) (int64, error) {
row := q.db.QueryRowContext(ctx, insertUser, arg.Username, arg.Password)
var id int64
err := row.Scan(&id)
return id, err
}
const updateUser = `-- name: UpdateUser :exec
UPDATE user
SET
username = COALESCE(?1, username),
password = COALESCE(?2, password),
profile_picture_id = COALESCE(
?3,
profile_picture_id
)
WHERE id = ?4
`
type UpdateUserParams struct {
Username *string
Password *string
ProfilePictureID *int64
ID int64
}
func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) error {
_, err := q.db.ExecContext(ctx, updateUser,
arg.Username,
arg.Password,
arg.ProfilePictureID,
arg.ID,
)
return err
}

View File

@ -0,0 +1,17 @@
package util
func DerefOrEmpty[T any](val *T) T {
if val == nil {
var empty T
return empty
}
return *val
}
func IsNotNil[T any](val *T) bool {
return val != nil
}
func ToPointer[T any](val T) *T {
return &val
}

View File

@ -0,0 +1,44 @@
package util
import (
"fmt"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
)
func NullLike(s *string) *string {
if s == nil {
return nil
}
ts := fmt.Sprintf("%%%s%%", *s)
return &ts
}
func NullTimestamp(ts *timestamppb.Timestamp) *time.Time {
if ts == nil {
return nil
}
t := ts.AsTime()
return &t
}
func NullFloat64(f *float32) *float64 {
if f == nil {
return nil
}
f64 := float64(*f)
return &f64
}
func NullInt64(i *int32) *int64 {
if i == nil {
return nil
}
i64 := int64(*i)
return &i64
}

View File

@ -1,120 +1,66 @@
// TrevStack HTTP Server
package main
import (
"context"
"embed"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
connectcors "connectrpc.com/cors"
"github.com/joho/godotenv"
"github.com/rs/cors"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"gorm.io/gorm"
"github.com/spotdemo4/trevstack/server/internal/database"
"github.com/spotdemo4/trevstack/server/internal/handlers"
"github.com/spotdemo4/trevstack/server/internal/handlers/client"
"github.com/spotdemo4/trevstack/server/internal/handlers/file"
"github.com/spotdemo4/trevstack/server/internal/handlers/item/v1"
"github.com/spotdemo4/trevstack/server/internal/handlers/user/v1"
"github.com/spotdemo4/trevstack/server/internal/interceptors"
)
type env struct {
DBType string
DBUser string
DBPass string
DBHost string
DBPort string
DBName string
Port string
Key string
}
var clientFS *embed.FS
var dbFS *embed.FS
func main() {
err := godotenv.Load()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{}))
slog.SetDefault(logger)
// Get env
env, err := getEnv()
if err != nil {
log.Println("Failed to load .env file, using environment variables")
log.Fatal(err.Error())
}
// Get environment variables for server
env := env{
DBType: os.Getenv("DB_TYPE"),
DBUser: os.Getenv("DB_USER"),
DBPass: os.Getenv("DB_PASS"),
DBHost: os.Getenv("DB_HOST"),
DBPort: os.Getenv("DB_PORT"),
DBName: os.Getenv("DB_NAME"),
Port: os.Getenv("PORT"),
Key: os.Getenv("KEY"),
}
if env.Port == "" {
env.Port = "8080"
}
if env.Key == "" {
log.Fatal("KEY is required")
// Migrate database
err = database.Migrate(env.DatabaseURL, dbFS)
if err != nil {
log.Fatal(err.Error())
}
// Get environment variables for database
db := &gorm.DB{}
switch env.DBType {
case "postgres":
log.Println("Using Postgres")
if env.DBUser == "" {
log.Fatal("DB_USER is required")
}
if env.DBPass == "" {
log.Fatal("DB_PASS is required")
}
if env.DBHost == "" {
log.Fatal("DB_HOST is required")
}
if env.DBPort == "" {
log.Fatal("DB_PORT is required")
}
if env.DBName == "" {
log.Fatal("DB_NAME is required")
}
db, err = database.NewPostgresConnection(env.DBUser, env.DBPass, env.DBHost, env.DBPort, env.DBName)
if err != nil {
log.Fatalf("failed to connect to postgres: %v", err)
}
case "sqlite":
log.Println("Using SQLite")
if env.DBName == "" {
log.Fatal("DB_NAME is required")
}
db, err = database.NewSQLiteConnection(env.DBName)
if err != nil {
log.Fatalf("failed to connect to sqlite: %v", err)
}
default:
log.Fatal("DB_TYPE must be either postgres or sqlite")
}
// Init database
if err := database.Migrate(db); err != nil {
log.Fatalf("failed to migrate database: %v", err)
// Get database
sqlc, db, err := database.New(env.DatabaseURL)
if err != nil {
log.Fatalf("failed to connect to database: %s", err.Error())
}
// Serve GRPC Handlers
api := http.NewServeMux()
api.Handle(withCORS(handlers.NewAuthHandler(db, env.Key)))
api.Handle(withCORS(handlers.NewUserHandler(db, env.Key)))
api.Handle(withCORS(handlers.NewItemHandler(db, env.Key)))
api.Handle(interceptors.WithCORS(user.NewAuthHandler(sqlc, env.Key)))
api.Handle(interceptors.WithCORS(user.NewHandler(sqlc, env.Key)))
api.Handle(interceptors.WithCORS(item.NewHandler(sqlc, env.Key)))
// Serve web interface
mux := http.NewServeMux()
mux.Handle("/", client.NewClientHandler(env.Key))
mux.Handle("/file/", handlers.NewFileHandler(db, env.Key))
mux.Handle("/", client.NewClientHandler(env.Key, clientFS))
mux.Handle("/file/", file.NewFileHandler(sqlc, env.Key))
mux.Handle("/grpc/", http.StripPrefix("/grpc", api))
// Start server
@ -129,8 +75,7 @@ func main() {
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
log.Printf("Received signal %s", sig)
log.Println("Exiting")
slog.Warn(fmt.Sprintf("Received signal %s, exiting", sig))
// Close HTTP server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@ -140,10 +85,7 @@ func main() {
cancel()
// Close database connection
sqlDB, err := db.DB() // Get underlying SQL database
if err == nil {
sqlDB.Close()
}
db.Close()
}()
if err := server.ListenAndServe(); err != nil {
@ -151,13 +93,35 @@ func main() {
}
}
// withCORS adds CORS support to a Connect HTTP handler.
func withCORS(pattern string, h http.Handler) (string, http.Handler) {
middleware := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: connectcors.AllowedMethods(),
AllowedHeaders: connectcors.AllowedHeaders(),
ExposedHeaders: connectcors.ExposedHeaders(),
})
return pattern, middleware.Handler(h)
type env struct {
Port string
Key string
DatabaseURL string
}
func getEnv() (*env, error) {
err := godotenv.Load()
if err != nil {
slog.Warn("Failed to load .env file, using environment variables")
}
// Create
env := env{
Port: os.Getenv("PORT"),
Key: os.Getenv("KEY"),
DatabaseURL: os.Getenv("DATABASE_URL"),
}
// Validate
if env.Port == "" {
env.Port = "8080"
}
if env.Key == "" {
return nil, errors.New("env 'key' not found")
}
if env.DatabaseURL == "" {
return nil, errors.New("env 'DATABASE_URL' not found")
}
return &env, nil
}

20
server/prod.go Normal file
View File

@ -0,0 +1,20 @@
//go:build !dev
package main
import (
"embed"
"log"
)
//go:embed all:client
var cFS embed.FS
//go:embed db/migrations/*.sql
var dFS embed.FS
func init() {
log.Println("initializing for production")
clientFS = &cFS
dbFS = &dFS
}

27
server/revive.toml Normal file
View File

@ -0,0 +1,27 @@
ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8
errorCode = 0
warningCode = 0
[rule.blank-imports]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
[rule.error-return]
[rule.error-strings]
[rule.error-naming]
[rule.increment-decrement]
[rule.var-naming]
[rule.var-declaration]
[rule.range]
[rule.receiver-naming]
[rule.time-naming]
[rule.unexported-return]
[rule.indent-error-flow]
[rule.errorf]
[rule.empty-block]
[rule.superfluous-else]
[rule.unused-parameter]
[rule.unreachable-code]
[rule.redefines-builtin-id]

14
server/sqlc.yaml Normal file
View File

@ -0,0 +1,14 @@
version: "2"
sql:
- engine: "sqlite"
queries: "db/queries"
schema: "db/schema.sql"
gen:
go:
package: "sqlc"
out: "internal/sqlc"
emit_pointers_for_null_types: true
database:
uri: ${DATABASE_URL}
rules:
- sqlc/db-prepare