Skip to content

Commit

Permalink
Fix env issues
Browse files Browse the repository at this point in the history
- add missing env vars to compose files
- add err checking in config package to exit if env vars missing
  • Loading branch information
GradeyCullins committed Oct 30, 2023
1 parent 4637e37 commit 680fb2e
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 71 deletions.
2 changes: 1 addition & 1 deletion .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/sh

if ! make test; then
echo "Please fix tests before committing."
echo "Please fix tests before committing."
exit 1
fi
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ pg-data/
secrets/
config/.env.prod
.DS_Store
.env
.env*
4 changes: 1 addition & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ WORKDIR /go/src/purity-vision
COPY . .

RUN go mod download
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o purity-vision .

# RUN GOOS=linux GOARCH=amd64 go build -o purity-vision .
RUN CGO_ENABLED=0 go build -a -installsuffix cgo -o purity-vision .

# Stage 2: Runtime
FROM alpine:latest
Expand Down
7 changes: 6 additions & 1 deletion compose.prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,19 @@ services:
secrets:
- google_credentials
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/run/secrets/google_credentials
- PURITY_DB_HOST=${PURITY_DB_HOST}
- PURITY_DB_PORT=${PURITY_DB_PORT}
- PURITY_DB_NAME=${PURITY_DB_NAME}
- PURITY_DB_USER=${PURITY_DB_USER}
- PURITY_DB_PASS=${PURITY_DB_PASS}
- PURITY_DB_SSL_MODE=${PURITY_DB_SSL_MODE}
- GOOGLE_APPLICATION_CREDENTIALS=/run/secrets/google_credentials
- PURITY_LOG_LEVEL=${PURITY_LOG_LEVEL}
- STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET}
- STRIPE_KEY=${STRIPE_KEY}
- EMAIL_NAME=${EMAIL_NAME}
- EMAIL_FROM=${EMAIL_FROM}
- SENDGRID_API_KEY=${SENDGRID_API_KEY}
db:
image: postgres:latest
hostname: postgres
Expand Down
8 changes: 6 additions & 2 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@ services:
secrets:
- google_credentials
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/run/secrets/google_credentials
- PURITY_DB_HOST=${PURITY_DB_HOST}
- PURITY_DB_PORT=${PURITY_DB_PORT}
- PURITY_DB_NAME=${PURITY_DB_NAME}
- PURITY_DB_USER=${PURITY_DB_USER}
- PURITY_DB_PASS=${PURITY_DB_PASS}
- PURITY_DB_SSL_MODE=${PURITY_DB_SSL_MODE}
- GOOGLE_APPLICATION_CREDENTIALS=/run/secrets/google_credentials
- PROJECT_ROOT=${PROJECT_ROOT}
- PURITY_LOG_LEVEL=${PURITY_LOG_LEVEL}
- STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET}
- STRIPE_KEY=${STRIPE_KEY}
- EMAIL_NAME=${EMAIL_NAME}
- EMAIL_FROM=${EMAIL_FROM}
- SENDGRID_API_KEY=${SENDGRID_API_KEY}
db:
image: postgres:latest
hostname: postgres
Expand Down
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ func main() {
log.Fatal().Err(err)
}

config.Init()
if err := config.Init(); err != nil {
log.Fatal().Msg(err.Error())
}

flag.IntVar(&portFlag, "port", config.DefaultPort, "port to run the service on")
flag.Parse()

Expand Down
58 changes: 37 additions & 21 deletions src/config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"fmt"
"os"
"strconv"

Expand Down Expand Up @@ -38,48 +39,63 @@ var (
// LogLevel is the level of logging for the application.
LogLevel string

// StripeKey is for making Stripe API requests.
StripeKey string

// Name on email license delivery
// Name on email license delivery.
EmailName string

// From address for email license delivery
// SendgridAPIKey is for sending emails.
SendgridAPIKey string

// Stripe webhook secret.
StripeWebhookSecret string

// From address for email license delivery.
EmailFrom string
)

func Init() {
// DefaultPort is the default port to expose the API server.
func Init() error {
DefaultPort = 8080

// DBHost is the host machine running the postgres instance.
DBHost = getEnvWithDefault("PURITY_DB_HOST", "localhost")

// DBPort is the port that exposes the db server.
DBPort = getEnvWithDefault("PURITY_DB_PORT", "5432")

// DBName is the postgres database name.
DBName = getEnvWithDefault("PURITY_DB_NAME", DefaultDBName)

// DBUser is the postgres user account.
DBUser = getEnvWithDefault("PURITY_DB_USER", "postgres")

// DBPassword is the password for the DBUser postgres account.
DBPassword = getEnvWithDefault("PURITY_DB_PASS", "")

// DBSSLMode sets the SSL mode of the postgres client.
DBSSLMode = getEnvWithDefault("PURITY_DB_SSL_MODE", "disable")

// LogLevel is the level of logging for the application.
LogLevel = getEnvWithDefault("PURITY_LOG_LEVEL", strconv.Itoa(int(zerolog.InfoLevel)))

StripeKey = os.Getenv("STRIPE_KEY")
missingEnvErr := func(envVar string) error {
return fmt.Errorf("%s not found in environment", envVar)
}

// Name on email license delivery
EmailName = getEnvWithDefault("EMAIL_NAME", "John Doe")
if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" {
return missingEnvErr("GOOGLE_APPLICATION_CREDENTIALS")
}

// From address for email license delivery
EmailFrom = getEnvWithDefault("EMAIL_FROM", "[email protected]")
if StripeKey = os.Getenv("STRIPE_KEY"); StripeKey == "" {
return missingEnvErr("STRIPE_KEY")
}

if StripeWebhookSecret = os.Getenv("STRIPE_WEBHOOK_SECRET"); StripeWebhookSecret == "" {
return missingEnvErr("STRIPE_WEBHOOK_SECRET")
}

if EmailName = getEnvWithDefault("EMAIL_NAME", "John Doe"); EmailName == "" {
return missingEnvErr("EMAIL_NAME")
}

if EmailFrom = getEnvWithDefault("EMAIL_FROM", "[email protected]"); EmailFrom == "" {
return missingEnvErr("EMAIL_FROM")
}

if SendgridAPIKey = os.Getenv("SENDGRID_API_KEY"); SendgridAPIKey == "" {
return missingEnvErr("SENDGRID_API_KEY")
}

return nil
}

func getEnvWithDefault(name string, def string) string {
Expand Down
11 changes: 3 additions & 8 deletions src/mail/mail.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package mail

import (
"fmt"
"os"
"purity-vision-filter/src/config"

"github.com/sendgrid/sendgrid-go"
Expand All @@ -19,20 +18,16 @@ type Email struct {

func SendMail(email Email) error {
from := mail.NewEmail(config.EmailName, config.EmailFrom)

to := mail.NewEmail(email.Name, email.To)
message := mail.NewSingleEmail(from, email.Subject, to, email.Plain, email.Html)
client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
client := sendgrid.NewSendClient(config.SendgridAPIKey)

_, err := client.Send(message)
if err != nil {
return err
} else {
// log.Println(response.StatusCode)
// log.Println(response.Body)
// log.Println(response.Headers)
return nil
}

return nil
}

func SendLicenseMail(emailTo string, licenseID string) error {
Expand Down
27 changes: 14 additions & 13 deletions src/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package server
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"os"
"purity-vision-filter/src/config"
"purity-vision-filter/src/images"
"purity-vision-filter/src/mail"
"purity-vision-filter/src/utils"
Expand All @@ -31,7 +32,7 @@ func removeDuplicates(vals []string) []string {
strMap := make(map[string]bool, 0)

for _, v := range vals {
if found := strMap[v]; found == true {
if found := strMap[v]; found {
logger.Debug().Msgf("Found duplicate image: %s in request. Removing.", v)
continue
}
Expand Down Expand Up @@ -99,16 +100,16 @@ func handleBatchFilter(logger zerolog.Logger) func(w http.ResponseWriter, req *h
func handleWebhook(w http.ResponseWriter, req *http.Request) {
const MaxBodyBytes = int64(65536)
req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes)
payload, err := ioutil.ReadAll(req.Body)
payload, err := io.ReadAll(req.Body)
if err != nil {
logger.Debug().Msgf("Error reading request body: %v", err)
w.WriteHeader(http.StatusServiceUnavailable)
return
}

endpointSecret := os.Getenv("STRIPE_WEBHOOK_SECRET")
event, err := webhook.ConstructEvent(payload, req.Header.Get("Stripe-Signature"),
endpointSecret)
// endpointSecret := os.Getenv("STRIPE_WEBHOOK_SECRET")
endpointSecret := config.StripeWebhookSecret
event, err := webhook.ConstructEvent(payload, req.Header.Get("Stripe-Signature"), endpointSecret)

if err != nil {
logger.Debug().Msgf("error verifying webhook signature: %v", err)
Expand All @@ -119,18 +120,18 @@ func handleWebhook(w http.ResponseWriter, req *http.Request) {
// Unmarshal the event data into an appropriate struct depending on its Type
switch event.Type {
// case "customer.subscription.created"
case "invoice.payment_succeeded":
invoice := stripe.Invoice{}
err := json.Unmarshal(event.Data.Raw, &invoice)
case "checkout.session.completed":
var session stripe.CheckoutSession
err := json.Unmarshal(event.Data.Raw, &session)
if err != nil {
fmt.Fprintf(w, "error parsing webhook JSON: %v", err)
fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}

subscriptionID := invoice.Subscription.ID
stripeID := invoice.Customer.ID
email := invoice.CustomerEmail
subscriptionID := session.Subscription.ID
stripeID := session.Customer.ID
email := session.CustomerDetails.Email

license, err := pgStore.GetLicenseByStripeID(stripeID)
if err != nil {
Expand Down
20 changes: 0 additions & 20 deletions src/vision/google_vision.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,14 @@ package vision

import (
"context"
"fmt"
"os"

vision "cloud.google.com/go/vision/apiv1"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
pb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

type BatchAnnotateResponse map[string]*pb.AnnotateImageResponse

func GetAnnoClient(ctx context.Context) (*vision.ImageAnnotatorClient, error) {
jwtConfig, err := google.JWTConfigFromJSON([]byte(os.Getenv("GOOGLE_CREDENTIALS")), vision.DefaultAuthScopes()...)
if err != nil {
fmt.Printf("JWTConfigFromJSON failed: %v", err)
return nil, err
}

// Create a new Vision client using the JWT config
client, err := vision.NewImageAnnotatorClient(ctx, option.WithTokenSource(jwtConfig.TokenSource(ctx)))
if err != nil {
fmt.Printf("NewImageAnnotatorClient: %v", err)
return nil, err
}

return client, nil
}

func BatchGetImgAnnotation(uris []string) (*pb.BatchAnnotateImagesResponse, error) {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
Expand Down

0 comments on commit 680fb2e

Please sign in to comment.