You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.1 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"git.phc.dm.unipi.it/aziis98/posti-dm/server/auth"
"git.phc.dm.unipi.it/aziis98/posti-dm/server/db"
"git.phc.dm.unipi.it/aziis98/posti-dm/server/util"
)
// simpleAuthenticator holds an in memory map of session tokens and a reference to the main database interface
type simpleAuthenticator struct {
// sessions is a map from a sessionToken to userID
sessions map[string]string
database db.Database
}
func (service *simpleAuthenticator) CheckUserPassword(userID, password string) error {
if password != "phc" {
return fmt.Errorf(`invalid password`)
}
// FIXME: al momento quando la password è giusta creiamo tutti gli account necessari
err := service.database.CreateUser(&db.User{
ID: userID,
Permissions: make(util.Set[string]),
})
if err != nil {
log.Printf(`got "%v" while trying to log as @%s`, err, userID)
return nil
}
return nil
}
func (service *simpleAuthenticator) UserPermissions(userID string) ([]string, error) {
user, err := service.database.GetUser(userID)
if err != nil {
return nil, err
}
return user.Permissions.Elements(), nil
}
func (service *simpleAuthenticator) SessionTokenFromUser(userID string) (string, error) {
user, err := service.database.GetUser(userID)
if err != nil {
return "", err
}
token := util.RandomHash(20)
service.sessions[token] = user.ID
return token, nil
}
func (service *simpleAuthenticator) UserFromSessionToken(session string) (*db.User, error) {
userID, present := service.sessions[session]
if !present {
return nil, auth.ErrNoUserForSession
}
user, err := service.database.GetUser(userID)
if err != nil {
return nil, err
}
return user, nil
}
func (service *simpleAuthenticator) AuthenticationFailed(err error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusUnauthorized)
})
}
func (service *simpleAuthenticator) OtherError(err error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
})
}