This commit is contained in:
Preston Baxter 2023-11-16 19:45:48 -06:00
parent f703f2d1ab
commit 6f1ce7dcc1
21 changed files with 50 additions and 57 deletions

View File

@ -11,9 +11,9 @@ import (
) )
var ( var (
log *logrus.Logger log *logrus.Logger
mongo *db.DB mongo *db.DB
ytClientMap map[primitive.ObjectID]*youtube.Service ytClientMap map[primitive.ObjectID]*youtube.Service
pcoClientMap map[primitive.ObjectID]*pco.PcoApiClient pcoClientMap map[primitive.ObjectID]*pco.PcoApiClient
) )

View File

@ -11,10 +11,10 @@ import (
const PCO_API_URL = "https://api.planningcenteronline.com" const PCO_API_URL = "https://api.planningcenteronline.com"
type PcoApiClient struct { type PcoApiClient struct {
oauth *oauth2.Config oauth *oauth2.Config
tokenSource oauth2.TokenSource tokenSource oauth2.TokenSource
client *http.Client client *http.Client
url *url.URL url *url.URL
} }
func NewClient() *PcoApiClient { func NewClient() *PcoApiClient {
@ -25,7 +25,7 @@ func NewClient() *PcoApiClient {
pco := &PcoApiClient{ pco := &PcoApiClient{
oauth: &oauth2.Config{}, oauth: &oauth2.Config{},
url: pco_url, url: pco_url,
} }
return pco return pco
@ -38,9 +38,9 @@ func NewClientWithOauthConfig(conf *oauth2.Config, tokenSource oauth2.TokenSourc
} }
pco := &PcoApiClient{ pco := &PcoApiClient{
oauth: conf, oauth: conf,
tokenSource: tokenSource, tokenSource: tokenSource,
url: pco_url, url: pco_url,
} }
return pco return pco

View File

@ -8,7 +8,7 @@ import (
"github.com/google/jsonapi" "github.com/google/jsonapi"
) )
func (api *PcoApiClient) GetPlan(service_type_id, plan_id string) (*services.Plan, error){ func (api *PcoApiClient) GetPlan(service_type_id, plan_id string) (*services.Plan, error) {
api.Url().Path = fmt.Sprintf("/services/v2/service_types/%s/plans/%s", service_type_id, plan_id) api.Url().Path = fmt.Sprintf("/services/v2/service_types/%s/plans/%s", service_type_id, plan_id)
req, err := http.NewRequest(http.MethodGet, api.Url().String(), nil) req, err := http.NewRequest(http.MethodGet, api.Url().String(), nil)

View File

@ -1,6 +1,5 @@
package services package services
type Series struct { type Series struct {
Id string `jsonapi:"primary,Series"` Id string `jsonapi:"primary,Series"`
} }

View File

@ -1,6 +1,5 @@
package services package services
type ServiceType struct { type ServiceType struct {
Id string `jsonapi:"primary,ServiceType"` Id string `jsonapi:"primary,ServiceType"`
} }

View File

@ -7,7 +7,7 @@ import (
"github.com/google/jsonapi" "github.com/google/jsonapi"
) )
//Structure delivered to target when sending webhooks // Structure delivered to target when sending webhooks
type EventDelivery struct { type EventDelivery struct {
//uuid of the EventDelivery //uuid of the EventDelivery
ID string `jsonapi:"primary,EventDelivery"` ID string `jsonapi:"primary,EventDelivery"`
@ -22,7 +22,7 @@ type EventDelivery struct {
Organization *services.Organization `jsonapi:"relation,organization"` Organization *services.Organization `jsonapi:"relation,organization"`
} }
//Unmarshall payload of EventDelivery into the struct you think it is // Unmarshall payload of EventDelivery into the struct you think it is
func (event *EventDelivery) UnmarshallPayload(obj any) error { func (event *EventDelivery) UnmarshallPayload(obj any) error {
return jsonapi.UnmarshalPayload(strings.NewReader(event.Payload), obj) return jsonapi.UnmarshalPayload(strings.NewReader(event.Payload), obj)
} }

View File

@ -8,10 +8,10 @@ import (
const ( const (
STATUS_PRIVATE = "private" STATUS_PRIVATE = "private"
STATUS_PUBLIC = "public" STATUS_PUBLIC = "public"
) )
//Inserts Broadcast into youtube // Inserts Broadcast into youtube
func InsertBroadcast(service *youtube.Service, title string, startTime time.Time, privacyStatus string) (*youtube.LiveBroadcast, error) { func InsertBroadcast(service *youtube.Service, title string, startTime time.Time, privacyStatus string) (*youtube.LiveBroadcast, error) {
liveBroadcast := &youtube.LiveBroadcast{ liveBroadcast := &youtube.LiveBroadcast{
Snippet: &youtube.LiveBroadcastSnippet{ Snippet: &youtube.LiveBroadcastSnippet{

View File

@ -15,10 +15,10 @@ type config struct {
} }
type MongoConfig struct { type MongoConfig struct {
Uri string `mapstructure:"uri"` Uri string `mapstructure:"uri"`
EntDb string `mapstructure:"ent_db"` EntDb string `mapstructure:"ent_db"`
EntCol string `mapstructure:"ent_col"` EntCol string `mapstructure:"ent_col"`
LockDb string `mapstructure:"lock_db"` LockDb string `mapstructure:"lock_db"`
LockCol string `mapstructure:"lock_col"` LockCol string `mapstructure:"lock_col"`
} }
@ -44,13 +44,13 @@ func (vendor *VendorConfig) OauthConfig() *oauth2.Config {
return &oauth2.Config{ return &oauth2.Config{
ClientID: vendor.ClientId, ClientID: vendor.ClientId,
ClientSecret: vendor.ClientSecret, ClientSecret: vendor.ClientSecret,
Endpoint: oauth2.Endpoint{ Endpoint: oauth2.Endpoint{
AuthURL: vendor.AuthUri, AuthURL: vendor.AuthUri,
TokenURL: vendor.TokenUri, TokenURL: vendor.TokenUri,
AuthStyle: oauth2.AuthStyleInParams, AuthStyle: oauth2.AuthStyleInParams,
}, },
RedirectURL: "", RedirectURL: "",
Scopes: vendor.Scopes, Scopes: vendor.Scopes,
} }
} }

View File

@ -42,13 +42,13 @@ func AddActionFromForm(c *gin.Context) {
// //
am := &models.ActionMapping{ am := &models.ActionMapping{
UserId: user.Id, UserId: user.Id,
SourceEvent: &models.Event{ SourceEvent: &models.Event{
VendorName: source[0], VendorName: source[0],
Key: source[1], Key: source[1],
Fields: map[string]string{}, Fields: map[string]string{},
}, },
Action: &models.Action{ Action: &models.Action{
VendorName: action[0], VendorName: action[0],
Type: action[1], Type: action[1],
Fields: map[string]string{}, Fields: map[string]string{},

View File

@ -146,7 +146,6 @@ func LoginHandler(c *gin.Context) {
return return
} }
if user == nil { if user == nil {
log.Warnf("No user was found for: %s", reqBody.Email) log.Warnf("No user was found for: %s", reqBody.Email)
renderTempl(c, templates.LoginPage(fmt.Sprintf("No user found for %s", reqBody.Email))) renderTempl(c, templates.LoginPage(fmt.Sprintf("No user found for %s", reqBody.Email)))

View File

@ -46,12 +46,12 @@ func DashboardPage(c *gin.Context) {
waitGroup := new(sync.WaitGroup) waitGroup := new(sync.WaitGroup)
waitGroup.Add(2) waitGroup.Add(2)
go func(wg *sync.WaitGroup){ go func(wg *sync.WaitGroup) {
vendors, errs[0] = mongo.FindAllVendorAccountsByUser(user.MongoId()) vendors, errs[0] = mongo.FindAllVendorAccountsByUser(user.MongoId())
wg.Done() wg.Done()
}(waitGroup) }(waitGroup)
go func(wg *sync.WaitGroup){ go func(wg *sync.WaitGroup) {
actions, errs[1] = mongo.FindActionMappingsByUser(user.MongoId()) actions, errs[1] = mongo.FindActionMappingsByUser(user.MongoId())
wg.Done() wg.Done()
}(waitGroup) }(waitGroup)
@ -68,6 +68,5 @@ func DashboardPage(c *gin.Context) {
} }
} }
renderTempl(c, templates.DashboardPage(user, vendors, actions)) renderTempl(c, templates.DashboardPage(user, vendors, actions))
} }

View File

@ -94,7 +94,7 @@ func RecievePCOOuath(c *gin.Context) {
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Errorf("Response failed with status code: %d. Error: %s", resp.StatusCode ,string(rawBody)) log.Errorf("Response failed with status code: %d. Error: %s", resp.StatusCode, string(rawBody))
c.AbortWithStatus(502) c.AbortWithStatus(502)
return return
} }

View File

@ -106,12 +106,11 @@ func ReceiveYoutubeOauth(c *gin.Context) {
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Errorf("Response failed with status code: %d. Error: %s", resp.StatusCode ,string(rawBody)) log.Errorf("Response failed with status code: %d. Error: %s", resp.StatusCode, string(rawBody))
c.AbortWithStatus(502) c.AbortWithStatus(502)
return return
} }
oauthResp := &models.OauthCredential{} oauthResp := &models.OauthCredential{}
err = json.Unmarshal(rawBody, oauthResp) err = json.Unmarshal(rawBody, oauthResp)
if err != nil { if err != nil {

View File

@ -11,7 +11,7 @@ import (
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
) )
//Interface for any object that wants to take advantage of the DB package // Interface for any object that wants to take advantage of the DB package
type Model interface { type Model interface {
//Should return the _id field of the object if it exits //Should return the _id field of the object if it exits
@ -35,7 +35,7 @@ func NewClient(uri string) (*DB, error) {
return &DB{client: client}, nil return &DB{client: client}, nil
} }
//Upserts // Upserts
func (db *DB) SaveModel(m Model) error { func (db *DB) SaveModel(m Model) error {
conf := config.Config() conf := config.Config()
@ -81,7 +81,7 @@ func (db *DB) SaveModels(m ...Model) error {
return nil return nil
} }
//Doesn't upsert // Doesn't upsert
func (db *DB) InsertModel(m Model) error { func (db *DB) InsertModel(m Model) error {
conf := config.Config() conf := config.Config()

View File

@ -25,8 +25,8 @@ type Action struct {
} }
type Event struct { type Event struct {
VendorName string `bson:"vendor_name,omitempty"` VendorName string `bson:"vendor_name,omitempty"`
Key string `bson:"key,omitempty"` Key string `bson:"key,omitempty"`
Fields map[string]string `bson:"fields,omitempty"` Fields map[string]string `bson:"fields,omitempty"`
} }

View File

@ -10,7 +10,7 @@ const USER_TYPE string = "user"
type User struct { type User struct {
*CommonFields `bson:"obj_info"` *CommonFields `bson:"obj_info"`
Id primitive.ObjectID `bson:"_id"` Id primitive.ObjectID `bson:"_id"`
Email string `bson:"email,omitempty"` Email string `bson:"email,omitempty"`
PassowrdHash string `bson:"password_hash,omitempty"` PassowrdHash string `bson:"password_hash,omitempty"`
} }

View File

@ -50,5 +50,3 @@ func (va *VendorAccount) Token() *oauth2.Token {
Expiry: va.OauthCredentials.ExpiresAt, Expiry: va.OauthCredentials.ExpiresAt,
} }
} }

View File

@ -90,10 +90,10 @@ func (ts *VendorTokenSource) Token() (*oauth2.Token, error) {
return token, nil return token, nil
} }
//Allow us to check for kind of error at the end // Allow us to check for kind of error at the end
var TokenWaitExpired error = errors.New("Waiting for token to refresh took too long") var TokenWaitExpired error = errors.New("Waiting for token to refresh took too long")
//Used to extract the token lock that was updated when the change stream alerts // Used to extract the token lock that was updated when the change stream alerts
type tokenLockChangeEvent struct { type tokenLockChangeEvent struct {
TokenLock *models.TokenLock `bson:"fullDocument"` TokenLock *models.TokenLock `bson:"fullDocument"`
} }
@ -115,7 +115,7 @@ func (ts *VendorTokenSource) waitForToken(tl *models.TokenLock) error {
}, opts) }, opts)
if err != nil { if err != nil {
return err return err
} }
defer changeStream.Close(context.Background()) defer changeStream.Close(context.Background())

View File

@ -74,7 +74,7 @@ func TestRefreshToken(t *testing.T) {
wg := new(sync.WaitGroup) wg := new(sync.WaitGroup)
wg.Add(2) wg.Add(2)
go func(tkr oauth2.TokenSource, wg *sync.WaitGroup){ go func(tkr oauth2.TokenSource, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
var err error var err error
tk1, err = tkr.Token() tk1, err = tkr.Token()
@ -84,7 +84,7 @@ func TestRefreshToken(t *testing.T) {
} }
}(tkr1, wg) }(tkr1, wg)
go func(tkr oauth2.TokenSource, wg *sync.WaitGroup){ go func(tkr oauth2.TokenSource, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
var err error var err error
tk2, err = tkr.Token() tk2, err = tkr.Token()
@ -92,7 +92,7 @@ func TestRefreshToken(t *testing.T) {
t.Errorf("got err = %v; want none", err) t.Errorf("got err = %v; want none", err)
return return
} }
}(tkr2,wg) }(tkr2, wg)
wg.Wait() wg.Wait()

View File

@ -11,7 +11,7 @@ import (
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
) )
//seraches for a single user by email address // seraches for a single user by email address
func (db *DB) FindUserByEmail(email string) (*models.User, error) { func (db *DB) FindUserByEmail(email string) (*models.User, error) {
conf := config.Config() conf := config.Config()
@ -34,7 +34,7 @@ func (db *DB) FindUserByEmail(email string) (*models.User, error) {
return user, nil return user, nil
} }
//find user by its unique id // find user by its unique id
func (db *DB) FindUserById(id string) (*models.User, error) { func (db *DB) FindUserById(id string) (*models.User, error) {
conf := config.Config() conf := config.Config()
@ -44,7 +44,7 @@ func (db *DB) FindUserById(id string) (*models.User, error) {
return nil, err return nil, err
} }
res := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).FindOne(context.Background(), bson.M{"_id": objId , "obj_info.ent": models.USER_TYPE}, opts) res := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).FindOne(context.Background(), bson.M{"_id": objId, "obj_info.ent": models.USER_TYPE}, opts)
if res.Err() != nil { if res.Err() != nil {
if res.Err() == mongo.ErrNoDocuments { if res.Err() == mongo.ErrNoDocuments {
@ -62,7 +62,7 @@ func (db *DB) FindUserById(id string) (*models.User, error) {
return user, nil return user, nil
} }
//returns all users // returns all users
func (db *DB) FindAllUsers() ([]models.User, error) { func (db *DB) FindAllUsers() ([]models.User, error) {
conf := config.Config() conf := config.Config()

View File

@ -11,7 +11,7 @@ import (
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
) )
//return all vendor accounts for a user // return all vendor accounts for a user
func (db *DB) FindAllVendorAccountsByUser(userId primitive.ObjectID) ([]models.VendorAccount, error) { func (db *DB) FindAllVendorAccountsByUser(userId primitive.ObjectID) ([]models.VendorAccount, error) {
conf := config.Config() conf := config.Config()
@ -33,7 +33,7 @@ func (db *DB) FindAllVendorAccountsByUser(userId primitive.ObjectID) ([]models.V
return vendors, nil return vendors, nil
} }
//find vendor for user by name // find vendor for user by name
func (db *DB) FindVendorAccountByUser(userId primitive.ObjectID, name string) (*models.VendorAccount, error) { func (db *DB) FindVendorAccountByUser(userId primitive.ObjectID, name string) (*models.VendorAccount, error) {
conf := config.Config() conf := config.Config()
@ -55,7 +55,7 @@ func (db *DB) FindVendorAccountByUser(userId primitive.ObjectID, name string) (*
return vendor, nil return vendor, nil
} }
//find vendoraccount by its unique id // find vendoraccount by its unique id
func (db *DB) FindVendorAccountById(vendorId primitive.ObjectID) (*models.VendorAccount, error) { func (db *DB) FindVendorAccountById(vendorId primitive.ObjectID) (*models.VendorAccount, error) {
conf := config.Config() conf := config.Config()