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.
website/auth/auth.go

73 lines
2.6 KiB
Go

package auth
import "fmt"
// ErrInvalidSession is thrown when an AuthenticatorService is given a missing or invalid session token
var ErrInvalidSession = fmt.Errorf(`invalid session token`)
// User represents a user returned from AuthenticatorService
type User struct {
Username string `json:"username"`
Name string `json:"name"`
Surname string `json:"surname"`
FullName string `json:"fullName"`
Email string `json:"email"`
}
// WithDefaultFullName is a utility that returns a copy of the given user with the full name set to the concatenation of the name and surname of the user.
func (u User) WithDefaultFullName() User {
return User{
Username: u.Username,
Name: u.Name,
Surname: u.Surname,
Email: u.Email,
FullName: u.Username + " " + u.Surname,
}
}
// Session represents a session returned from AuthenticatorService
type Session struct {
Username string `json:"username"`
Token string `json:"token"`
}
// AuthenticatorService can login users using a separate http service or a temporary in memory store. When a user logs in the auth service returns a session token that can be used to read and modify user properties without having to re-send the user password. (TODO: Not yet implemented: this token has to be renewed every so often otherwise it lasts just a couple of days)
type AuthenticatorService interface {
// GetUser retrieves the user info given the username
GetUser(username string) (*User, error)
// GetUsers retrieves the full user list from the authentication service
GetUsers() ([]*User, error)
// GetSession retrieves the user session associated to a session token
GetSession(token string) (*Session, error)
// Login tries to log in a user given username and password and if successful returns a new user session
Login(username, password string) (*Session, error)
}
// UserForSession returns the user (object) linked to a session token, this is just a shortcut for calling [AuthenticatorService.GetSession] and then [AuthenticatorService.GetUser]
func UserForSession(as AuthenticatorService, token string) (*User, error) {
session, err := as.GetSession(token)
if err != nil {
return nil, err
}
user, err := as.GetUser(session.Username)
if err != nil {
return nil, err
}
return user, nil
}
// New create an AuthenticatorService given an "host" string, if ":memory:" then this just returns an example AuthenticatorService using the [auth.Memory] implementation, otherwise for now this defaults to [auth.LDAPAuthService]
func New(host string) AuthenticatorService {
if host == ":memory:" {
return exampleMemoryUsers
}
return &LDAPAuthService{host}
}