Estratto il servizio lista utenti e qualche altra modifica

feat/db
Antonio De Lucreziis 2 years ago
parent 85a0a21d15
commit 805d9a7ba5

@ -17,3 +17,6 @@ USER_PAGES_BASE_URL=https://poisson.phc.dm.unipi.it/~
# AuthService # AuthService
AUTH_SERVICE_HOST=:memory: AUTH_SERVICE_HOST=:memory:
# Origine per Lista Utenti
LISTA_UTENTI=utenti-poisson-2022.local.json

@ -41,7 +41,7 @@
entry.item.cognome + ' ' + entry.item.nome : entry.item.cognome + ' ' + entry.item.nome :
entry.item.nome + ' ' + entry.item.cognome entry.item.nome + ' ' + entry.item.cognome
"></a> "></a>
<template x-if="entry.item.macchinista"> <template x-if="entry.item.tags?.includes('macchinista')">
<div class="icon" title="Macchinista"> <div class="icon" title="Macchinista">
<i class="fas fa-wrench"></i> <i class="fas fa-wrench"></i>
</div> </div>

@ -48,5 +48,5 @@ func NewDefaultService(host string) Service {
return exampleMemoryUsers return exampleMemoryUsers
} }
return &LDAPAuthService{host} return newLDAPAuthService(host)
} }

@ -33,17 +33,17 @@ func (u ldapUser) AsUser() *model.User {
} }
} }
// LDAPAuthService just holds the remote host of the HTTP LDAP service to make requests to // ldapAuthService just holds the remote host of the HTTP LDAP service to make requests to
type LDAPAuthService struct { type ldapAuthService struct {
Host string Host string
} }
func NewLDAPAuthService(host string) Service { func newLDAPAuthService(host string) Service {
return &LDAPAuthService{host} return &ldapAuthService{host}
} }
// doGetRequest is a utility to make HTTP GET requests // doGetRequest is a utility to make HTTP GET requests
func (a *LDAPAuthService) doGetRequest(url string, response interface{}) error { func (a *ldapAuthService) doGetRequest(url string, response interface{}) error {
req, err := http.NewRequest( req, err := http.NewRequest(
"GET", path.Join(a.Host, "poisson-ldap", url), bytes.NewBuffer([]byte("")), "GET", path.Join(a.Host, "poisson-ldap", url), bytes.NewBuffer([]byte("")),
) )
@ -68,7 +68,7 @@ func (a *LDAPAuthService) doGetRequest(url string, response interface{}) error {
} }
// doPostRequest is a utility to make HTTP POST requests // doPostRequest is a utility to make HTTP POST requests
func (a *LDAPAuthService) doPostRequest(url string, request interface{}, response interface{}) error { func (a *ldapAuthService) doPostRequest(url string, request interface{}, response interface{}) error {
jsonStr, err := json.Marshal(request) jsonStr, err := json.Marshal(request)
if err != nil { if err != nil {
return err return err
@ -89,7 +89,7 @@ func (a *LDAPAuthService) doPostRequest(url string, request interface{}, respons
return json.NewDecoder(res.Body).Decode(response) return json.NewDecoder(res.Body).Decode(response)
} }
func (a *LDAPAuthService) GetUser(username string) (*model.User, error) { func (a *ldapAuthService) GetUser(username string) (*model.User, error) {
var user ldapUser var user ldapUser
if err := a.doGetRequest(fmt.Sprintf("/user/%s", username), &user); err != nil { if err := a.doGetRequest(fmt.Sprintf("/user/%s", username), &user); err != nil {
return nil, err return nil, err
@ -98,7 +98,7 @@ func (a *LDAPAuthService) GetUser(username string) (*model.User, error) {
return user.AsUser(), nil return user.AsUser(), nil
} }
func (a *LDAPAuthService) GetUsers() ([]*model.User, error) { func (a *ldapAuthService) GetUsers() ([]*model.User, error) {
ldapUsers := []*ldapUser{} ldapUsers := []*ldapUser{}
if err := a.doGetRequest("/users", &ldapUsers); err != nil { if err := a.doGetRequest("/users", &ldapUsers); err != nil {
return nil, err return nil, err
@ -112,7 +112,7 @@ func (a *LDAPAuthService) GetUsers() ([]*model.User, error) {
return users, nil return users, nil
} }
func (a *LDAPAuthService) GetSession(token string) (*model.Session, error) { func (a *ldapAuthService) GetSession(token string) (*model.Session, error) {
var response model.Session var response model.Session
if err := a.doGetRequest(fmt.Sprintf("/session/%s", token), &response); err != nil { if err := a.doGetRequest(fmt.Sprintf("/session/%s", token), &response); err != nil {
return nil, err return nil, err
@ -121,7 +121,7 @@ func (a *LDAPAuthService) GetSession(token string) (*model.Session, error) {
return &response, nil return &response, nil
} }
func (a *LDAPAuthService) Login(username, password string) (*model.Session, error) { func (a *ldapAuthService) Login(username, password string) (*model.Session, error) {
reqBody := map[string]interface{}{ reqBody := map[string]interface{}{
"username": username, "username": username,
"password": password, "password": password,

@ -7,6 +7,7 @@ import (
"git.phc.dm.unipi.it/phc/website/auth" "git.phc.dm.unipi.it/phc/website/auth"
"git.phc.dm.unipi.it/phc/website/config" "git.phc.dm.unipi.it/phc/website/config"
"git.phc.dm.unipi.it/phc/website/handler" "git.phc.dm.unipi.it/phc/website/handler"
"git.phc.dm.unipi.it/phc/website/lista_utenti"
"git.phc.dm.unipi.it/phc/website/server" "git.phc.dm.unipi.it/phc/website/server"
"git.phc.dm.unipi.it/phc/website/storia" "git.phc.dm.unipi.it/phc/website/storia"
"git.phc.dm.unipi.it/phc/website/templates" "git.phc.dm.unipi.it/phc/website/templates"
@ -15,8 +16,15 @@ import (
func main() { func main() {
config.Load() config.Load()
authService := auth.NewDefaultService(config.AuthServiceHost)
listaUtentiService, err := lista_utenti.New(authService, config.ListaUtenti)
if err != nil {
log.Fatal(err)
}
h := &handler.DefaultHandler{ h := &handler.DefaultHandler{
AuthService: auth.NewDefaultService(config.AuthServiceHost), AuthService: authService,
Renderer: templates.NewRenderer( Renderer: templates.NewRenderer(
"./_views/", "./_views/",
"./_views/base.html", "./_views/base.html",
@ -24,20 +32,16 @@ func main() {
), ),
NewsArticlesRegistry: articles.NewRegistry("./_content/news"), NewsArticlesRegistry: articles.NewRegistry("./_content/news"),
GuideArticlesRegistry: articles.NewRegistry("./_content/guide"), GuideArticlesRegistry: articles.NewRegistry("./_content/guide"),
// ListaUtenti: &website.JsonFileListaUtenti{
// Path: "./utenti-poisson-2022.local.json",
// },
ListaUtentiService: auth.NewLDAPAuthService(config.AuthServiceHost),
Storia: &storia.JsonFileStoria{ Storia: &storia.JsonFileStoria{
Path: "./storia.json", Path: "./storia.json",
}, },
ListaUtenti: listaUtentiService,
} }
app := server.NewFiberServer(h) app := server.NewFiberServer(h)
log.Printf("Starting server on host %q", config.Host) log.Printf("Starting server on host %q", config.Host)
err := app.Listen(config.Host) if err := app.Listen(config.Host); err != nil {
if err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }

@ -22,6 +22,9 @@ var UserPagesBaseUrl string
var AuthServiceHost string var AuthServiceHost string
// ListaUtenti è un file json da cui leggere la lista degli utenti oppure ":auth:" per utilizzare il servizio di autenticazione
var ListaUtenti string
func loadEnv(target *string, name, defaultValue string) { func loadEnv(target *string, name, defaultValue string) {
value := os.Getenv(name) value := os.Getenv(name)
if len(strings.TrimSpace(value)) == 0 { if len(strings.TrimSpace(value)) == 0 {
@ -43,20 +46,21 @@ func Load() {
// Production // Production
loadEnv(&Mode, "MODE", "production") loadEnv(&Mode, "MODE", "production")
loadEnv(&Host, "HOST", ":8080") loadEnv(&Host, "HOST", ":8080")
loadEnv(&BaseUrl, "BASE_URL", "localhost:8080")
// Services // Services
loadEnv(&GitUrl, "GIT_URL", "https://git.example.org") loadEnv(&GitUrl, "GIT_URL", "https://git.example.org")
loadEnv(&ChatUrl, "CHAT_URL", "https://chat.example.org") loadEnv(&ChatUrl, "CHAT_URL", "https://chat.example.org")
loadEnv(&Email, "EMAIL", "mail@example.org") loadEnv(&Email, "EMAIL", "mail@example.org")
// Base URL
loadEnv(&BaseUrl, "BASE_URL", "localhost:8080")
// Poisson // Poisson
loadEnv(&UserPagesBaseUrl, "USER_PAGES_BASE_URL", "https://poisson.phc.dm.unipi.it/~") loadEnv(&UserPagesBaseUrl, "USER_PAGES_BASE_URL", "https://poisson.phc.dm.unipi.it/~")
// AuthService // Auth
loadEnv(&AuthServiceHost, "AUTH_SERVICE_HOST", "http://localhost:3535") loadEnv(&AuthServiceHost, "AUTH_SERVICE_HOST", "http://localhost:3535")
// Altro
loadEnv(&ListaUtenti, "LISTA_UTENTI", ":auth:")
} }
func Object() util.Map { func Object() util.Map {
@ -73,5 +77,7 @@ func Object() util.Map {
"UserPagesBaseUrl": UserPagesBaseUrl, "UserPagesBaseUrl": UserPagesBaseUrl,
"AuthServiceHost": AuthServiceHost, "AuthServiceHost": AuthServiceHost,
"ListaUtenti": ListaUtenti,
} }
} }

@ -1,6 +1,6 @@
module git.phc.dm.unipi.it/phc/website module git.phc.dm.unipi.it/phc/website
go 1.18 go 1.19
require ( require (
github.com/alecthomas/chroma v0.9.4 github.com/alecthomas/chroma v0.9.4

@ -7,6 +7,7 @@ import (
"git.phc.dm.unipi.it/phc/website/articles" "git.phc.dm.unipi.it/phc/website/articles"
"git.phc.dm.unipi.it/phc/website/auth" "git.phc.dm.unipi.it/phc/website/auth"
"git.phc.dm.unipi.it/phc/website/lista_utenti"
"git.phc.dm.unipi.it/phc/website/model" "git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/rss" "git.phc.dm.unipi.it/phc/website/rss"
"git.phc.dm.unipi.it/phc/website/storia" "git.phc.dm.unipi.it/phc/website/storia"
@ -17,7 +18,7 @@ import (
type Service interface { type Service interface {
HandleStaticPage(w io.Writer, view string, ctx Context) error HandleStaticPage(w io.Writer, view string, ctx Context) error
HandleUtenti() ([]*model.User, error) HandleUtenti() ([]*model.User, error)
HandleListaUtenti() ([]*model.User, error) HandleListaUtenti() ([]*model.ListUser, error)
HandleStoriaPage(w io.Writer, ctx Context) error HandleStoriaPage(w io.Writer, ctx Context) error
HandleQueryAppunti(w io.Writer, query string, ctx Context) error HandleQueryAppunti(w io.Writer, query string, ctx Context) error
HandleAppuntiCondivisiPage(w io.Writer, ctx Context) error HandleAppuntiCondivisiPage(w io.Writer, ctx Context) error
@ -50,7 +51,7 @@ type DefaultHandler struct {
Renderer *templates.TemplateRenderer Renderer *templates.TemplateRenderer
NewsArticlesRegistry *articles.Registry NewsArticlesRegistry *articles.Registry
GuideArticlesRegistry *articles.Registry GuideArticlesRegistry *articles.Registry
ListaUtentiService auth.Service ListaUtenti lista_utenti.Service
Storia storia.StoriaService Storia storia.StoriaService
} }
@ -69,8 +70,8 @@ func (h *DefaultHandler) HandleUtenti() ([]*model.User, error) {
return utenti, nil return utenti, nil
} }
func (h *DefaultHandler) HandleListaUtenti() ([]*model.User, error) { func (h *DefaultHandler) HandleListaUtenti() ([]*model.ListUser, error) {
utenti, err := h.ListaUtentiService.GetUsers() utenti, err := h.ListaUtenti.GetUtenti()
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -0,0 +1,43 @@
package lista_utenti
import (
"git.phc.dm.unipi.it/phc/website/auth"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/util"
)
type authListaUtenti struct {
AuthService auth.Service
Macchinisti util.Set[string]
}
func newAuthListaUtenti(authService auth.Service) (Service, error) {
macchinisti, err := loadMacchinisti()
if err != nil {
return nil, err
}
return &authListaUtenti{authService, macchinisti}, nil
}
func (a *authListaUtenti) GetUtenti() ([]*model.ListUser, error) {
authUsers, err := a.AuthService.GetUsers()
if err != nil {
return nil, err
}
users := make([]*model.ListUser, 0, len(authUsers))
for _, u := range authUsers {
users = append(users, &model.ListUser{
Uid: u.Username,
Nome: u.Name,
Cognome: u.Surname,
Tags: []string{},
})
}
mergeMacchinisti(users, a.Macchinisti)
return users, nil
}

@ -0,0 +1,44 @@
package lista_utenti
import (
"encoding/json"
"log"
"os"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/util"
)
type jsonListaUtenti struct {
Path string
Macchinisti util.Set[string]
}
func newJsonListaUtenti(path string) (Service, error) {
macchinisti, err := loadMacchinisti()
if err != nil {
return nil, err
}
return &jsonListaUtenti{path, macchinisti}, nil
}
func (j *jsonListaUtenti) GetUtenti() ([]*model.ListUser, error) {
var users []*model.ListUser
f, err := os.Open(j.Path)
if err != nil {
return nil, err
}
if err := json.NewDecoder(f).Decode(&users); err != nil {
return nil, err
}
mergeMacchinisti(users, j.Macchinisti)
log.Printf("Caricata lista di %d utenti", len(users))
return users, nil
}

@ -0,0 +1,46 @@
package lista_utenti
import (
"encoding/json"
"os"
"git.phc.dm.unipi.it/phc/website/auth"
"git.phc.dm.unipi.it/phc/website/model"
"git.phc.dm.unipi.it/phc/website/util"
)
type Service interface {
GetUtenti() ([]*model.ListUser, error)
}
// New crea un nuovo servizio che lista gli utenti utilizzando AuthService se config è ":auth:" oppure un file json
func New(authService auth.Service, config string) (Service, error) {
if config == ":auth:" {
return newAuthListaUtenti(authService)
}
return newJsonListaUtenti(config)
}
func loadMacchinisti() (util.Set[string], error) {
f, err := os.Open("macchinisti.json")
if err != nil {
return nil, err
}
macchinisti := []string{}
if err := json.NewDecoder(f).Decode(&macchinisti); err != nil {
return nil, err
}
return util.NewSet(macchinisti...), nil
}
func mergeMacchinisti(users []*model.ListUser, macchinisti util.Set[string]) {
for _, user := range users {
if _, found := macchinisti[user.Uid]; found {
user.Tags = append(user.Tags, "macchinista")
}
}
}

@ -0,0 +1 @@
["delucreziis", "serdyuk", "minnocci", "manicastri"]

@ -1,5 +1,12 @@
package model package model
type ListUser struct {
Uid string `json:"uid"`
Nome string `json:"nome"`
Cognome string `json:"cognome"`
Tags []string `json:"tags,omitempty"`
}
// User represents a user returned from AuthenticatorService // User represents a user returned from AuthenticatorService
type User struct { type User struct {
Username string `json:"username"` Username string `json:"username"`

@ -0,0 +1,26 @@
package util
type Set[T comparable] map[T]struct{}
func NewSet[T comparable](elements ...T) Set[T] {
set := Set[T]{}
for _, e := range elements {
set[e] = struct{}{}
}
return set
}
func (set Set[T]) Add(value T) {
set[value] = struct{}{}
}
func (set Set[T]) Remove(value T) {
delete(set, value)
}
func (set Set[T]) Has(value T) bool {
_, found := set[value]
return found
}
Loading…
Cancel
Save