Compare commits
8 Commits
c735261f0c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
91997686d1
|
|||
|
2f4e0bb8ce
|
|||
|
56cc1c50a7
|
|||
|
088d32984c
|
|||
|
e7da8c9443
|
|||
|
0afd5bfc3a
|
|||
|
ef7ef3cf74
|
|||
|
c75c405200
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,4 +1,5 @@
|
|||||||
appdata
|
appdata
|
||||||
.idea
|
.idea
|
||||||
*.exe
|
*.exe
|
||||||
*.cmd
|
*.cmd
|
||||||
|
.run
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
@@ -13,8 +12,6 @@ type Claims struct {
|
|||||||
jwt.RegisteredClaims
|
jwt.RegisteredClaims
|
||||||
}
|
}
|
||||||
|
|
||||||
var secret = os.Getenv("SHAP_JWT_SECRET")
|
|
||||||
|
|
||||||
func GenerateJWT(userID, role string, secret []byte) (string, error) {
|
func GenerateJWT(userID, role string, secret []byte) (string, error) {
|
||||||
claims := Claims{
|
claims := Claims{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
HouseholdName string `yaml:"household_name"`
|
HouseholdName string `yaml:"household_name"`
|
||||||
Port string `yaml:"port"`
|
Port string `yaml:"port"`
|
||||||
DatabasePath string `yaml:"database_path"`
|
DatabasePath string `yaml:"database_path"`
|
||||||
|
CertificatePath string `yaml:"certificate_path"`
|
||||||
|
PrivateKeyPath string `yaml:"private_key_path"`
|
||||||
}
|
}
|
||||||
|
|
||||||
const configPath = "./appdata/config.yaml"
|
const configPath = "./appdata/config.yaml"
|
||||||
@@ -33,9 +35,11 @@ func CheckIfExists() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
defaultConfig := Config{
|
defaultConfig := Config{
|
||||||
Port: "8080",
|
Port: "8080",
|
||||||
DatabasePath: "./appdata/database.db",
|
DatabasePath: "./appdata/database.db",
|
||||||
HouseholdName: "Example-Household",
|
HouseholdName: "Example-Household",
|
||||||
|
CertificatePath: "./appdata/cert.pem",
|
||||||
|
PrivateKeyPath: "./appdata/key.pem",
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := yaml.Marshal(defaultConfig)
|
data, err := yaml.Marshal(defaultConfig)
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ func Register(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
user.Password = hashed
|
user.Password = hashed
|
||||||
user.ID = utils.GenerateUUID()
|
user.ID = utils.GenerateUUID()
|
||||||
user.Role = "user"
|
user.Role = models.RoleUser
|
||||||
|
|
||||||
if err := storage.AddUser(&user); err != nil {
|
if err := storage.AddUser(&user); err != nil {
|
||||||
log.Println("POST [api/register] " + r.RemoteAddr + ": " + err.Error())
|
log.Println("POST [api/register] " + r.RemoteAddr + ": " + err.Error())
|
||||||
@@ -200,7 +200,13 @@ func RefreshToken(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
accessToken, _ := auth.GenerateJWT(tokenRow.UserID, "", []byte(os.Getenv("SHAP_JWT_SECRET")))
|
user, err := storage.GetUserById(tokenRow.UserID)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("POST [api/refresh] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
accessToken, _ := auth.GenerateJWT(tokenRow.UserID, user.Role, []byte(os.Getenv("SHAP_JWT_SECRET")))
|
||||||
|
|
||||||
if err = json.NewEncoder(w).Encode(map[string]string{
|
if err = json.NewEncoder(w).Encode(map[string]string{
|
||||||
"access_token": accessToken,
|
"access_token": accessToken,
|
||||||
@@ -210,4 +216,31 @@ func RefreshToken(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
log.Println("POST [api/refresh] " + r.RemoteAddr + ": Successfully refreshed token")
|
||||||
|
}
|
||||||
|
func UserInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
log.Println("GET [api/userinfo] " + r.RemoteAddr + ": Method " + r.Method + " not allowed")
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
query := r.URL.Query()
|
||||||
|
idParam := query.Get("id")
|
||||||
|
user, err := storage.GetUserById(idParam)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/userinfo] " + r.RemoteAddr + ": User " + idParam + " not found")
|
||||||
|
http.Error(w, "User not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
err = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"id": user.ID,
|
||||||
|
"name": user.Username,
|
||||||
|
"avatar_url": "",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/userinfo] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("GET [api/userinfo] " + r.RemoteAddr + ": Successfully retrieved user info")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"shap-planner-backend/models"
|
"shap-planner-backend/models"
|
||||||
"shap-planner-backend/storage"
|
"shap-planner-backend/storage"
|
||||||
"shap-planner-backend/utils"
|
"shap-planner-backend/utils"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,6 +16,20 @@ func Expenses(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet: // -> Get Expenses
|
case http.MethodGet: // -> Get Expenses
|
||||||
|
expenses, err := storage.GetAllExpenses()
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/expense] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
http.Error(w, "Something went wrong", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"expenses": expenses,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/expense] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("GET [api/expense] " + r.RemoteAddr + ": Successfully retrieved expenses")
|
||||||
break
|
break
|
||||||
case http.MethodPost: // -> Create Expense
|
case http.MethodPost: // -> Create Expense
|
||||||
var body struct {
|
var body struct {
|
||||||
@@ -90,4 +105,56 @@ func Expenses(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
func ExpenseShares(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet:
|
||||||
|
query := r.URL.Query()
|
||||||
|
idParam := query.Get("id")
|
||||||
|
idTypeParam := strings.ToLower(query.Get("idType"))
|
||||||
|
if idTypeParam == models.IDTypeEXPENSE {
|
||||||
|
println(idParam)
|
||||||
|
shares, err := storage.GetSharesByExpenseId(idParam)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
http.Error(w, "Something went wrong", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
err = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"shares": shares,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": Successfully retrieved shares")
|
||||||
|
} else if idTypeParam == models.IDTypeSHARE || idTypeParam == "" {
|
||||||
|
share, err := storage.GetShareById(idParam)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
http.Error(w, "Something went wrong", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
err = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"id": share.ID,
|
||||||
|
"expense_id": share.ExpenseID,
|
||||||
|
"user_id": share.UserID,
|
||||||
|
"share_cents": share.ShareCents,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("GET [api/shares] " + r.RemoteAddr + ": Successfully retrieved shares")
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case http.MethodPut:
|
||||||
|
break
|
||||||
|
case http.MethodDelete:
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
}
|
||||||
func AdminPanel(w http.ResponseWriter, r *http.Request) {}
|
func AdminPanel(w http.ResponseWriter, r *http.Request) {}
|
||||||
|
|||||||
10
main.go
10
main.go
@@ -7,17 +7,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var SERVER = server.InitServer()
|
var _server = server.InitServer()
|
||||||
|
|
||||||
err := storage.InitDB(SERVER.DatabasePath)
|
err := storage.InitDB(_server.DatabasePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
SERVER.Run()
|
_server.Run()
|
||||||
}
|
|
||||||
|
|
||||||
func Setup() {
|
|
||||||
//TODO: first configuration
|
|
||||||
}
|
}
|
||||||
|
|||||||
14
models/constants.go
Normal file
14
models/constants.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
// Roles
|
||||||
|
const (
|
||||||
|
RoleUser = "user"
|
||||||
|
RoleAdmin = "admin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ID-Types
|
||||||
|
const (
|
||||||
|
IDTypeSHARE = "share"
|
||||||
|
IDTypeEXPENSE = "expense"
|
||||||
|
IDTypeUSER = "user"
|
||||||
|
)
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
type RefreshToken struct {
|
type RefreshToken struct {
|
||||||
ID string `json:id`
|
ID string `json:"id"`
|
||||||
UserID string `json:userid`
|
UserID string `json:"user_id"`
|
||||||
Token string `json:token`
|
Token string `json:"token"`
|
||||||
ExpiresAt int64 `json:expiresat`
|
ExpiresAt int64 `json:"expires_at"`
|
||||||
CreatedAt int64 `json:createdat`
|
CreatedAt int64 `json:"created_at"`
|
||||||
Revoked bool `json:revoked`
|
Revoked bool `json:"revoked"`
|
||||||
DeviceInfo string `json:deviceinfo`
|
DeviceInfo string `json:"device_info"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
Port string
|
Port string
|
||||||
JWTSecret []byte
|
JWTSecret []byte
|
||||||
DatabasePath string
|
DatabasePath string
|
||||||
|
CertificatePath string
|
||||||
|
PrivateKeyPath string
|
||||||
}
|
}
|
||||||
|
|
||||||
var cfg, _ = config.LoadConfig()
|
|
||||||
|
|
||||||
func InitServer() *Server {
|
func InitServer() *Server {
|
||||||
|
|
||||||
err := config.CheckIfExists()
|
err := config.CheckIfExists()
|
||||||
@@ -42,9 +42,11 @@ func InitServer() *Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &Server{
|
return &Server{
|
||||||
Port: cfg.Port,
|
Port: cfg.Port,
|
||||||
JWTSecret: []byte(jwtSecret),
|
JWTSecret: []byte(jwtSecret),
|
||||||
DatabasePath: cfg.DatabasePath,
|
DatabasePath: cfg.DatabasePath,
|
||||||
|
CertificatePath: cfg.CertificatePath,
|
||||||
|
PrivateKeyPath: cfg.PrivateKeyPath,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,12 +62,14 @@ func (server *Server) Run() {
|
|||||||
|
|
||||||
// Login required
|
// Login required
|
||||||
mux.Handle("/api/expenses", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.Expenses)))
|
mux.Handle("/api/expenses", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.Expenses)))
|
||||||
|
mux.Handle("/api/shares", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.ExpenseShares)))
|
||||||
mux.Handle("/api/balance", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.GetBalance)))
|
mux.Handle("/api/balance", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.GetBalance)))
|
||||||
mux.Handle("/api/ping", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.TestHandler)))
|
mux.Handle("/api/ping", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.TestHandler)))
|
||||||
|
mux.Handle("/api/userinfo", auth.AuthMiddleware(server.JWTSecret)(http.HandlerFunc(handlers.UserInfo)))
|
||||||
|
|
||||||
// Admin-only
|
// Admin-only
|
||||||
mux.Handle("/api/admin", auth.AuthMiddleware(server.JWTSecret)(auth.RequireRole("admin")(http.HandlerFunc(handlers.AdminPanel))))
|
mux.Handle("/api/admin", auth.AuthMiddleware(server.JWTSecret)(auth.RequireRole("admin")(http.HandlerFunc(handlers.AdminPanel))))
|
||||||
|
|
||||||
log.Printf("Listening on port %s", server.Port)
|
log.Printf("Listening on port %s", server.Port)
|
||||||
log.Fatal(http.ListenAndServe(":"+server.Port, mux))
|
log.Fatal(http.ListenAndServeTLS(":"+server.Port, server.CertificatePath, server.PrivateKeyPath, mux))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,7 +120,35 @@ func GetExpensesByUserId(userId string) ([]models.Expense, error) {
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
func GetAllExpenses() ([]models.Expense, error) {
|
func GetAllExpenses() ([]models.Expense, error) {
|
||||||
return nil, nil
|
query := "SELECT * FROM expenses"
|
||||||
|
rows, err := DB.Query(query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var expenses []models.Expense
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var expense models.Expense
|
||||||
|
var attachmentsJSON []byte
|
||||||
|
|
||||||
|
err := rows.Scan(&expense.ID, &expense.PayerID, &expense.Amount, &expense.Title, &expense.Description, &attachmentsJSON, &expense.CreatedAt, &expense.LastUpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(attachmentsJSON) > 0 {
|
||||||
|
err := json.Unmarshal(attachmentsJSON, &expense.Attachments)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expenses = append(expenses, expense)
|
||||||
|
}
|
||||||
|
if err = rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return expenses, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Expense Shares
|
// Expense Shares
|
||||||
@@ -132,6 +160,36 @@ func AddShare(share *models.ExpenseShare) error {
|
|||||||
share.ShareCents)
|
share.ShareCents)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
func GetShareById(id string) (models.ExpenseShare, error) {
|
||||||
|
row := DB.QueryRow("SELECT * FROM expense_shares WHERE id = ?", id)
|
||||||
|
var share models.ExpenseShare
|
||||||
|
err := row.Scan(&share.ID, &share.ExpenseID, &share.UserID, &share.ShareCents)
|
||||||
|
return share, err
|
||||||
|
}
|
||||||
|
func GetSharesByExpenseId(id string) ([]models.ExpenseShare, error) {
|
||||||
|
query := "SELECT * FROM expense_shares WHERE expense_id = ?"
|
||||||
|
rows, err := DB.Query(query, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var shares []models.ExpenseShare
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var share models.ExpenseShare
|
||||||
|
|
||||||
|
err := rows.Scan(&share.ID, &share.ExpenseID, &share.UserID, &share.ShareCents)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
shares = append(shares, share)
|
||||||
|
}
|
||||||
|
if err = rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return shares, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Balances
|
// Balances
|
||||||
func ComputeBalance(userId string) (float64, error) {
|
func ComputeBalance(userId string) (float64, error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user