2020-07-16 09:28:27 +02:00
|
|
|
package graph
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2020-09-04 10:10:32 +02:00
|
|
|
"forge.cadoles.com/Cadoles/daddy/internal/voter"
|
|
|
|
|
2020-07-21 18:10:03 +02:00
|
|
|
"forge.cadoles.com/Cadoles/daddy/internal/model"
|
2020-07-16 09:28:27 +02:00
|
|
|
"forge.cadoles.com/Cadoles/daddy/internal/orm"
|
2020-07-21 18:10:03 +02:00
|
|
|
"forge.cadoles.com/Cadoles/daddy/internal/session"
|
2020-07-16 09:28:27 +02:00
|
|
|
"github.com/jinzhu/gorm"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"gitlab.com/wpetit/goweb/middleware/container"
|
|
|
|
)
|
|
|
|
|
|
|
|
func getDB(ctx context.Context) (*gorm.DB, error) {
|
|
|
|
ctn, err := container.From(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
orm, err := orm.From(ctn)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return orm.DB(), nil
|
|
|
|
}
|
2020-07-21 18:10:03 +02:00
|
|
|
|
|
|
|
func getSessionUser(ctx context.Context) (*model.User, *gorm.DB, error) {
|
|
|
|
db, err := getDB(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
userEmail, err := session.UserEmail(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
repo := model.NewUserRepository(db)
|
|
|
|
|
|
|
|
user, err := repo.FindUserByEmail(ctx, userEmail)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return user, db, nil
|
|
|
|
}
|
2020-09-04 10:10:32 +02:00
|
|
|
|
|
|
|
func isAuthorized(ctx context.Context, obj interface{}, action interface{}) (bool, error) {
|
|
|
|
user, _, err := getSessionUser(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctn, err := container.From(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
voterSrv, err := voter.From(ctn)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
decision, err := voterSrv.Authorized(ctx, user, obj, action)
|
|
|
|
if err != nil {
|
|
|
|
return false, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if decision == voter.Allow {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil
|
|
|
|
}
|