working sub

This commit is contained in:
2026-03-05 12:21:32 +03:00
parent 205d9cf8b0
commit 951f3ab482
6 changed files with 65 additions and 14 deletions

View File

@@ -12,6 +12,7 @@ type Error struct {
}
func WriteError(w http.ResponseWriter, err error) {
log.Println(err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
e := json.NewEncoder(w).Encode(Error{
@@ -59,6 +60,7 @@ func ReadBody[T any](r *http.Request) (T, error) {
}
func CheckToken(r *http.Request) bool {
auth := r.Header.Get("Authorization")
log.Println(auth)
if auth != cfg.JWTSecret {
return false
}

View File

@@ -2,15 +2,21 @@ package app
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/vinovest/sqlx"
)
import _ "github.com/lib/pq"
var db *sqlx.DB = nil
func init() {
if err := godotenv.Load(".env"); err != nil {
log.Println("Error loading .env file. If you use docker, then you can ignore this.")
}
if db == nil {
connectPsql()
}
@@ -33,6 +39,4 @@ func connectPsql() {
panic(err)
}
}
func ClosePsql() error {
return db.Close()
}
func ClosePsql() error { return db.Close() }

View File

@@ -14,6 +14,14 @@ import (
"github.com/go-chi/chi/v5"
)
func GetConfig(w http.ResponseWriter, _ *http.Request) {
res := map[string]any{
"config": cfg,
"hysteria": hysteriaCfg,
}
WriteResponse(w, res)
}
type AddUserReq struct {
Username string `json:"username"`
Password string `json:"password"`
@@ -84,6 +92,44 @@ func AllUsers(w http.ResponseWriter, r *http.Request) {
}
WriteResponse(w, users)
}
func GetUser(w http.ResponseWriter, r *http.Request) {
fmt.Println("GetUser called")
if !CheckToken(r) {
WriteError(w, errors.New("token required"))
return
}
id := chi.URLParam(r, "id")
userId, err := strconv.Atoi(id)
if err != nil {
WriteError(w, err)
return
}
rep := NewUserRepository(db)
user, err := rep.GetById(userId)
WriteResponseOrError(w, user, err)
}
func GetUserKey(w http.ResponseWriter, r *http.Request) {
fmt.Println("GetUserKey called")
if !CheckToken(r) {
WriteError(w, errors.New("token required"))
return
}
id := chi.URLParam(r, "id")
userId, err := strconv.Atoi(id)
if err != nil {
WriteError(w, err)
return
}
rep := NewUserRepository(db)
user, err := rep.GetById(userId)
if err != nil {
WriteError(w, err)
return
}
WriteResponse(w, encodeURL(user))
}
type GetConnectURLReq struct {
ID int `json:"id"`

View File

@@ -7,13 +7,14 @@ import (
"net/http"
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
func encodeURL(user User) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.ID, "name": user.Username, "pass": user.Password,
"id": user.ID, "name": user.Username, "pass": user.Password, "iat": time.Now().Unix(),
})
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {

2
go.mod
View File

@@ -8,10 +8,10 @@ require (
github.com/lib/pq v1.11.2
github.com/vinovest/sqlx v1.7.2
gopkg.in/yaml.v3 v3.0.1
github.com/joho/godotenv v1.5.1
)
require (
github.com/joho/godotenv v1.5.1 // indirect
github.com/muir/list v1.2.1 // indirect
github.com/muir/sqltoken v0.4.0 // indirect
)

14
main.go
View File

@@ -8,14 +8,9 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
)
func main() {
if err := godotenv.Load(".env"); err != nil {
log.Println("Error loading .env file. If you use docker, then you can ignore this.")
}
app.LoadConfig()
r := chi.NewRouter()
@@ -25,9 +20,12 @@ func main() {
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
r.Post("/add", app.AddUser)
r.Get("/config", app.GetConfig)
r.Post("/delete", app.DeleteUser)
r.Get("/users", app.AllUsers)
r.Post("/users", app.AddUser)
r.Get("/users/{id}", app.GetUser)
r.Get("/users/{id}/key", app.GetUserKey)
r.Post("/connect", app.GetUserURL)
r.Get("/sub/{id}", app.Sub)
@@ -35,8 +33,8 @@ func main() {
r.Post("/auth", app.DoAuth)
defer app.ClosePsql()
log.Println("Listening on :8080")
if err := http.ListenAndServe(":8080", r); err != nil {
log.Println("Listening on :9999")
if err := http.ListenAndServe(":9999", r); err != nil {
log.Fatal(err)
}
}