2021-12-08 10:03:00 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/ed25519"
|
|
|
|
"crypto/rand"
|
|
|
|
"database/sql"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
2022-02-16 11:50:25 +01:00
|
|
|
"time"
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-03-15 11:04:54 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/graph/model"
|
2022-01-27 10:35:26 +01:00
|
|
|
"github.com/ClusterCockpit/cc-backend/log"
|
2021-12-08 10:03:00 +01:00
|
|
|
sq "github.com/Masterminds/squirrel"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
// Only Username and Roles will always be filled in when returned by `GetUser`.
|
|
|
|
// If Name and Email is needed as well, use auth.FetchUser(), which does a database
|
|
|
|
// query for all fields.
|
2021-12-08 10:03:00 +01:00
|
|
|
type User struct {
|
2022-03-03 14:54:37 +01:00
|
|
|
Username string `json:"username"`
|
|
|
|
Password string `json:"-"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Roles []string `json:"roles"`
|
|
|
|
ViaLdap bool `json:"via-ldap"`
|
|
|
|
Email string `json:"email"`
|
2022-01-27 09:29:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
RoleAdmin string = "admin"
|
|
|
|
RoleApi string = "api"
|
|
|
|
RoleUser string = "user"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (u *User) HasRole(role string) bool {
|
|
|
|
for _, r := range u.Roles {
|
|
|
|
if r == role {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type ContextKey string
|
|
|
|
|
|
|
|
const ContextUserKey ContextKey = "user"
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
type Authentication struct {
|
|
|
|
db *sqlx.DB
|
|
|
|
sessionStore *sessions.CookieStore
|
|
|
|
jwtPublicKey ed25519.PublicKey
|
|
|
|
jwtPrivateKey ed25519.PrivateKey
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
ldapConfig *LdapConfig
|
|
|
|
ldapSyncUserPassword string
|
2022-02-16 11:50:25 +01:00
|
|
|
|
|
|
|
// If zero, tokens/sessions do not expire.
|
|
|
|
SessionMaxAge time.Duration
|
|
|
|
JwtMaxAge time.Duration
|
2022-02-14 14:22:44 +01:00
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) Init(db *sqlx.DB, ldapConfig *LdapConfig) error {
|
|
|
|
auth.db = db
|
2021-12-08 10:03:00 +01:00
|
|
|
_, err := db.Exec(`
|
|
|
|
CREATE TABLE IF NOT EXISTS user (
|
2022-03-17 10:54:17 +01:00
|
|
|
username varchar(255) PRIMARY KEY NOT NULL,
|
2021-12-08 10:03:00 +01:00
|
|
|
password varchar(255) DEFAULT NULL,
|
2022-03-17 10:54:17 +01:00
|
|
|
ldap tinyint NOT NULL DEFAULT 0,
|
2021-12-08 10:03:00 +01:00
|
|
|
name varchar(255) DEFAULT NULL,
|
2022-03-17 10:54:17 +01:00
|
|
|
roles varchar(255) NOT NULL DEFAULT "[]",
|
2021-12-08 10:03:00 +01:00
|
|
|
email varchar(255) DEFAULT NULL);`)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sessKey := os.Getenv("SESSION_KEY")
|
|
|
|
if sessKey == "" {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("environment variable 'SESSION_KEY' not set (will use non-persistent random key)")
|
2021-12-08 10:03:00 +01:00
|
|
|
bytes := make([]byte, 32)
|
|
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.sessionStore = sessions.NewCookieStore(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(sessKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.sessionStore = sessions.NewCookieStore(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pubKey, privKey := os.Getenv("JWT_PUBLIC_KEY"), os.Getenv("JWT_PRIVATE_KEY")
|
|
|
|
if pubKey == "" || privKey == "" {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("environment variables 'JWT_PUBLIC_KEY' or 'JWT_PRIVATE_KEY' not set (token based authentication will not work)")
|
2021-12-08 10:03:00 +01:00
|
|
|
} else {
|
|
|
|
bytes, err := base64.StdEncoding.DecodeString(pubKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.jwtPublicKey = ed25519.PublicKey(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
bytes, err = base64.StdEncoding.DecodeString(privKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.jwtPrivateKey = ed25519.PrivateKey(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if ldapConfig != nil {
|
2022-02-14 14:22:44 +01:00
|
|
|
auth.ldapConfig = ldapConfig
|
|
|
|
if err := auth.initLdap(); err != nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
// arg must be formated like this: "<username>:[admin|api|]:<password>"
|
|
|
|
func (auth *Authentication) AddUser(arg string) error {
|
2021-12-08 10:03:00 +01:00
|
|
|
parts := strings.SplitN(arg, ":", 3)
|
2022-01-27 09:29:11 +01:00
|
|
|
if len(parts) != 3 || len(parts[0]) == 0 {
|
2021-12-08 10:03:00 +01:00
|
|
|
return errors.New("invalid argument format")
|
|
|
|
}
|
|
|
|
|
2022-03-03 14:54:37 +01:00
|
|
|
roles := strings.Split(parts[1], ",")
|
|
|
|
return auth.CreateUser(parts[0], "", parts[2], "", roles)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (auth *Authentication) CreateUser(username, name, password, email string, roles []string) error {
|
|
|
|
for _, role := range roles {
|
|
|
|
if role != RoleAdmin && role != RoleApi && role != RoleUser {
|
|
|
|
return fmt.Errorf("invalid user role: %#v", role)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if username == "" {
|
|
|
|
return errors.New("username should not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
if password != "" {
|
|
|
|
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
2022-01-27 09:29:11 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
password = string(bytes)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2022-03-03 14:54:37 +01:00
|
|
|
rolesJson, _ := json.Marshal(roles)
|
|
|
|
cols := []string{"username", "password", "roles"}
|
|
|
|
vals := []interface{}{username, password, string(rolesJson)}
|
|
|
|
if name != "" {
|
|
|
|
cols = append(cols, "name")
|
|
|
|
vals = append(vals, name)
|
|
|
|
}
|
|
|
|
if email != "" {
|
|
|
|
cols = append(cols, "email")
|
|
|
|
vals = append(vals, email)
|
2022-01-10 16:14:54 +01:00
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
|
2022-03-03 14:54:37 +01:00
|
|
|
if _, err := sq.Insert("user").Columns(cols...).Values(vals...).RunWith(auth.db).Exec(); err != nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
return err
|
|
|
|
}
|
2022-03-03 14:54:37 +01:00
|
|
|
|
|
|
|
log.Infof("new user %#v created (roles: %s)", username, roles)
|
2021-12-08 10:03:00 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) DelUser(username string) error {
|
|
|
|
_, err := auth.db.Exec(`DELETE FROM user WHERE user.username = ?`, username)
|
2021-12-08 10:03:00 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-03 14:54:37 +01:00
|
|
|
func (auth *Authentication) FetchUsers(viaLdap bool) ([]*User, error) {
|
|
|
|
q := sq.Select("username", "name", "email", "roles").From("user")
|
|
|
|
if !viaLdap {
|
|
|
|
q = q.Where("ldap = 0")
|
|
|
|
} else {
|
|
|
|
q = q.Where("ldap = 1")
|
|
|
|
}
|
|
|
|
|
|
|
|
rows, err := q.RunWith(auth.db).Query()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
users := make([]*User, 0)
|
|
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
|
|
rawroles := ""
|
|
|
|
user := &User{}
|
|
|
|
var name, email sql.NullString
|
|
|
|
if err := rows.Scan(&user.Username, &name, &email, &rawroles); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := json.Unmarshal([]byte(rawroles), &user.Roles); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
user.Name = name.String
|
|
|
|
user.Email = email.String
|
|
|
|
users = append(users, user)
|
|
|
|
}
|
|
|
|
return users, nil
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) FetchUser(username string) (*User, error) {
|
2021-12-08 10:03:00 +01:00
|
|
|
user := &User{Username: username}
|
|
|
|
var hashedPassword, name, rawRoles, email sql.NullString
|
|
|
|
if err := sq.Select("password", "ldap", "name", "roles", "email").From("user").
|
2022-02-14 14:22:44 +01:00
|
|
|
Where("user.username = ?", username).RunWith(auth.db).
|
2021-12-08 10:03:00 +01:00
|
|
|
QueryRow().Scan(&hashedPassword, &user.ViaLdap, &name, &rawRoles, &email); err != nil {
|
|
|
|
return nil, fmt.Errorf("user '%s' not found (%s)", username, err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
user.Password = hashedPassword.String
|
|
|
|
user.Name = name.String
|
|
|
|
user.Email = email.String
|
|
|
|
if rawRoles.Valid {
|
2022-02-14 14:22:44 +01:00
|
|
|
if err := json.Unmarshal([]byte(rawRoles.String), &user.Roles); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2022-03-15 11:04:54 +01:00
|
|
|
func FetchUser(ctx context.Context, db *sqlx.DB, username string) (*model.User, error) {
|
|
|
|
me := GetUser(ctx)
|
|
|
|
if me != nil && !me.HasRole(RoleAdmin) && me.Username != username {
|
|
|
|
return nil, errors.New("forbidden")
|
|
|
|
}
|
|
|
|
|
|
|
|
user := &model.User{Username: username}
|
2022-03-17 10:54:17 +01:00
|
|
|
var name, email sql.NullString
|
2022-03-15 11:04:54 +01:00
|
|
|
if err := sq.Select("name", "email").From("user").Where("user.username = ?", username).
|
2022-03-17 10:54:17 +01:00
|
|
|
RunWith(db).QueryRow().Scan(&name, &email); err != nil {
|
2022-03-15 11:04:54 +01:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-17 10:54:17 +01:00
|
|
|
|
|
|
|
user.Name = name.String
|
|
|
|
user.Email = email.String
|
2022-03-15 11:04:54 +01:00
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
// Handle a POST request that should log the user in, starting a new session.
|
|
|
|
func (auth *Authentication) Login(onsuccess http.Handler, onfailure func(rw http.ResponseWriter, r *http.Request, loginErr error)) http.Handler {
|
2021-12-08 10:03:00 +01:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
username, password := r.FormValue("username"), r.FormValue("password")
|
2022-02-14 14:22:44 +01:00
|
|
|
user, err := auth.FetchUser(username)
|
|
|
|
if err == nil && user.ViaLdap && auth.ldapConfig != nil {
|
|
|
|
err = auth.loginViaLdap(user, password)
|
2021-12-08 10:03:00 +01:00
|
|
|
} else if err == nil && !user.ViaLdap && user.Password != "" {
|
|
|
|
if e := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); e != nil {
|
|
|
|
err = fmt.Errorf("user '%s' provided the wrong password (%s)", username, e.Error())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
err = errors.New("could not authenticate user")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warnf("login of user %#v failed: %s", username, err.Error())
|
2022-02-14 14:22:44 +01:00
|
|
|
onfailure(rw, r, err)
|
2021-12-08 10:03:00 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
session, err := auth.sessionStore.New(r, "session")
|
2021-12-08 10:03:00 +01:00
|
|
|
if err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Errorf("session creation failed: %s", err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-16 11:50:25 +01:00
|
|
|
if auth.SessionMaxAge != 0 {
|
|
|
|
session.Options.MaxAge = int(auth.SessionMaxAge.Seconds())
|
|
|
|
}
|
2021-12-08 10:03:00 +01:00
|
|
|
session.Values["username"] = user.Username
|
2022-01-27 09:29:11 +01:00
|
|
|
session.Values["roles"] = user.Roles
|
2022-02-14 14:22:44 +01:00
|
|
|
if err := auth.sessionStore.Save(r, rw, session); err != nil {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Errorf("session save failed: %s", err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Infof("login successfull: user: %#v (roles: %v)", user.Username, user.Roles)
|
2022-02-14 14:22:44 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, user)
|
|
|
|
onsuccess.ServeHTTP(rw, r.WithContext(ctx))
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrTokenInvalid error = errors.New("invalid token")
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) authViaToken(r *http.Request) (*User, error) {
|
|
|
|
if auth.jwtPublicKey == nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
rawtoken := r.Header.Get("X-Auth-Token")
|
|
|
|
if rawtoken == "" {
|
|
|
|
rawtoken = r.Header.Get("Authorization")
|
|
|
|
prefix := "Bearer "
|
|
|
|
if !strings.HasPrefix(rawtoken, prefix) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
rawtoken = rawtoken[len(prefix):]
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := jwt.Parse(rawtoken, func(t *jwt.Token) (interface{}, error) {
|
|
|
|
if t.Method != jwt.SigningMethodEdDSA {
|
|
|
|
return nil, errors.New("only Ed25519/EdDSA supported")
|
|
|
|
}
|
2022-02-14 14:22:44 +01:00
|
|
|
return auth.jwtPublicKey, nil
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-14 15:52:59 +01:00
|
|
|
return nil, err
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := token.Claims.Valid(); err != nil {
|
2022-02-14 15:52:59 +01:00
|
|
|
return nil, err
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
sub, _ := claims["sub"].(string)
|
2022-02-14 15:52:59 +01:00
|
|
|
|
|
|
|
var roles []string
|
|
|
|
if rawroles, ok := claims["roles"].([]interface{}); ok {
|
|
|
|
for _, rr := range rawroles {
|
|
|
|
if r, ok := rr.(string); ok {
|
|
|
|
roles = append(roles, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-01-17 13:35:49 +01:00
|
|
|
|
|
|
|
// TODO: Check if sub is still a valid user!
|
2021-12-08 10:03:00 +01:00
|
|
|
return &User{
|
2022-01-27 09:29:11 +01:00
|
|
|
Username: sub,
|
|
|
|
Roles: roles,
|
2021-12-08 10:03:00 +01:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Authenticate the user and put a User object in the
|
|
|
|
// context of the request. If authentication fails,
|
|
|
|
// do not continue but send client to the login screen.
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) Auth(onsuccess http.Handler, onfailure func(rw http.ResponseWriter, r *http.Request, authErr error)) http.Handler {
|
2021-12-08 10:03:00 +01:00
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
2022-02-14 14:22:44 +01:00
|
|
|
user, err := auth.authViaToken(r)
|
2022-02-14 15:52:59 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Warnf("authentication failed: %s", err.Error())
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if user != nil {
|
2022-01-17 13:35:49 +01:00
|
|
|
// Successfull authentication using a token
|
2021-12-08 10:03:00 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, user)
|
2022-02-14 14:22:44 +01:00
|
|
|
onsuccess.ServeHTTP(rw, r.WithContext(ctx))
|
2021-12-08 10:03:00 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
session, err := auth.sessionStore.Get(r, "session")
|
2021-12-08 10:03:00 +01:00
|
|
|
if err != nil {
|
2022-01-17 13:35:49 +01:00
|
|
|
// sessionStore.Get will return a new session if no current one is attached to this request.
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if session.IsNew {
|
2022-01-27 10:35:26 +01:00
|
|
|
log.Warn("authentication failed: no session or jwt found")
|
2022-02-14 14:22:44 +01:00
|
|
|
onfailure(rw, r, errors.New("no valid session or JWT provided"))
|
2021-12-08 10:03:00 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-27 09:29:11 +01:00
|
|
|
username, _ := session.Values["username"].(string)
|
|
|
|
roles, _ := session.Values["roles"].([]string)
|
2021-12-08 10:03:00 +01:00
|
|
|
ctx := context.WithValue(r.Context(), ContextUserKey, &User{
|
2022-01-27 09:29:11 +01:00
|
|
|
Username: username,
|
|
|
|
Roles: roles,
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
2022-02-14 14:22:44 +01:00
|
|
|
onsuccess.ServeHTTP(rw, r.WithContext(ctx))
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a new JWT that can be used for authentication
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) ProvideJWT(user *User) (string, error) {
|
|
|
|
if auth.jwtPrivateKey == nil {
|
2022-01-27 09:29:11 +01:00
|
|
|
return "", errors.New("environment variable 'JWT_PRIVATE_KEY' not set")
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
2022-03-10 14:09:13 +01:00
|
|
|
now := time.Now()
|
2022-02-16 11:50:25 +01:00
|
|
|
claims := jwt.MapClaims{
|
2022-01-27 09:29:11 +01:00
|
|
|
"sub": user.Username,
|
|
|
|
"roles": user.Roles,
|
2022-03-10 14:09:13 +01:00
|
|
|
"iat": now.Unix(),
|
2022-02-16 11:50:25 +01:00
|
|
|
}
|
|
|
|
if auth.JwtMaxAge != 0 {
|
2022-03-10 14:09:13 +01:00
|
|
|
claims["exp"] = now.Add(auth.JwtMaxAge).Unix()
|
2022-02-16 11:50:25 +01:00
|
|
|
}
|
|
|
|
|
2022-03-10 14:09:13 +01:00
|
|
|
return jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(auth.jwtPrivateKey)
|
2021-12-08 10:03:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func GetUser(ctx context.Context) *User {
|
|
|
|
x := ctx.Value(ContextUserKey)
|
|
|
|
if x == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return x.(*User)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clears the session cookie
|
2022-02-14 14:22:44 +01:00
|
|
|
func (auth *Authentication) Logout(onsuccess http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
session, err := auth.sessionStore.Get(r, "session")
|
|
|
|
if err != nil {
|
2021-12-08 10:03:00 +01:00
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-14 14:22:44 +01:00
|
|
|
if !session.IsNew {
|
|
|
|
session.Options.MaxAge = -1
|
|
|
|
if err := auth.sessionStore.Save(r, rw, session); err != nil {
|
|
|
|
http.Error(rw, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
onsuccess.ServeHTTP(rw, r)
|
2021-12-08 10:03:00 +01:00
|
|
|
})
|
|
|
|
}
|