mirror of
https://github.com/Fishwaldo/mouthpiece.git
synced 2025-03-15 11:31:32 +00:00
go fmt repository
This commit is contained in:
parent
edc6c74fb3
commit
4ff78432bf
20 changed files with 164 additions and 186 deletions
|
@ -7,4 +7,4 @@ import (
|
|||
//go:generate npm run build
|
||||
|
||||
//go:embed dist
|
||||
var FrontEndFiles embed.FS
|
||||
var FrontEndFiles embed.FS
|
||||
|
|
|
@ -3,35 +3,35 @@ package app
|
|||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/filter"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/user"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/filter"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
"github.com/jinzhu/copier"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AppDetails struct {
|
||||
AppName string `doc:"Application Name" pattern:"^[a-z0-9]+$" gorm:"unique;uniqueIndex"`
|
||||
Status string `doc:"Status of Application" enum:"Enabled,Disabled" default:"Enabled"`
|
||||
AppName string `doc:"Application Name" pattern:"^[a-z0-9]+$" gorm:"unique;uniqueIndex"`
|
||||
Status string `doc:"Status of Application" enum:"Enabled,Disabled" default:"Enabled"`
|
||||
Description string `doc:"Description of Application"`
|
||||
Icon string `doc:"Icon of Application"`
|
||||
URL string `doc:"URL of Application"`
|
||||
Icon string `doc:"Icon of Application"`
|
||||
URL string `doc:"URL of Application"`
|
||||
}
|
||||
|
||||
type ApplicationFilters struct {
|
||||
gorm.Model `json:"-"`
|
||||
AppID uint `json:"-"`
|
||||
Name string
|
||||
gorm.Model `json:"-"`
|
||||
AppID uint `json:"-"`
|
||||
Name string
|
||||
}
|
||||
|
||||
type App struct {
|
||||
gorm.Model `json:"-"`
|
||||
gorm.Model `json:"-"`
|
||||
AppDetails
|
||||
AssociatedUsers []*user.User `gorm:"many2many:app_user;"`
|
||||
Filters []ApplicationFilters
|
||||
Filters []ApplicationFilters
|
||||
}
|
||||
|
||||
func InitializeApps() {
|
||||
|
@ -50,14 +50,14 @@ func FindApp(app_name string) (app *App, err error) {
|
|||
return app, tx.Error
|
||||
}
|
||||
|
||||
func AppExists(app_name string) (bool) {
|
||||
func AppExists(app_name string) bool {
|
||||
var app App
|
||||
tx := db.Db.First(&app, "app_name = ?", app_name)
|
||||
return tx.Error == nil
|
||||
}
|
||||
|
||||
func CreateApp(app AppDetails) (newapp *App, err error) {
|
||||
newapp, err = FindApp(app.AppName);
|
||||
newapp, err = FindApp(app.AppName)
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
Log.Info("Creating New App", "App", app)
|
||||
var dbApp App
|
||||
|
@ -66,10 +66,10 @@ func CreateApp(app AppDetails) (newapp *App, err error) {
|
|||
dbApp.AssociatedUsers = append(dbApp.AssociatedUsers, adminuser)
|
||||
normaluser, _ := user.GetUser("user@example.com")
|
||||
dbApp.AssociatedUsers = append(dbApp.AssociatedUsers, normaluser)
|
||||
if (filter.FindFilter("CopyShortMessage") != nil) {
|
||||
if filter.FindFilter("CopyShortMessage") != nil {
|
||||
dbApp.Filters = append(dbApp.Filters, ApplicationFilters{Name: "CopyShortMessage"})
|
||||
}
|
||||
if (filter.FindFilter("FindSeverity") != nil) {
|
||||
if filter.FindFilter("FindSeverity") != nil {
|
||||
dbApp.Filters = append(dbApp.Filters, ApplicationFilters{Name: "FindSeverity"})
|
||||
}
|
||||
result := db.Db.Create(&dbApp)
|
||||
|
@ -82,7 +82,7 @@ func CreateApp(app AppDetails) (newapp *App, err error) {
|
|||
return newapp, mperror.ErrAppExists
|
||||
}
|
||||
|
||||
func (app App) ProcessMessage(msg *msg.Message) (error) {
|
||||
func (app App) ProcessMessage(msg *msg.Message) error {
|
||||
Log.V(1).Info("App Processing Message", "App", app.AppName, "MessageID", msg.ID)
|
||||
/* populate Message Fields with App Data */
|
||||
msg.Body.Fields["app_description"] = app.Description
|
||||
|
@ -90,10 +90,10 @@ func (app App) ProcessMessage(msg *msg.Message) (error) {
|
|||
msg.Body.Fields["app_url"] = app.URL
|
||||
for _, appfilter := range app.Filters {
|
||||
flt := filter.FindFilter(appfilter.Name)
|
||||
if (flt != nil) {
|
||||
if flt != nil {
|
||||
Log.V(1).Info("App Processing Message with Filter", "Filter", appfilter)
|
||||
ok, _ := flt.ProcessMessage(msg);
|
||||
if (!ok) {
|
||||
ok, _ := flt.ProcessMessage(msg)
|
||||
if !ok {
|
||||
Log.Info("App Filter Blocked Message", "App", app.AppName, "Filter", appfilter, "Message", msg)
|
||||
return nil
|
||||
}
|
||||
|
@ -102,7 +102,7 @@ func (app App) ProcessMessage(msg *msg.Message) (error) {
|
|||
}
|
||||
}
|
||||
for _, user := range app.AssociatedUsers {
|
||||
user.ProcessMessage(*msg)
|
||||
user.ProcessMessage(*msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
|
@ -52,11 +52,11 @@ func (AL AuthLogger) Logf(format string, args ...interface{}) {
|
|||
}
|
||||
|
||||
type AuthConfig struct {
|
||||
CredChecker func(username string, password string) (ok bool, err error)
|
||||
CredChecker func(username string, password string) (ok bool, err error)
|
||||
MapClaimsToUser token.ClaimsUpdFunc
|
||||
Validator token.ValidatorFunc
|
||||
Host string
|
||||
ConfigDir fs.FS
|
||||
Validator token.ValidatorFunc
|
||||
Host string
|
||||
ConfigDir fs.FS
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
@ -99,7 +99,6 @@ func customGitHubProvider() (cred pkauth.Client, ch provider.CustomHandlerOpt) {
|
|||
return cred, ch
|
||||
}
|
||||
|
||||
|
||||
func InitAuth(Config AuthConfig) {
|
||||
AL = &AuthLogger{}
|
||||
AuthService = &Auth{}
|
||||
|
@ -107,7 +106,7 @@ func InitAuth(Config AuthConfig) {
|
|||
var avatarcachedir string
|
||||
if viper.IsSet("auth.avatar.cachedir") {
|
||||
avatarcachedir = viper.GetString("auth.avatar.cachedir")
|
||||
} else {
|
||||
} else {
|
||||
avatarcachedir, _ = os.MkdirTemp("", "mouthpiece_avatar")
|
||||
}
|
||||
options := pkauth.Opts{
|
||||
|
@ -118,14 +117,14 @@ func InitAuth(Config AuthConfig) {
|
|||
CookieDuration: time.Hour * 24, // cookie fine to keep for long time
|
||||
DisableXSRF: true, // don't disable XSRF in real-life applications!
|
||||
Issuer: "mouthpiece", // part of token, just informational
|
||||
URL: Config.Host, // base url of the protected service
|
||||
URL: Config.Host, // base url of the protected service
|
||||
//AdminPasswd: "password", // admin password
|
||||
AvatarStore: avatar.NewLocalFS(avatarcachedir), // stores avatars locally
|
||||
AvatarResizeLimit: 200, // resizes avatars to 200x200
|
||||
ClaimsUpd: token.ClaimsUpdFunc(Config.MapClaimsToUser),
|
||||
Validator: Config.Validator,
|
||||
Logger: AL, // optional logger for auth library
|
||||
UseGravatar: true, // for verified provider use gravatar service
|
||||
AvatarResizeLimit: 200, // resizes avatars to 200x200
|
||||
ClaimsUpd: token.ClaimsUpdFunc(Config.MapClaimsToUser),
|
||||
Validator: Config.Validator,
|
||||
Logger: AL, // optional logger for auth library
|
||||
UseGravatar: true, // for verified provider use gravatar service
|
||||
}
|
||||
|
||||
// create auth service
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package dbauth
|
||||
|
||||
import (
|
||||
"crypto/sha1" //nolint
|
||||
"crypto/rand"
|
||||
"crypto/sha1" //nolint
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mime"
|
||||
|
@ -13,8 +13,8 @@ import (
|
|||
"github.com/golang-jwt/jwt"
|
||||
|
||||
"github.com/go-pkgz/auth/logger"
|
||||
"github.com/go-pkgz/auth/token"
|
||||
"github.com/go-pkgz/auth/provider"
|
||||
"github.com/go-pkgz/auth/token"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -22,7 +22,6 @@ const (
|
|||
MaxHTTPBodySize = 1024 * 1024
|
||||
)
|
||||
|
||||
|
||||
type ICredChecker func(user string, password string) (ok bool, err error)
|
||||
|
||||
// DirectHandler implements non-oauth2 provider authorizing user in traditional way with storage
|
||||
|
@ -83,8 +82,8 @@ func (p DirectHandler) LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|||
userID := p.ProviderName + "_" + token.HashID(sha1.New(), creds.User)
|
||||
|
||||
u := token.User{
|
||||
Name: creds.User,
|
||||
ID: userID,
|
||||
Name: creds.User,
|
||||
ID: userID,
|
||||
Email: creds.User,
|
||||
}
|
||||
u, err = setAvatar(p.AvatarSaver, u, &http.Client{Timeout: 5 * time.Second})
|
||||
|
@ -196,4 +195,4 @@ func randToken() (string, error) {
|
|||
return "", fmt.Errorf("can't write randoms to sha1: %w", err)
|
||||
}
|
||||
return fmt.Sprintf("%x", s.Sum(nil)), nil
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package telegramauth
|
||||
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
@ -13,7 +13,6 @@ import (
|
|||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/go-pkgz/repeater"
|
||||
"github.com/go-pkgz/rest"
|
||||
|
@ -146,7 +145,7 @@ func (th *TelegramHandler) ProcessUpdate(ctx context.Context, textUpdate string)
|
|||
th.requests.data = make(map[string]tgAuthRequest)
|
||||
}
|
||||
th.requests.Unlock()
|
||||
|
||||
|
||||
fmt.Printf("Processing update: %s\n", textUpdate)
|
||||
|
||||
var updates telegramUpdate
|
||||
|
@ -511,4 +510,4 @@ func (tg *tgAPI) parseError(r io.Reader, statusCode int) error {
|
|||
return fmt.Errorf("unexpected telegram API status code %d", statusCode)
|
||||
}
|
||||
return fmt.Errorf("unexpected telegram API status code %d, error: %q", statusCode, tgErr.Description)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,30 +5,30 @@ import (
|
|||
)
|
||||
|
||||
type OAuthConfig struct {
|
||||
ClientID string `json:"clientid" doc:"OAuth Client ID"`
|
||||
ClientID string `json:"clientid" doc:"OAuth Client ID"`
|
||||
}
|
||||
|
||||
type FEConfig struct {
|
||||
OAuthProviders map[string]OAuthConfig `json:"oauthproviders" doc:"Provider OAuth Config for Frontend"`
|
||||
OAuthProviders map[string]OAuthConfig `json:"oauthproviders" doc:"Provider OAuth Config for Frontend"`
|
||||
}
|
||||
|
||||
func GetFEConfig() (config *FEConfig) {
|
||||
config = &FEConfig{}
|
||||
config.OAuthProviders = make(map[string]OAuthConfig)
|
||||
if (viper.GetBool("auth.github.enabled")) {
|
||||
if viper.GetBool("auth.github.enabled") {
|
||||
config.OAuthProviders["github"] = OAuthConfig{
|
||||
ClientID: viper.GetString("auth.github.client_id"),
|
||||
}
|
||||
}
|
||||
if (viper.GetBool("auth.google.enabled")) {
|
||||
if viper.GetBool("auth.google.enabled") {
|
||||
config.OAuthProviders["google"] = OAuthConfig{
|
||||
ClientID: viper.GetString("auth.google.client_id"),
|
||||
}
|
||||
}
|
||||
if (viper.GetBool("auth.dev.enabled")) {
|
||||
if viper.GetBool("auth.dev.enabled") {
|
||||
config.OAuthProviders["dev"] = OAuthConfig{
|
||||
ClientID: "123456",
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
ErrAppExists = errors.New("App Already Exists")
|
||||
ErrAppNotFound = errors.New("App Not Found")
|
||||
ErrAppExists = errors.New("App Already Exists")
|
||||
ErrAppNotFound = errors.New("App Not Found")
|
||||
ErrUserNotFound = errors.New("User Not Found")
|
||||
)
|
||||
)
|
||||
|
|
|
@ -9,9 +9,9 @@ import (
|
|||
"embed"
|
||||
"fmt"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
|
||||
"github.com/skx/evalfilter/v2"
|
||||
"github.com/skx/evalfilter/v2/object"
|
||||
|
@ -21,7 +21,6 @@ import (
|
|||
//go:embed scripts
|
||||
var ScriptFiles embed.FS
|
||||
|
||||
|
||||
type FilterType int
|
||||
|
||||
const (
|
||||
|
@ -35,14 +34,14 @@ func (ft FilterType) String() string {
|
|||
}
|
||||
|
||||
type Filter struct {
|
||||
gorm.Model `json:"-"`
|
||||
Name string
|
||||
Content string
|
||||
Type FilterType
|
||||
Enabled bool
|
||||
script *evalfilter.Eval `gorm:"-" json:"-"`
|
||||
ok bool `gorm:"-"`
|
||||
processedMessage *msg.Message `gorm:"-" json:"-"`
|
||||
gorm.Model `json:"-"`
|
||||
Name string
|
||||
Content string
|
||||
Type FilterType
|
||||
Enabled bool
|
||||
script *evalfilter.Eval `gorm:"-" json:"-"`
|
||||
ok bool `gorm:"-"`
|
||||
processedMessage *msg.Message `gorm:"-" json:"-"`
|
||||
}
|
||||
|
||||
var Filters []*Filter
|
||||
|
@ -82,9 +81,9 @@ func loadScriptFiles(files []string, scripttype FilterType) {
|
|||
// Create an evalfilter, with the script inside it.
|
||||
//
|
||||
flt = &Filter{
|
||||
Name: trimFileExtension(filepath.Base(script)),
|
||||
Content: string(content),
|
||||
Type: scripttype,
|
||||
Name: trimFileExtension(filepath.Base(script)),
|
||||
Content: string(content),
|
||||
Type: scripttype,
|
||||
}
|
||||
} else {
|
||||
Log.Info("Loading Filter Script from Databse", "type", scripttype, "filter", flt.Name)
|
||||
|
@ -176,12 +175,12 @@ func (ev *Filter) fnSetField(args []object.Object) object.Object {
|
|||
return &object.Void{}
|
||||
}
|
||||
|
||||
func (ev *Filter) fnClearField(args[] object.Object) object.Object {
|
||||
if (len(args) != 1) {
|
||||
func (ev *Filter) fnClearField(args []object.Object) object.Object {
|
||||
if len(args) != 1 {
|
||||
return &object.Null{}
|
||||
}
|
||||
// Type-check
|
||||
if (args[0].Type() != object.STRING) {
|
||||
if args[0].Type() != object.STRING {
|
||||
return &object.Null{}
|
||||
}
|
||||
fld := args[0].(*object.String).Value
|
||||
|
@ -194,12 +193,12 @@ func (ev *Filter) fnClearField(args[] object.Object) object.Object {
|
|||
return &object.Void{}
|
||||
}
|
||||
|
||||
func (ev *Filter) fnSetShortMessage(arg[] object.Object) object.Object {
|
||||
if (len(arg) != 1) {
|
||||
func (ev *Filter) fnSetShortMessage(arg []object.Object) object.Object {
|
||||
if len(arg) != 1 {
|
||||
return &object.Null{}
|
||||
}
|
||||
// Type-check
|
||||
if (arg[0].Type() != object.STRING) {
|
||||
if arg[0].Type() != object.STRING {
|
||||
return &object.Null{}
|
||||
}
|
||||
msg := arg[0].(*object.String).Value
|
||||
|
@ -208,12 +207,12 @@ func (ev *Filter) fnSetShortMessage(arg[] object.Object) object.Object {
|
|||
return &object.Void{}
|
||||
}
|
||||
|
||||
func (ev *Filter) fnSetSeverity(arg[] object.Object) object.Object {
|
||||
if (len(arg) != 1) {
|
||||
func (ev *Filter) fnSetSeverity(arg []object.Object) object.Object {
|
||||
if len(arg) != 1 {
|
||||
return &object.Null{}
|
||||
}
|
||||
// Type-check
|
||||
if (arg[0].Type() != object.STRING) {
|
||||
if arg[0].Type() != object.STRING {
|
||||
return &object.Null{}
|
||||
}
|
||||
msg := arg[0].(*object.String).Value
|
||||
|
@ -231,14 +230,14 @@ func (ev *Filter) ProcessMessage(msg *msg.Message) (bool, error) {
|
|||
Log.Error(err.(error), "Filter Script Error", "filter", ev.Name)
|
||||
}
|
||||
}()
|
||||
if (!ev.ok) {
|
||||
if !ev.ok {
|
||||
Log.Info("Filter Script Not ready", "filter", ev.Name)
|
||||
return true, nil
|
||||
}
|
||||
ev.processedMessage = msg
|
||||
ok, err := ev.script.Run(msg.Body)
|
||||
ev.processedMessage = nil
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
Log.Info("Filter Run Failed", "filter", ev.Name, "result", ok, "Error", err)
|
||||
return true, err
|
||||
}
|
||||
|
@ -266,4 +265,4 @@ func (ev *Filter) SetupEvalFilter() error {
|
|||
Log.Info("Compile Filter Script Success", "filter", ev.Name)
|
||||
ev.ok = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,9 +5,8 @@ import (
|
|||
_ "fmt"
|
||||
"time"
|
||||
|
||||
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
|
||||
"github.com/alexliesenfeld/health"
|
||||
|
||||
|
|
|
@ -2,10 +2,10 @@ package log
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/danielgtaylor/huma/middleware"
|
||||
"github.com/go-logr/logr"
|
||||
"github.com/go-logr/zapr"
|
||||
"go.uber.org/zap"
|
||||
"github.com/danielgtaylor/huma/middleware"
|
||||
)
|
||||
|
||||
var Log logr.Logger
|
||||
|
@ -13,10 +13,10 @@ var zapLog *zap.Logger
|
|||
|
||||
func InitLogger() {
|
||||
zapLog, err := middleware.NewDefaultLogger()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Initilize Logging Failed (%v)?", err))
|
||||
}
|
||||
Log = zapr.NewLogger(zapLog)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Initilize Logging Failed (%v)?", err))
|
||||
}
|
||||
Log = zapr.NewLogger(zapLog)
|
||||
|
||||
Log.Info("Logging Started")
|
||||
}
|
||||
Log.Info("Logging Started")
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
package msg
|
||||
|
||||
import (
|
||||
"time"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func InitializeMessage() {
|
||||
|
@ -15,21 +15,21 @@ func InitializeMessage() {
|
|||
|
||||
type Message struct {
|
||||
gorm.Model
|
||||
AppName string `path:"application" doc:"Application Name" Example:"MyApp"`
|
||||
Body struct {
|
||||
Message string `json:"message" doc:"Message to be Sent"`
|
||||
ShortMsg string `json:"shortmessage,omitempty" doc:"Short Message to be Sent"`
|
||||
Topic string `json:"topic,omitempty" doc:"Topic of Message"`
|
||||
Severity string `json:"severity,omitempty" doc:"Severity of Message" default:"INFO"`
|
||||
Timestamp time.Time `json:"timestamp,omitempty" doc:"Timestamp of Message"`
|
||||
Fields map[string]interface{} `json:"fields,omitempty" doc:"Additional Fields" gorm:"-"`
|
||||
} `json:"body" doc:"Message Body" gorm:"embedded"`
|
||||
AppName string `path:"application" doc:"Application Name" Example:"MyApp"`
|
||||
Body struct {
|
||||
Message string `json:"message" doc:"Message to be Sent"`
|
||||
ShortMsg string `json:"shortmessage,omitempty" doc:"Short Message to be Sent"`
|
||||
Topic string `json:"topic,omitempty" doc:"Topic of Message"`
|
||||
Severity string `json:"severity,omitempty" doc:"Severity of Message" default:"INFO"`
|
||||
Timestamp time.Time `json:"timestamp,omitempty" doc:"Timestamp of Message"`
|
||||
Fields map[string]interface{} `json:"fields,omitempty" doc:"Additional Fields" gorm:"-"`
|
||||
} `json:"body" doc:"Message Body" gorm:"embedded"`
|
||||
Result *MessageResult `json:"result,omitempty" doc:"Result of Message"`
|
||||
}
|
||||
|
||||
type MessageResult struct {
|
||||
MessageID uint `json:"message_id" doc:"Message ID"`
|
||||
Status string `json:"status" doc:"Status of Message"`
|
||||
MessageID uint `json:"message_id" doc:"Message ID"`
|
||||
Status string `json:"status" doc:"Status of Message"`
|
||||
}
|
||||
|
||||
func (msg *Message) ProcessMessage() (err error) {
|
||||
|
@ -43,4 +43,4 @@ func (msg *Message) ProcessMessage() (err error) {
|
|||
msg.Result = &MessageResult{MessageID: msg.ID, Status: "Queued"}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ package middleware
|
|||
|
||||
import (
|
||||
"context"
|
||||
// "fmt"
|
||||
// "fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/auth"
|
||||
|
@ -17,7 +17,6 @@ import (
|
|||
type Middleware struct {
|
||||
}
|
||||
|
||||
|
||||
type CtxUserValue struct{}
|
||||
|
||||
// Update user info in request context from go-pkgz/auth token.User to mouthpiece.User
|
||||
|
@ -30,21 +29,21 @@ func (a *Middleware) Update() func(http.Handler) http.Handler {
|
|||
if dbUser, err := user.GetUser(tknuser.Email); err != nil {
|
||||
Log.Info("DBUser Not Found", "token", tknuser, "error", err)
|
||||
ctx := huma.ContextFromRequest(w, r)
|
||||
/* do Something */
|
||||
/* do Something */
|
||||
ctx.WriteError(http.StatusForbidden, "User not found", err)
|
||||
return
|
||||
} else {
|
||||
ok, res, err := auth.AuthService.AuthEnforcer.EnforceEx(dbUser.Email, r.URL.Path, r.Method)
|
||||
Log.V(1).Info("Access Control", "result", ok, "Policy", res, "Error", err)
|
||||
if (!ok) {
|
||||
if !ok {
|
||||
huma.ContextFromRequest(w, r).WriteError(http.StatusForbidden, "Access Denied", err)
|
||||
return;
|
||||
return
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), CtxUserValue{}, tknuser))
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
return;
|
||||
} else {
|
||||
return
|
||||
} else {
|
||||
ctx := huma.ContextFromRequest(w, r)
|
||||
ctx.WriteError(http.StatusUnauthorized, "Access Denied")
|
||||
}
|
||||
|
@ -52,4 +51,4 @@ func (a *Middleware) Update() func(http.Handler) http.Handler {
|
|||
return http.HandlerFunc(fn)
|
||||
}
|
||||
return f
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package mouthpiece
|
||||
|
||||
import (
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/app"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
)
|
||||
|
||||
|
@ -13,4 +13,4 @@ func RouteMessage(msg *msg.Message) {
|
|||
} else {
|
||||
Log.Error(mperror.ErrAppNotFound, "App Not Found", "App", msg.AppName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,19 +1,15 @@
|
|||
package stdout
|
||||
|
||||
import (
|
||||
|
||||
"fmt"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/transport"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/transport"
|
||||
)
|
||||
|
||||
type StdoutTransport struct {
|
||||
|
||||
}
|
||||
|
||||
|
||||
func init() {
|
||||
tp := NewStdoutTransport()
|
||||
transport.RegisterTransport(tp)
|
||||
|
@ -39,10 +35,10 @@ func (t StdoutTransport) Start() {
|
|||
Log.Info("Transport Started", "name", t.GetName())
|
||||
}
|
||||
|
||||
func (t StdoutTransport) NewTransportConfig(){
|
||||
// user.TransportConfigs = append(user.TransportConfigs, mouthpiece.TransportConfig{
|
||||
// Transport: t.GetName(),
|
||||
// Config: user.Username,
|
||||
// })
|
||||
func (t StdoutTransport) NewTransportConfig() {
|
||||
// user.TransportConfigs = append(user.TransportConfigs, mouthpiece.TransportConfig{
|
||||
// Transport: t.GetName(),
|
||||
// Config: user.Username,
|
||||
// })
|
||||
return
|
||||
}
|
||||
|
|
|
@ -4,7 +4,6 @@ import (
|
|||
"fmt"
|
||||
// "os"
|
||||
|
||||
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/transport"
|
||||
|
@ -16,9 +15,7 @@ import (
|
|||
"github.com/mymmrac/telego/telegoutil"
|
||||
)
|
||||
|
||||
|
||||
type TelegramTransport struct {
|
||||
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
@ -76,11 +73,11 @@ func (t TelegramTransport) Start() {
|
|||
Log.Info("Transport Started", "name", t.GetName())
|
||||
}
|
||||
|
||||
func (t TelegramTransport) NewTransportConfig(){
|
||||
// user.TransportConfigs = append(user.TransportConfigs, mouthpiece.TransportConfig{
|
||||
// Transport: t.GetName(),
|
||||
// Config: user.Username,
|
||||
// })
|
||||
func (t TelegramTransport) NewTransportConfig() {
|
||||
// user.TransportConfigs = append(user.TransportConfigs, mouthpiece.TransportConfig{
|
||||
// Transport: t.GetName(),
|
||||
// Config: user.Username,
|
||||
// })
|
||||
}
|
||||
|
||||
func (t TelegramTransport) SendMessage(config transport.TransportConfig, msg msg.Message) (err error) {
|
||||
|
@ -89,4 +86,4 @@ func (t TelegramTransport) SendMessage(config transport.TransportConfig, msg msg
|
|||
fmt.Println("=========================================================")
|
||||
transport.UpdateTransportStatus(t, msg, "sent")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,17 +3,17 @@ package transport
|
|||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TransportConfig struct {
|
||||
gorm.Model `json:"-"`
|
||||
UserID uint `json:"-"`
|
||||
Transport string
|
||||
Config string
|
||||
gorm.Model `json:"-"`
|
||||
UserID uint `json:"-"`
|
||||
Transport string
|
||||
Config string
|
||||
}
|
||||
|
||||
type ITransport interface {
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/go-pkgz/auth/token"
|
||||
|
||||
)
|
||||
|
||||
func dbAuthProvider(user, pass string) (ok bool, err error) {
|
||||
|
@ -26,26 +25,26 @@ func dbAuthProvider(user, pass string) (ok bool, err error) {
|
|||
return true, nil
|
||||
}
|
||||
|
||||
// Called when the Tokens are created/refreshed.
|
||||
// Called when the Tokens are created/refreshed.
|
||||
func MapClaimsToUser(claims token.Claims) token.Claims {
|
||||
Log.Info("Map Claims To User", "claims", claims)
|
||||
// if claims.User != nil {
|
||||
// if user, err := GetUser(claims.User.Name); err != nil {
|
||||
// Log.Info("User not found", "user", claims.User.Name)
|
||||
// claims.User.SetBoolAttr("valid", false)
|
||||
// } else {
|
||||
// claims.User.SetStrAttr("backenduser", user.Username)
|
||||
// claims.User.SetBoolAttr("valid", true)
|
||||
// }
|
||||
// }
|
||||
// if claims.User != nil {
|
||||
// if user, err := GetUser(claims.User.Name); err != nil {
|
||||
// Log.Info("User not found", "user", claims.User.Name)
|
||||
// claims.User.SetBoolAttr("valid", false)
|
||||
// } else {
|
||||
// claims.User.SetStrAttr("backenduser", user.Username)
|
||||
// claims.User.SetBoolAttr("valid", true)
|
||||
// }
|
||||
// }
|
||||
return claims
|
||||
}
|
||||
|
||||
// called on every access to the API
|
||||
func UserValidator(token string, claims token.Claims) (bool) {
|
||||
func UserValidator(token string, claims token.Claims) bool {
|
||||
Log.Info("User Validator", "token", token, "claims", claims)
|
||||
if claims.User != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,46 +3,44 @@ package user
|
|||
import (
|
||||
"fmt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/internal/auth"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
. "github.com/Fishwaldo/mouthpiece/internal/log"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/message"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/transport"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/db"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/auth"
|
||||
"github.com/Fishwaldo/mouthpiece/internal/errors"
|
||||
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
|
||||
type User struct {
|
||||
gorm.Model `json:"-"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Email string `validate:"required,email"`
|
||||
FirstName string `validate:"required"`
|
||||
LastName string `validate:"required"`
|
||||
Password string `json:"-" writeOnly:"true" validate:"required"`
|
||||
gorm.Model `json:"-"`
|
||||
ID uint `gorm:"primarykey"`
|
||||
Email string `validate:"required,email"`
|
||||
FirstName string `validate:"required"`
|
||||
LastName string `validate:"required"`
|
||||
Password string `json:"-" writeOnly:"true" validate:"required"`
|
||||
TransportConfigs []transport.TransportConfig `json:"transports,omitempty" gorm:"many2many:user_transports;" validate:"-"`
|
||||
}
|
||||
|
||||
var AuthConfig auth.AuthConfig
|
||||
|
||||
func init() {
|
||||
AuthConfig = auth.AuthConfig {
|
||||
CredChecker: dbAuthProvider,
|
||||
AuthConfig = auth.AuthConfig{
|
||||
CredChecker: dbAuthProvider,
|
||||
MapClaimsToUser: MapClaimsToUser,
|
||||
Validator: UserValidator,
|
||||
Validator: UserValidator,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func CreateUser(user *User) error {
|
||||
validate := validator.New()
|
||||
if err := validate.Struct(user); err != nil {
|
||||
Log.Info("User Validation Error", "Error", err)
|
||||
return err;
|
||||
return err
|
||||
}
|
||||
tx := db.Db.Omit("Password").Create(&user)
|
||||
if tx.Error != nil {
|
||||
|
@ -53,7 +51,7 @@ func CreateUser(user *User) error {
|
|||
if err := dbuser.SetPassword(user.Password); err != nil {
|
||||
if tx := db.Db.Delete(&dbuser); tx.Error != nil {
|
||||
Log.Info("Error Deleting User after failed Password", "Error", tx.Error)
|
||||
return err;
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
@ -69,11 +67,11 @@ func CreateUser(user *User) error {
|
|||
|
||||
func (u *User) addUserRole(role string) bool {
|
||||
_, err := auth.AuthService.AuthEnforcer.AddRoleForUser(u.Email, fmt.Sprintf("role:%s", role))
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
Log.Info("Failed to add role for user", "email", u.Email, "role", role, "error", err)
|
||||
return false
|
||||
}
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
|
||||
func (u *User) CheckPassword(password string) bool {
|
||||
|
@ -89,7 +87,7 @@ func (u *User) CheckPassword(password string) bool {
|
|||
func (u *User) SetPassword(password string) error {
|
||||
Log.Info("Setting Password", "Email", u.Email)
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if (err != nil) {
|
||||
if err != nil {
|
||||
Log.Info("Error Generating SetPassword Hash", "Error", err)
|
||||
return err
|
||||
}
|
||||
|
@ -105,7 +103,7 @@ func InitializeUsers() {
|
|||
var count int64
|
||||
db.Db.Model(&User{}).Count(&count)
|
||||
Log.V(1).Info("Initializing Users", "count", count)
|
||||
if (count == 0) {
|
||||
if count == 0 {
|
||||
Log.Info("Creating Default Users")
|
||||
admin := &User{FirstName: "Admin", LastName: "User", Email: "admin@example.com", Password: "password"}
|
||||
if err := CreateUser(admin); err == nil {
|
||||
|
@ -116,7 +114,7 @@ func InitializeUsers() {
|
|||
Log.Info("Created Default User user@example.com")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetUsers() []User {
|
||||
var users []User
|
||||
|
@ -139,8 +137,6 @@ func GetUserByID(id uint) (user *User, err error) {
|
|||
return
|
||||
}
|
||||
|
||||
|
||||
|
||||
func (u User) ProcessMessage(msg msg.Message) (err error) {
|
||||
/* add User Fields to Message */
|
||||
msg.Body.Fields["first_name"] = u.FirstName
|
||||
|
@ -148,7 +144,7 @@ func (u User) ProcessMessage(msg msg.Message) (err error) {
|
|||
msg.Body.Fields["email"] = u.Email
|
||||
Log.V(1).Info("User Processing Message", "Email", u.Email, "MessageID", msg.ID)
|
||||
for _, tc := range u.TransportConfigs {
|
||||
t, err := transport.GetTransport(tc.Transport);
|
||||
t, err := transport.GetTransport(tc.Transport)
|
||||
if err != nil {
|
||||
Log.Info("Cant find Transport", "Transport", tc.Transport)
|
||||
}
|
||||
|
|
|
@ -202,4 +202,4 @@ func (i *Info) CheckFontName(fontName string) bool {
|
|||
|
||||
fmt.Fprintln(os.Stderr, "font not valid, using default")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
10
main.go
10
main.go
|
@ -28,16 +28,16 @@ import (
|
|||
//"fmt"
|
||||
// "context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
|
||||
// "reflect"
|
||||
"strings"
|
||||
// "unsafe"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"embed"
|
||||
|
||||
"github.com/Fishwaldo/mouthpiece/frontend"
|
||||
_ "github.com/Fishwaldo/mouthpiece/frontend"
|
||||
|
@ -66,11 +66,9 @@ import (
|
|||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
|
||||
//go:embed config
|
||||
var ConfigFiles embed.FS
|
||||
|
||||
|
||||
func init() {
|
||||
viper.SetDefault("frontend.path", "frontend/dist")
|
||||
viper.SetDefault("frontend.external", false)
|
||||
|
@ -103,7 +101,7 @@ func printBuildInfo() {
|
|||
fmt.Println("Getting build info failed (not in module mode?)!")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(bi); err != nil {
|
||||
|
@ -111,7 +109,6 @@ func printBuildInfo() {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
func main() {
|
||||
viper.SetConfigName("config")
|
||||
viper.SetConfigType("yaml")
|
||||
|
@ -141,7 +138,6 @@ func main() {
|
|||
|
||||
fmt.Println(bi.String())
|
||||
|
||||
|
||||
// Create a new router & CLI with default middleware.
|
||||
InitLogger()
|
||||
db.InitializeDB()
|
||||
|
|
Loading…
Add table
Reference in a new issue