Initial commit

This commit is contained in:
2023-05-14 19:44:16 +02:00
commit 15bc406494
29 changed files with 4346 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
package config
import (
"git.phc.dm.unipi.it/phc/website/libs/sl"
"github.com/joho/godotenv"
)
var Slot = sl.NewSlot[Config]()
var TestingProductionConfig = Config{
Mode: "production",
Host: ":4000",
}
var TestingDevelopmentConfig = Config{
Mode: "development",
Host: ":4000",
}
type Config struct {
Mode string
Host string
}
func Load(l *sl.ServiceLocator) (Config, error) {
m, err := godotenv.Read(".env")
if err != nil {
return Config{}, err
}
var cfg Config
cfg.Mode = "production"
if v, ok := m["MODE"]; ok {
cfg.Mode = v
}
cfg.Host = ":4000"
if v, ok := m["HOST"]; ok {
cfg.Host = v
}
return cfg, nil
}
+82
View File
@@ -0,0 +1,82 @@
package database
import (
"fmt"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/model"
)
var Slot = sl.NewSlot[Database]()
// Database is the main database service interface
type Database interface {
// User
CreateUser(user model.User) error
ReadUser(id db.Ref[model.User]) (model.User, error)
ReadUsers() ([]model.User, error)
UpdateUser(user model.User) error
DeleteUser(id db.Ref[model.User]) error
// Accounts
CreateAccount(account model.Account) (db.Ref[model.Account], error)
ReadAccount(id db.Ref[model.Account]) (model.Account, error)
UpdateAccount(user model.Account) error
DeleteAccount(id db.Ref[model.Account]) error
// Users & Accounts
ReadUserAccounts(user db.Ref[model.User]) ([]model.Account, error)
}
// Memory is an in-memory implementation of [Database] that can be used for testing
type Memory struct {
Database // TODO: Per ora almeno così facciamo compilare il codice
Users []model.User
}
func (m *Memory) CreateUser(user model.User) error {
m.Users = append(m.Users, user)
return nil
}
func (m *Memory) ReadUser(id db.Ref[model.User]) (model.User, error) {
for _, u := range m.Users {
if u.Id == id {
return u, nil
}
}
return model.User{}, fmt.Errorf(`no user with id "%s"`, id)
}
func (m *Memory) ReadUsers() ([]model.User, error) {
return m.Users, nil
}
func (m *Memory) UpdateUser(user model.User) error {
for i, u := range m.Users {
if u.Id == user.Id {
m.Users[i] = user
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, user.Id)
}
func (m *Memory) DeleteUser(id db.Ref[model.User]) error {
for i, u := range m.Users {
if u.Id == id {
m.Users = append(m.Users[:i], m.Users[i+1:]...)
return nil
}
}
return fmt.Errorf(`no user with id "%s"`, id)
}
+10
View File
@@ -0,0 +1,10 @@
package tables
import (
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/server/model"
)
var Users = db.AutoTable[model.User]("users")
var Accounts = db.AutoTable[model.Account]("accounts")
+34
View File
@@ -0,0 +1,34 @@
package listautenti
import (
"github.com/gofiber/fiber/v2"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/routes"
)
func Configure(l *sl.ServiceLocator) error {
db, err := sl.Use(l, database.Slot)
if err != nil {
return err
}
r, err := sl.Use(l, routes.Root)
if err != nil {
return err
}
r.Get("/api/lista-utenti", func(c *fiber.Ctx) error {
users, err := db.ReadUsers()
if err != nil {
return err
}
// TODO: Pre-process data to strip server only fields...
return c.JSON(users)
})
return nil
}
+104
View File
@@ -0,0 +1,104 @@
package listautenti_test
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"gotest.tools/assert"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/libs/util"
"git.phc.dm.unipi.it/phc/website/server/config"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/model"
"git.phc.dm.unipi.it/phc/website/server/routes"
)
func TestApiListaUtenti(t *testing.T) {
r := fiber.New()
memDB := &database.Memory{
Users: []model.User{
{
Id: "e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
Username: "claire-doe",
FullName: db.NewOption("Claire Doe"),
Email: db.NewOption("claire.doe@example.org"),
},
{
Id: "9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
Username: "john-smith",
FullName: db.NewOption("John Smith"),
Email: db.NewOption("john.smith@example.org"),
},
},
}
l := sl.New()
sl.InjectValue(l, config.Slot, config.TestingProductionConfig)
sl.InjectValue[database.Database](l, database.Slot, memDB)
sl.InjectValue(l, routes.Root, fiber.Router(r))
listautenti.Configure(l)
// Try doing the request
req, err := http.NewRequest("GET", "http://localhost:4000/api/lista-utenti", nil)
if err != nil {
t.Error(err)
}
ln := fasthttputil.NewInmemoryListener()
defer ln.Close()
go func() {
err := fasthttp.Serve(ln, r.Handler())
if err != nil {
panic(fmt.Errorf("failed to serve: %v", err))
}
}()
client := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return ln.Dial()
},
},
}
res, err := client.Do(req)
if err != nil {
t.Error(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
assert.Equal(t, string(body), util.CompactIndentedLines(`
[
{
"Id":"claire",
"FullName":"Claire Doe",
"Nickname":"claire-doe",
"Email":"claire.doe@example.org"
},
{
"Id":"john",
"FullName":"John Smith",
"Nickname":"john-smith",
"Email":"john.smith@example.org"
}
]
`))
}
+37
View File
@@ -0,0 +1,37 @@
package model
import "git.phc.dm.unipi.it/phc/website/libs/db"
type User struct {
// Id è l'id unico di questo utente, non è modificabile una volta creato
// l'utente.
Id db.Ref[User] `db:"id"`
// Username è il nome leggibile di questo utente utilizzato anche per le
// route per singolo utente, deve essere unico nel sito.
//
// NOTE: Quando un utente accede per la prima volta di default gli viene
// chiesto se usare quello dell'account che sta usando o se cambiarlo
// (in teoria non dovrebbe essere un problema poterlo modificare
// successivamente).
Username string `db:"username"`
// FullName da mostrare in giro per il sito
FullName db.Option[string] `db:"full_name"`
// Email per eventuale contatto
Email db.Option[string] `db:"email"`
}
type ProviderType string
const AteneoProvider ProviderType = "ateneo"
const PoissonProvider ProviderType = "poisson"
type Account struct {
Id db.Ref[Account] `db:"id"` // Id of this entity
UserId db.Ref[User] `db:"user_id"` // UserId tells the owner of this account binding
Provider ProviderType `db:"provider"` // Provider is the name of the authentication method
Token string `db:"token"` // Token to use to make requests on behalf of this user
}
+9
View File
@@ -0,0 +1,9 @@
package routes
import (
"git.phc.dm.unipi.it/phc/website/libs/sl"
"github.com/gofiber/fiber/v2"
)
var Root = sl.NewSlot[fiber.Router]()
+24
View File
@@ -0,0 +1,24 @@
package server
import (
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/routes"
"github.com/gofiber/fiber/v2"
)
type Server struct{ Router *fiber.App }
func Configure(l *sl.ServiceLocator) (*Server, error) {
r := fiber.New(fiber.Config{})
r.Static("/assets", "./out/frontend/assets")
sl.InjectValue(l, routes.Root, fiber.Router(r))
if err := listautenti.Configure(l); err != nil {
return nil, err
}
return &Server{r}, nil
}