Skip to content

Commit

Permalink
fill more manager
Browse files Browse the repository at this point in the history
  • Loading branch information
zyxkad committed Aug 17, 2024
1 parent 88b902b commit 8cf633b
Show file tree
Hide file tree
Showing 8 changed files with 375 additions and 224 deletions.
1 change: 1 addition & 0 deletions api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type UserManager interface {
GetUser(id string) *User
AddUser(*User) error
RemoveUser(id string) error
ForEachUser(cb func(*User) error) error
UpdateUserPassword(username string, password string) error
UpdateUserPermissions(username string, permissions PermissionFlag) error

Expand Down
212 changes: 0 additions & 212 deletions api/v0/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,215 +281,3 @@ func (h *Handler) routeLogout(rw http.ResponseWriter, req *http.Request) {
h.tokens.InvalidToken(tid)
rw.WriteHeader(http.StatusNoContent)
}

// var (
// ErrUnsupportAuthType = errors.New("unsupported authorization type")
// ErrScopeNotMatch = errors.New("scope not match")
// ErrJTINotExists = errors.New("jti not exists")

// ErrStrictPathNotMatch = errors.New("strict path not match")
// ErrStrictQueryNotMatch = errors.New("strict query value not match")
// )

// func (cr *Cluster) getJWTKey(t *jwt.Token) (any, error) {
// if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
// return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
// }
// return cr.apiHmacKey, nil
// }

// const (
// challengeTokenScope = "GOBA-challenge"
// authTokenScope = "GOBA-auth"
// apiTokenScope = "GOBA-API"
// )

// type challengeTokenClaims struct {
// jwt.RegisteredClaims

// Scope string `json:"scope"`
// Action string `json:"act"`
// }

// func (cr *Cluster) generateChallengeToken(cliId string, action string) (string, error) {
// now := time.Now()
// exp := now.Add(time.Minute * 1)
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, &challengeTokenClaims{
// RegisteredClaims: jwt.RegisteredClaims{
// Subject: cliId,
// Issuer: cr.jwtIssuer,
// IssuedAt: jwt.NewNumericDate(now),
// ExpiresAt: jwt.NewNumericDate(exp),
// },
// Scope: challengeTokenScope,
// Action: action,
// })
// tokenStr, err := token.SignedString(cr.apiHmacKey)
// if err != nil {
// return "", err
// }
// return tokenStr, nil
// }

// func (cr *Cluster) verifyChallengeToken(cliId string, action string, token string) (err error) {
// var claims challengeTokenClaims
// if _, err = jwt.ParseWithClaims(
// token,
// &claims,
// cr.getJWTKey,
// jwt.WithSubject(cliId),
// jwt.WithIssuedAt(),
// jwt.WithIssuer(cr.jwtIssuer),
// ); err != nil {
// return
// }
// if claims.Scope != challengeTokenScope {
// return ErrScopeNotMatch
// }
// if claims.Action != action {
// return ErrJTINotExists
// }
// return
// }

// type authTokenClaims struct {
// jwt.RegisteredClaims

// Scope string `json:"scope"`
// User string `json:"usr"`
// }

// func (cr *Cluster) generateAuthToken(cliId string, userId string) (string, error) {
// jti, err := utils.GenRandB64(16)
// if err != nil {
// return "", err
// }
// now := time.Now()
// exp := now.Add(time.Hour * 24)
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, &authTokenClaims{
// RegisteredClaims: jwt.RegisteredClaims{
// ID: jti,
// Subject: cliId,
// Issuer: cr.jwtIssuer,
// IssuedAt: jwt.NewNumericDate(now),
// ExpiresAt: jwt.NewNumericDate(exp),
// },
// Scope: authTokenScope,
// User: userId,
// })
// tokenStr, err := token.SignedString(cr.apiHmacKey)
// if err != nil {
// return "", err
// }
// if err = cr.database.AddJTI(jti, exp); err != nil {
// return "", err
// }
// return tokenStr, nil
// }

// func (cr *Cluster) verifyAuthToken(cliId string, token string) (id string, user string, err error) {
// var claims authTokenClaims
// if _, err = jwt.ParseWithClaims(
// token,
// &claims,
// cr.getJWTKey,
// jwt.WithSubject(cliId),
// jwt.WithIssuedAt(),
// jwt.WithIssuer(cr.jwtIssuer),
// ); err != nil {
// return
// }
// if claims.Scope != authTokenScope {
// err = ErrScopeNotMatch
// return
// }
// if user = claims.User; user == "" {
// // reject old token
// err = ErrJTINotExists
// return
// }
// id = claims.ID
// if ok, _ := cr.database.ValidJTI(id); !ok {
// err = ErrJTINotExists
// return
// }
// return
// }

// type apiTokenClaims struct {
// jwt.RegisteredClaims

// Scope string `json:"scope"`
// User string `json:"usr"`
// StrictPath string `json:"str-p"`
// StrictQuery map[string]string `json:"str-q,omitempty"`
// }

// func (cr *Cluster) generateAPIToken(cliId string, userId string, path string, query map[string]string) (string, error) {
// jti, err := utils.GenRandB64(8)
// if err != nil {
// return "", err
// }
// now := time.Now()
// exp := now.Add(time.Minute * 10)
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, &apiTokenClaims{
// RegisteredClaims: jwt.RegisteredClaims{
// ID: jti,
// Subject: cliId,
// Issuer: cr.jwtIssuer,
// IssuedAt: jwt.NewNumericDate(now),
// ExpiresAt: jwt.NewNumericDate(exp),
// },
// Scope: apiTokenScope,
// User: userId,
// StrictPath: path,
// StrictQuery: query,
// })
// tokenStr, err := token.SignedString(cr.apiHmacKey)
// if err != nil {
// return "", err
// }
// if err = cr.database.AddJTI(jti, exp); err != nil {
// return "", err
// }
// return tokenStr, nil
// }

// func (h *Handler) verifyAPIToken(cliId string, token string, path string, query url.Values) (id string, user string, err error) {
// var claims apiTokenClaims
// _, err = jwt.ParseWithClaims(
// token,
// &claims,
// cr.getJWTKey,
// jwt.WithSubject(cliId),
// jwt.WithIssuedAt(),
// jwt.WithIssuer(cr.jwtIssuer),
// )
// if err != nil {
// return
// }
// if claims.Scope != apiTokenScope {
// err = ErrScopeNotMatch
// return
// }
// if user = claims.User; user == "" {
// err = ErrJTINotExists
// return
// }
// id = claims.ID
// if ok, _ := cr.database.ValidJTI(id); !ok {
// err = ErrJTINotExists
// return
// }
// if claims.StrictPath != path {
// err = ErrStrictPathNotMatch
// return
// }
// for k, v := range claims.StrictQuery {
// if query.Get(k) != v {
// err = ErrStrictQueryNotMatch
// return
// }
// }
// return
// }
9 changes: 9 additions & 0 deletions database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ type DB interface {
// the callback should not edit the record pointer
ForEachFileRecord(cb func(*FileRecord) error) error

// GetUsers() []*api.User
// GetUser(id string) *api.User
// AddUser(*api.User) error
// RemoveUser(id string) error
// ForEachUser(cb func(*api.User) error) error
// UpdateUserPassword(username string, password string) error
// UpdateUserPermissions(username string, permissions api.PermissionFlag) error
// VerifyUserPassword(userId string, comparator func(password string) bool) error

GetSubscribe(user string, client string) (*api.SubscribeRecord, error)
SetSubscribe(api.SubscribeRecord) error
RemoveSubscribe(user string, client string) error
Expand Down
2 changes: 1 addition & 1 deletion notify/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

package webpush
package webhook

import (
"bytes"
Expand Down
48 changes: 39 additions & 9 deletions runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,11 @@ import (
"github.com/LiterMC/go-openbmclapi/limited"
"github.com/LiterMC/go-openbmclapi/log"
"github.com/LiterMC/go-openbmclapi/notify"
"github.com/LiterMC/go-openbmclapi/notify/email"
"github.com/LiterMC/go-openbmclapi/notify/webhook"
"github.com/LiterMC/go-openbmclapi/notify/webpush"
"github.com/LiterMC/go-openbmclapi/storage"
"github.com/LiterMC/go-openbmclapi/token"
"github.com/LiterMC/go-openbmclapi/utils"
)

Expand Down Expand Up @@ -104,21 +107,48 @@ func NewRunner() *Runner {
r.database = database.NewMemoryDB()
} else if r.database, err = database.NewSqlDB(r.Config.Database.Driver, r.Config.Database.DSN); err != nil {
log.Errorf("Cannot connect to database: %v", err)
os.Exit(1)
}
}

// r.userManager =
// r.tokenManager =
webpushPlg := new(webpush.Plugin)
r.subManager = &subscriptionManager{
webpushPlg: webpushPlg,
DB: r.database,
}
r.notifyManager = notify.NewManager(dataDir, r.database, r.client.CachedClient(), "go-openbmclapi")
r.storageManager = storage.NewManager(storages)
if apiHMACKey, err := utils.LoadOrCreateHmacKey(dataDir, "server"); err != nil {
log.Errorf("Cannot load HMAC key: %v", err)
os.Exit(1)
} else {
r.tokenManager = token.NewDBManager("go-openbmclapi", apiHMACKey, r.database)
}
{
r.notifyManager = notify.NewManager(dataDir, r.database, r.client.CachedClient(), "go-openbmclapi")
r.notifyManager.AddPlugin(new(webhook.Plugin))
if r.Config.Notification.EnableEmail {
emailPlg, err := email.NewSMTP(r.Config.Notification.EmailSMTP, r.Config.Notification.EmailSMTPEncryption,
r.Config.Notification.EmailSender, r.Config.Notification.EmailSenderPassword)
if err != nil {
log.Errorf("Cannot init SMTP client: %v", err)
os.Exit(1)
}
r.notifyManager.AddPlugin(emailPlg)
}
r.notifyManager.AddPlugin(new(email.Plugin))
webpushPlg := new(webpush.Plugin)
r.notifyManager.AddPlugin(webpushPlg)

r.subManager = &subscriptionManager{
webpushPlg: webpushPlg,
DB: r.database,
}
}
{
storages := make([]storage.Storage, len(r.Config.Storages))
for i, s := range r.Config.Storages {
storages[i] = storage.NewStorage(s)
}
r.storageManager = storage.NewManager(storages)
}
r.statManager = cluster.NewStatManager()
if err := r.statManager.Load(dataDir); err != nil {
log.Errorf("Stat load failed:", err)
log.Errorf("Stat load failed: %v", err)
}
r.apiRateLimiter = limited.NewAPIRateMiddleWare(api.RealAddrCtxKey, "go-openbmclapi.cluster.logged.user" /* api/v0.loggedUserKey */)
return r
Expand Down
Loading

0 comments on commit 8cf633b

Please sign in to comment.