Security added on delete service and list all node + cleaning some code
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
FROM golang:1.22 AS builder
|
||||
FROM golang:1.24 AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
module backend
|
||||
|
||||
go 1.22
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.11
|
||||
|
||||
require github.com/gorilla/mux v1.8.1
|
||||
|
||||
@ -8,4 +10,42 @@ require github.com/rs/cors v1.11.1
|
||||
|
||||
require github.com/lib/pq v1.10.9
|
||||
|
||||
require github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
require (
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sessions v1.0.4 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/gin-gonic/gin v1.11.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/mod v0.30.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.39.0 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
)
|
||||
|
||||
@ -1,11 +1,102 @@
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
github.com/gin-contrib/sessions v1.0.4 h1:ha6CNdpYiTOK/hTp05miJLbpTSNfOnFg5Jm2kbcqy8U=
|
||||
github.com/gin-contrib/sessions v1.0.4/go.mod h1:ccmkrb2z6iU2osiAHZG3x3J4suJK+OU27oqzlWOqQgs=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
|
||||
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/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.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
12
backend/handlers/login_handler.go
Normal file
12
backend/handlers/login_handler.go
Normal file
@ -0,0 +1,12 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (r *NodeHandler) LoginHandler(c *gin.Context) {
|
||||
log.Println("trying to login")
|
||||
r.Repo.LoginHandler(c)
|
||||
}
|
||||
@ -7,115 +7,51 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
type NodeHandler struct {
|
||||
Repo *repositories.NodeRepository // On stocke le repo ici
|
||||
Repo *repositories.NodeRepository
|
||||
}
|
||||
|
||||
var registeredNodes = make(map[string]models.NodeInfo)
|
||||
|
||||
func (h *NodeHandler) HandleRegisterNode(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
func (h *NodeHandler) HandleRegisterNode(c *gin.Context) {
|
||||
|
||||
var node models.NodeInfo
|
||||
err := json.NewDecoder(r.Body).Decode(&node)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
|
||||
if err := c.ShouldBindJSON(&node); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var nodeID int
|
||||
nodeID, err = h.Repo.RegisterNode(node)
|
||||
|
||||
nodeID, err := h.Repo.RegisterNode(node)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]int{"id": nodeID})
|
||||
c.JSON(http.StatusOK, gin.H{"id": nodeID})
|
||||
}
|
||||
|
||||
func (h *NodeHandler) HandleRetrieveNodeList(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
http.Error(w, "GET requested", http.StatusMethodNotAllowed)
|
||||
func (h *NodeHandler) HandleRetrieveNodeList(c *gin.Context) {
|
||||
|
||||
log.Println("All nodes retrieved request")
|
||||
|
||||
registeredNodes, err := h.Repo.RetriveNodeList()
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Request error on retrieving all nodes: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Impossible de récupérer la liste des nœuds"})
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("All node retrieved")
|
||||
|
||||
var registeredNodes = make(map[string]models.FullNodeInfo)
|
||||
var err error
|
||||
|
||||
registeredNodes, err = h.Repo.RetriveNodeList()
|
||||
|
||||
log.Printf("nb nodes: %v", len(registeredNodes))
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Request error on retrieving all node: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
err = json.NewEncoder(w).Encode(registeredNodes)
|
||||
if err != nil {
|
||||
log.Fatalf("Erreur lors de l'encodage JSON: %v", err)
|
||||
http.Error(w, "Erreur lors de l'encodage JSON", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, registeredNodes)
|
||||
}
|
||||
|
||||
/*func (h *NodeHandler) HandleUpdateNode(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var nodeUpdate models.NodeUpdate
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&nodeUpdate)
|
||||
if err != nil {
|
||||
http.Error(w, "Erreur lors du décodage du JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
h.UpdateNode(nodeUpdate)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status": "success"}`))
|
||||
}*/
|
||||
|
||||
func HandleUpdateNodes(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
UpdateNodes()
|
||||
}
|
||||
|
||||
/*func (h *NodeHandler) UpdateNode(nodeUpdate models.NodeUpdate) {
|
||||
node, found := registeredNodes[nodeUpdate.NodeId]
|
||||
if found {
|
||||
|
||||
updateServicesFromNode(&node)
|
||||
h.Repo.UpdateNodeLastSeen(nodeUpdate.NodeId)
|
||||
|
||||
for _, serviceUpdate := range nodeUpdate.Services {
|
||||
h.Repo.UpdateServiceStatus(serviceUpdate)
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
func HandleRetrieveNode(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" {
|
||||
http.Error(w, "GET requested", http.StatusMethodNotAllowed)
|
||||
@ -129,20 +65,14 @@ func HandleRetrieveNode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
node, found := registeredNodes[nodeID]
|
||||
if found {
|
||||
// 4. Node trouvé : le retourner au format JSON
|
||||
json.NewEncoder(w).Encode(node)
|
||||
} else {
|
||||
// 5. Node non trouvé : retourner une erreur 404
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
|
||||
// Optionnel : Retourner un message d'erreur clair
|
||||
errorResponse := map[string]string{"error": "Node non trouvé", "id": nodeID}
|
||||
json.NewEncoder(w).Encode(errorResponse)
|
||||
}
|
||||
}
|
||||
|
||||
func UpdateNodes() {
|
||||
/*for nodeId := range registeredNodes {
|
||||
updateNode(nodeId)
|
||||
}*/
|
||||
}
|
||||
|
||||
@ -2,132 +2,67 @@ package handlers
|
||||
|
||||
import (
|
||||
"backend/models"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
/*func retrieveServicesFromNode(node *models.NodeInfo) map[string]models.Service {
|
||||
|
||||
apiURL := node.Address + "/list"
|
||||
|
||||
resp, err := http.Get(apiURL)
|
||||
|
||||
log.Printf("retrieving node %s on address %s", node.Name, apiURL)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Erreur lors de la requête : %v", err)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Fatalf("Requête échouée avec le statut : %s", resp.Status)
|
||||
}
|
||||
|
||||
bodyBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Fatalf("Erreur lors de la lecture du corps de la réponse : %v", err)
|
||||
}
|
||||
|
||||
var services []models.Service
|
||||
|
||||
err = json.Unmarshal(bodyBytes, &services)
|
||||
if err != nil {
|
||||
log.Fatalf("Erreur lors du décodage JSON : %v", err)
|
||||
}
|
||||
|
||||
var result map[string]models.Service
|
||||
|
||||
for _, service := range services {
|
||||
result[service.Name] = service
|
||||
}
|
||||
|
||||
return result
|
||||
}*/
|
||||
|
||||
func (h *NodeHandler) HandleRegisterService(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
func (h *NodeHandler) HandleRegisterService(c *gin.Context) {
|
||||
var serviceRegister models.ServiceRegister
|
||||
err := json.NewDecoder(r.Body).Decode(&serviceRegister)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
|
||||
if err := c.ShouldBindJSON(&serviceRegister); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var serviceID int
|
||||
serviceID, err = h.Repo.RegisterService(serviceRegister.Service, serviceRegister.NodeId)
|
||||
|
||||
serviceID, err := h.Repo.RegisterService(serviceRegister.Service, serviceRegister.NodeId)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]int{"id": serviceID})
|
||||
c.JSON(http.StatusOK, gin.H{"id": serviceID})
|
||||
}
|
||||
|
||||
func (h *NodeHandler) HandleUpdateServiceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "POST requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
func (h *NodeHandler) HandleUpdateServiceStatus(c *gin.Context) {
|
||||
var serviceUpdate models.ServiceUpdateRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&serviceUpdate)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
|
||||
if err := c.ShouldBindJSON(&serviceUpdate); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.Repo.UpdateServiceStatus(serviceUpdate)
|
||||
|
||||
err := h.Repo.UpdateServiceStatus(serviceUpdate)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "updated"})
|
||||
}
|
||||
|
||||
/*func updateServicesFromNode(node *models.NodeInfo) {
|
||||
node.Services = retrieveServicesFromNode(node)
|
||||
}*/
|
||||
|
||||
func (h *NodeHandler) HandleDeleteService(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "DELETE" {
|
||||
http.Error(w, "DELETE requested", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
func (h *NodeHandler) HandleDeleteService(c *gin.Context) {
|
||||
|
||||
var serviceDelete models.ServiceMinimal
|
||||
err := json.NewDecoder(r.Body).Decode(&serviceDelete)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
if err := c.ShouldBindJSON(&serviceDelete); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var node models.NodeInfo
|
||||
|
||||
node, err = h.Repo.RetriveNode(serviceDelete.NodeId)
|
||||
|
||||
if err == nil {
|
||||
err = h.Repo.DeleteService(node, serviceDelete.ServiceId)
|
||||
if err != nil {
|
||||
|
||||
log.Fatalf("error on deleteing service from node %v error : %v", serviceDelete.NodeId, err.Error())
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
} else {
|
||||
log.Fatalf("Node not found %v error : %v", serviceDelete.NodeId, err.Error())
|
||||
node, err := h.Repo.RetriveNode(serviceDelete.NodeId)
|
||||
if err != nil {
|
||||
log.Printf("Node not found %v error : %v", serviceDelete.NodeId, err)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Node not found"})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.Repo.DeleteService(node, serviceDelete.ServiceId)
|
||||
if err != nil {
|
||||
log.Printf("Error deleting service: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete service"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -4,18 +4,67 @@ import (
|
||||
"backend/handlers"
|
||||
"backend/repositories"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/cookie"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/cors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func SeedAdmin(db *sqlx.DB) error {
|
||||
var count int
|
||||
err := db.Get(&count, "SELECT count(*) FROM users WHERE role = 'admin'")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte("admin"), bcrypt.DefaultCost)
|
||||
|
||||
_, err = db.Exec(
|
||||
"INSERT INTO users (username, email, password_hash, role) VALUES ($1, $2, $3, $4)",
|
||||
"admin", "admin@localhost", string(hash), "admin",
|
||||
)
|
||||
if err == nil {
|
||||
fmt.Println("✅ Compte admin créé (admin / admin)")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func AuthRequired(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
userID := session.Get("user_id")
|
||||
|
||||
if userID == nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Veuillez vous connecter"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
r := gin.Default()
|
||||
store := cookie.NewStore([]byte("ma_cle_secrete_super_secure"))
|
||||
|
||||
store.Options(sessions.Options{
|
||||
Path: "/",
|
||||
MaxAge: 3600 * 8,
|
||||
HttpOnly: true,
|
||||
Secure: false,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
|
||||
r.Use(sessions.Sessions("session_id", store))
|
||||
|
||||
dsn := "host=db user=admin password=admin dbname=monitoring sslmode=disable"
|
||||
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
@ -30,35 +79,34 @@ func main() {
|
||||
|
||||
dbSqlx := sqlx.NewDb(db, "postgres")
|
||||
|
||||
if err := SeedAdmin(dbSqlx); err != nil {
|
||||
log.Printf("Erreur lors du seeding: %v", err)
|
||||
}
|
||||
nodeRepo := &repositories.NodeRepository{DB: dbSqlx}
|
||||
|
||||
nodeHandler := &handlers.NodeHandler{
|
||||
Repo: nodeRepo,
|
||||
}
|
||||
|
||||
router := mux.NewRouter()
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.POST("/login", nodeHandler.LoginHandler)
|
||||
|
||||
router.HandleFunc("/register", nodeHandler.HandleRegisterNode).Methods("POST")
|
||||
router.HandleFunc("/registerService", nodeHandler.HandleRegisterService).Methods("POST")
|
||||
router.HandleFunc("/updateServiceStatus", nodeHandler.HandleUpdateServiceStatus).Methods("POST")
|
||||
api.POST("/register", nodeHandler.HandleRegisterNode)
|
||||
api.POST("/registerService", nodeHandler.HandleRegisterService)
|
||||
api.POST("/updateServiceStatus", nodeHandler.HandleUpdateServiceStatus)
|
||||
|
||||
router.HandleFunc("/retrieveNodeList", nodeHandler.HandleRetrieveNodeList).Methods("GET")
|
||||
router.HandleFunc("/retrieveNode/{id}", handlers.HandleRetrieveNode).Methods("GET")
|
||||
|
||||
//router.HandleFunc("/updateNode/{id}", nodeHandler.HandleUpdateNode).Methods("POST")
|
||||
|
||||
//router.HandleFunc("/handleAddService/{NodeId}", handleUpdateNode).Methods("POST")
|
||||
router.HandleFunc("/deleteService", nodeHandler.HandleDeleteService).Methods("DELETE")
|
||||
|
||||
c := cors.New(cors.Options{
|
||||
// Remplacez par l'origine exacte de votre frontend
|
||||
AllowedOrigins: []string{"http://localhost:3000"},
|
||||
AllowedMethods: []string{"GET", "POST", "PATCH", "DELETE"},
|
||||
AllowCredentials: true,
|
||||
})
|
||||
|
||||
handler := c.Handler(router)
|
||||
protected := api.Group("/")
|
||||
protected.Use(AuthRequired)
|
||||
{
|
||||
protected.DELETE("/deleteService", nodeHandler.HandleDeleteService)
|
||||
protected.GET("/retrieveNodeList", nodeHandler.HandleRetrieveNodeList)
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Backend running on :8080")
|
||||
log.Fatal(http.ListenAndServe(":8080", handler))
|
||||
|
||||
if err := r.Run(":8080"); err != nil {
|
||||
log.Fatalf("Erreur lors du lancement du serveur: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
17
backend/migrations/000002_auth_features.up.sql
Normal file
17
backend/migrations/000002_auth_features.up.sql
Normal file
@ -0,0 +1,17 @@
|
||||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role VARCHAR(20) DEFAULT 'user',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
11
backend/models/login.go
Normal file
11
backend/models/login.go
Normal file
@ -0,0 +1,11 @@
|
||||
package models
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Message string `json:"message"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
60
backend/repositories/login_repo.go
Normal file
60
backend/repositories/login_repo.go
Normal file
@ -0,0 +1,60 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"backend/models"
|
||||
"database/sql"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func (r *NodeRepository) LoginHandler(c *gin.Context) {
|
||||
var req models.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Format invalide"})
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("trying to login")
|
||||
|
||||
var user struct {
|
||||
ID int `db:"id"`
|
||||
PasswordHash string `db:"password_hash"`
|
||||
Role string `db:"role"`
|
||||
}
|
||||
|
||||
log.Printf("trying to login with %v pswd %v", req.Username, req.Password)
|
||||
|
||||
query := "SELECT id, password_hash, role FROM users WHERE username = $1"
|
||||
err := r.DB.Get(&user, query, req.Username)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Identifiants incorrects"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur serveur"})
|
||||
return
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Identifiants incorrects"})
|
||||
return
|
||||
} else {
|
||||
session := sessions.Default(c)
|
||||
session.Set("user_id", user.ID)
|
||||
session.Set("role", user.Role)
|
||||
|
||||
if err := session.Save(); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Impossible de créer la session"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Connexion réussie"})
|
||||
return
|
||||
}
|
||||
}
|
||||
@ -40,7 +40,6 @@ func (r *NodeRepository) UpdateServiceStatus(serviceUpdate models.ServiceUpdateR
|
||||
timestamps = append(timestamps, s.Status.Timestamp)
|
||||
}
|
||||
|
||||
// lib/pq supporte le passage de slices Go vers les types array de Postgres
|
||||
_, err := r.DB.Exec(string(query), pq.Array(serviceIds), pq.Array(statuses), pq.Array(timestamps))
|
||||
return err
|
||||
}
|
||||
@ -106,9 +105,8 @@ func (r *NodeRepository) RetriveNodeList() (map[string]models.FullNodeInfo, erro
|
||||
log.Printf("new node")
|
||||
|
||||
var node models.FullNodeInfo
|
||||
var servicesData []byte // On récupère le JSON brut ici
|
||||
var servicesData []byte
|
||||
|
||||
// On scanne les colonnes dans l'ordre du SELECT
|
||||
err := rows.Scan(
|
||||
&node.Id,
|
||||
&node.Name,
|
||||
@ -122,7 +120,6 @@ func (r *NodeRepository) RetriveNodeList() (map[string]models.FullNodeInfo, erro
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// On décode le JSON des services dans la Map de la structure
|
||||
if err := json.Unmarshal(servicesData, &node.Services); err != nil {
|
||||
return nil, fmt.Errorf("error decoding services for node %d: %v", node.Id, err)
|
||||
}
|
||||
@ -146,7 +143,7 @@ func deleteServiceFromNode(node *models.NodeInfo, serviceId int) error {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodDelete, apiURL, bytes.NewBuffer(jsonData)) // Le corps (body) est nil pour un DELETE
|
||||
req, err := http.NewRequest(http.MethodDelete, apiURL, bytes.NewBuffer(jsonData))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
if err != nil {
|
||||
@ -154,7 +151,7 @@ func deleteServiceFromNode(node *models.NodeInfo, serviceId int) error {
|
||||
}
|
||||
|
||||
client := http.Client{
|
||||
Timeout: 10 * time.Second, // Définir un timeout
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
@ -194,7 +191,6 @@ func (r *NodeRepository) DeleteService(node models.NodeInfo, serviceId int) erro
|
||||
|
||||
err = deleteServiceFromNode(&node, serviceId)
|
||||
if err != nil {
|
||||
// 4. LE NODE A ÉCHOUÉ : On annule tout en DB
|
||||
tx.Rollback()
|
||||
return fmt.Errorf("échec sur le node, annulation du changement en base de données : %w", err)
|
||||
}
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
WITH base_data AS (
|
||||
-- On récupère les 60 derniers jours de données
|
||||
SELECT
|
||||
service_id,
|
||||
status,
|
||||
@ -10,7 +9,6 @@ WITH base_data AS (
|
||||
WHERE timestamp >= NOW() - INTERVAL '60 days'
|
||||
),
|
||||
time_slots_minutes AS (
|
||||
-- On génère une série de 60 minutes jusqu'à maintenant
|
||||
SELECT generate_series(
|
||||
date_trunc('minute', now()) - interval '59 minutes',
|
||||
date_trunc('minute', now()),
|
||||
@ -18,12 +16,9 @@ time_slots_minutes AS (
|
||||
) as slot
|
||||
),
|
||||
filled_minute_data AS (
|
||||
-- On crée une ligne pour chaque minute et chaque service
|
||||
SELECT
|
||||
s.id as service_id,
|
||||
ts.slot as timestamp,
|
||||
-- On prend la valeur la plus récente si plusieurs existent dans la même minute,
|
||||
-- sinon 3 s'il n'y a rien (COALESCE)
|
||||
COALESCE(MAX(bd.status), 3) as status
|
||||
FROM time_slots_minutes ts
|
||||
CROSS JOIN services s
|
||||
@ -33,7 +28,6 @@ filled_minute_data AS (
|
||||
GROUP BY s.id, ts.slot
|
||||
),
|
||||
minute_agg AS (
|
||||
-- 60 dernières minutes
|
||||
SELECT
|
||||
service_id,
|
||||
json_agg(
|
||||
@ -45,7 +39,7 @@ minute_agg AS (
|
||||
),
|
||||
time_slots_hours AS (
|
||||
SELECT generate_series(
|
||||
date_trunc('hour', now()) - interval '23 hours', -- 23 car on inclut l'heure actuelle pour faire 24h
|
||||
date_trunc('hour', now()) - interval '23 hours',
|
||||
date_trunc('hour', now()),
|
||||
interval '1 hour'
|
||||
) as slot
|
||||
@ -54,8 +48,6 @@ filled_hours_data AS (
|
||||
SELECT
|
||||
s.id as service_id,
|
||||
ts.slot as timestamp,
|
||||
-- On récupère tous les statuts bruts de base_data qui tombent dans cette heure
|
||||
-- On garde la liste pour calculer le ratio après
|
||||
COALESCE(AVG(CASE WHEN bd.status = 1 THEN 1.0 WHEN bd.status = 3 THEN NULL ELSE 0.0 END), 3) as ratio
|
||||
FROM time_slots_hours ts
|
||||
CROSS JOIN services s
|
||||
@ -71,10 +63,10 @@ hour_agg AS (
|
||||
json_build_object(
|
||||
'timestamp', timestamp,
|
||||
'status', CASE
|
||||
WHEN ratio = 3 THEN 3 -- Aucune donnée (Inconnu)
|
||||
WHEN ratio >= 0.95 THEN 1 -- Presque tout l'heure est OK
|
||||
WHEN ratio >= 0.5 THEN 2 -- Moitié de l'heure instable
|
||||
ELSE 0 -- Majorité de l'heure en panne
|
||||
WHEN ratio = 3 THEN 3
|
||||
WHEN ratio >= 0.95 THEN 1
|
||||
WHEN ratio >= 0.5 THEN 2
|
||||
ELSE 0
|
||||
END
|
||||
) ORDER BY timestamp DESC
|
||||
) as data
|
||||
@ -82,7 +74,6 @@ hour_agg AS (
|
||||
GROUP BY service_id
|
||||
),
|
||||
time_slots_days AS (
|
||||
-- On génère les 60 derniers jours
|
||||
SELECT generate_series(
|
||||
date_trunc('day', now()) - interval '59 days',
|
||||
date_trunc('day', now()),
|
||||
@ -90,12 +81,9 @@ time_slots_days AS (
|
||||
) as slot
|
||||
),
|
||||
filled_days_data AS (
|
||||
-- On calcule le ratio pour chaque jour et chaque service
|
||||
SELECT
|
||||
s.id as service_id,
|
||||
ts.slot as timestamp,
|
||||
-- Ratio d'uptime : (points OK) / (points totaux réels)
|
||||
-- Si aucun point n'existe du tout pour le jour, on met 3 (Inconnu)
|
||||
COALESCE(
|
||||
AVG(CASE WHEN bd.status = 1 THEN 1.0 WHEN bd.status = 3 THEN NULL ELSE 0.0 END),
|
||||
3
|
||||
@ -114,10 +102,10 @@ day_agg AS (
|
||||
json_build_object(
|
||||
'timestamp', timestamp,
|
||||
'status', CASE
|
||||
WHEN ratio = 3 THEN 3 -- Aucune donnée
|
||||
WHEN ratio >= 0.98 THEN 1 -- Seuil d'excellence journalier
|
||||
WHEN ratio >= 0.5 THEN 2 -- Journée instable
|
||||
ELSE 0 -- Service majoritairement HS ce jour-là
|
||||
WHEN ratio = 3 THEN 3
|
||||
WHEN ratio >= 0.98 THEN 1
|
||||
WHEN ratio >= 0.5 THEN 2
|
||||
ELSE 0
|
||||
END
|
||||
) ORDER BY timestamp DESC
|
||||
) as data
|
||||
@ -131,7 +119,7 @@ SELECT
|
||||
json_build_object(
|
||||
'id', s.id,
|
||||
'name', s.name,
|
||||
'command', s.command, -- La virgule ici est cruciale
|
||||
'command', s.command,
|
||||
'history', json_build_object(
|
||||
'minute', COALESCE(ma.data, '[]'::json),
|
||||
'hour', COALESCE(ha.data, '[]'::json),
|
||||
|
||||
Reference in New Issue
Block a user