auth.go: make user of generics in RequestUser

dev
Francesco Minnocci 3 years ago
parent d5aa7c0ba2
commit f670c78337
Signed by: BachoSeven
GPG Key ID: 2BE4AB7FDAD828A4

@ -7,8 +7,6 @@ import (
"errors"
"net/http"
"time"
"git.phc.dm.unipi.it/aziis98/posti-dm/server/util"
)
var (
@ -30,7 +28,7 @@ type Authenticator[UserID any, U User[UserID]] interface {
// SessionTokenFromUser returns a (new) session token that represents this user
SessionTokenFromUser(user UserID) (string, error)
// UserFromSessionToken returns the corresponding user for this session token or "service.ErrNoUserForSession"
UserFromSessionToken(session string) (U, error)
UserFromSessionToken(session string) (*U, error)
// AuthenticationFailed handles failed authentications
AuthenticationFailed(error) http.Handler
@ -130,7 +128,7 @@ func (service *AuthSessionService[UserID, U]) Middleware(config *MiddlewareConfi
}
if config.RequireLogged {
userPerms, err := service.Authenticator.UserPermissions(user.UID())
userPerms, err := service.Authenticator.UserPermissions((*user).UID())
if err != nil {
service.Authenticator.OtherError(err).ServeHTTP(w, r)
return
@ -181,21 +179,16 @@ func (service *AuthSessionService[UserID, U]) LoggedMiddleware() func(http.Handl
})
}
// RequestUser retrives the "userID" from the given request based on the cookie session token.
// When generics arrive this will become something like
//
// func (auth *AuthService[U]) RequestUser(r *http.Request) *U
//
// and will just return nil if no user is present.
func (service *AuthSessionService[UserID, U]) RequestUser(r *http.Request) (U, error) {
// RequestUser retrieves the "userID" from the given request based on the cookie session token.
func (service *AuthSessionService[UserID, U]) RequestUser(r *http.Request) (*U, error) {
cookie, err := r.Cookie(service.SessionCookieName)
if err != nil {
return util.Zero[U](), err
return nil, err
}
user, err := service.Authenticator.UserFromSessionToken(cookie.Value)
if err == ErrNoUserForSession {
return util.Zero[U](), err
return nil, err
}
return user, nil

@ -12,7 +12,7 @@ import (
)
type Server struct {
auth *auth.AuthSessionService[string, *db.User]
auth *auth.AuthSessionService[string, db.User]
roomServerEventStreams map[string]serverevents.Handler
@ -25,7 +25,7 @@ func NewServer() *Server {
server := &Server{
Database: database,
auth: auth.NewAuthSessionService[string, *db.User](
auth: auth.NewAuthSessionService[string, db.User](
&simpleAuthenticator{
make(map[string]string),
database,

@ -1,6 +0,0 @@
package util
func Zero[T any]() T {
var zero T
return zero
}
Loading…
Cancel
Save