Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
PORT=8080
ENV=development
API_URL=localhost:8080
FRONTEND_URL=http://localhost:5173/
CORS_ALLOWED_ORIGIN=http://localhost:5173

DB_ADDR=postgres://postgres:postgres@localhost:5432/psocial?sslmode=disable
DB_MAX_OPEN_CONNS=30
DB_MAX_IDLE_CONNS=30
DB_MAX_IDLE_TIME=15m

REDIS_ADDR=localhost:6379
REDIS_PW=
REDIS_DB=0
REDIS_ENABLED=true

BASIC_AUTH_USER=admin
BASIC_AUTH_PASS=change-me
JWT_SECRET=change-me

RATE_LIMIT_REQUESTS_COUNT=20
RATE_LIMIT_ENABLED=true

# Use "smtp" for Gmail or "sendgrid" for the existing provider.
MAIL_PROVIDER=smtp
MAIL_FROM_NAME=Psocial
MAIL_FROM_EMAIL=your-account@gmail.com

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-account@gmail.com
SMTP_PASSWORD=your-google-app-password

SENDGRID_API_KEY=
342 changes: 342 additions & 0 deletions README.md

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,25 @@ type basicAuthConfig struct {
}

type mailConfig struct {
provider string
sendGrid sendGridConfig
smtp smtpConfig
exp time.Duration
fromName string
fromEmail string
}

type sendGridConfig struct {
apiKey string
}

type smtpConfig struct {
host string
port int
username string
password string
}

type dbConfig struct {
addr string
maxOpenConns int
Expand All @@ -94,8 +104,8 @@ func (app *application) mount() *chi.Mux {
r.Use(middleware.ClientIPFromRemoteAddr)
r.Use(middleware.Recoverer)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{env.GetEnv("CORS_ALLOWED_ORIGIN", "http://localhost:5174")},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedOrigins: []string{env.GetEnv("CORS_ALLOWED_ORIGIN", "http://localhost:5173")},
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
Expand All @@ -121,11 +131,13 @@ func (app *application) mount() *chi.Mux {

r.Route("/users", func(r chi.Router) {
r.Put("/activate/{token}", app.activateUserHandler)
r.With(app.AuthTokenMiddleware).Get("/me", app.getCurrentUserHandler)

r.Route("/{userID}", func(r chi.Router) {
r.Use(app.AuthTokenMiddleware)

r.Get("/", app.getUserHandler)
r.Get("/relationship", app.getRelationshipHandler)
r.Put("/follow", app.followUserHandler)
r.Put("/unfollow", app.unfollowUserHandler)
})
Expand Down
14 changes: 5 additions & 9 deletions cmd/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"net/http"
"strings"
"time"

"github.com/golang-jwt/jwt/v5"
Expand Down Expand Up @@ -85,9 +85,7 @@ func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Reque
Token: plainToken,
}

activationURL := app.config.frontendURL + "/auth/activate?token=" + plainToken
isProduction := app.config.env == "production"

activationURL := strings.TrimRight(app.config.frontendURL, "/") + "/auth/activate?token=" + plainToken
vars := struct {
Username string
ActivationURL string
Expand All @@ -96,8 +94,7 @@ func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Reque
ActivationURL: activationURL,
}
//send mail
status, err := app.mailer.Send(mailer.UserWelcomeTemplate, user.Username, user.Email, vars, !isProduction)
if err != nil {
if err := app.mailer.Send(r.Context(), mailer.UserWelcomeTemplate, user.Username, user.Email, vars); err != nil {
app.logger.Errorw("failed to send welcome email", "error", err, "userID", user.ID)

// rollback the user creation by deleting the user from the database (SAGA pattern)
Expand All @@ -109,7 +106,7 @@ func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Reque
return
}

app.logger.Infow("Email sent", "status code", status)
app.logger.Infow("Email sent", "provider", app.config.mail.provider, "userID", user.ID)

if err := app.jsonResponse(w, http.StatusCreated, userWithToken); err != nil {
app.internalServerError(w, r, err)
Expand Down Expand Up @@ -155,7 +152,7 @@ func (app *application) createTokenHandler(w http.ResponseWriter, r *http.Reques
if err != nil {
switch err {
case store.ErrNotFound:
app.unauthorizedError(w, r, err)
app.notFoundError(w, r, err)
default:
app.internalServerError(w, r, err)
}
Comment on lines 154 to 158
Expand All @@ -164,7 +161,6 @@ func (app *application) createTokenHandler(w http.ResponseWriter, r *http.Reques

// verify password
if err := user.Password.Compare(payload.Password); err != nil {
log.Print("pass err: ", err)
app.unauthorizedError(w, r, fmt.Errorf("invalid Password"))
return
}
Expand Down
110 changes: 110 additions & 0 deletions cmd/api/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package main

import (
"context"
"database/sql"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/peterintech/psocial/internal/store"
"go.uber.org/zap"
)

type registrationMailer struct {
err error
calls int
}

func (m *registrationMailer) Send(context.Context, string, string, string, any) error {
m.calls++
return m.err
}

type registrationUserStore struct {
created bool
deleted bool
}

func (s *registrationUserStore) Create(context.Context, *sql.Tx, *store.User) error {
return nil
}

func (s *registrationUserStore) GetByID(context.Context, string) (*store.User, error) {
return nil, store.ErrNotFound
}

func (s *registrationUserStore) GetByEmail(context.Context, string) (*store.User, error) {
return nil, store.ErrNotFound
}

func (s *registrationUserStore) CreateAndInvite(_ context.Context, user *store.User, _ string, _ time.Duration) error {
s.created = true
user.ID = "test-user-id"
return nil
}

func (s *registrationUserStore) Activate(context.Context, string) error {
return nil
}

func (s *registrationUserStore) Delete(context.Context, string) error {
s.deleted = true
return nil
}

func TestRegisterUserMailDelivery(t *testing.T) {
tests := []struct {
name string
mailError error
wantStatus int
wantDeleted bool
}{
{name: "successful delivery", wantStatus: http.StatusCreated},
{name: "failed delivery rolls back user", mailError: errors.New("delivery failed"), wantStatus: http.StatusInternalServerError, wantDeleted: true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
users := &registrationUserStore{}
mailClient := &registrationMailer{err: tt.mailError}
app := &application{
config: config{
frontendURL: "http://localhost:5173/",
mail: mailConfig{
provider: "smtp",
exp: 72 * time.Hour,
},
},
store: store.Storage{Users: users},
logger: zap.NewNop().Sugar(),
mailer: mailClient,
}

req := httptest.NewRequest(http.MethodPost, "/v1/auth/register", strings.NewReader(`{
"username":"peter",
"email":"peter@example.com",
"password":"password123"
}`))
recorder := httptest.NewRecorder()

app.registerUserHandler(recorder, req)

if recorder.Code != tt.wantStatus {
t.Fatalf("expected status %d, got %d", tt.wantStatus, recorder.Code)
}
if !users.created {
t.Fatal("expected the user to be created")
}
if mailClient.calls != 1 {
t.Fatalf("expected one mail delivery attempt, got %d", mailClient.calls)
}
if users.deleted != tt.wantDeleted {
t.Fatalf("expected deleted=%t, got %t", tt.wantDeleted, users.deleted)
}
})
}
}
3 changes: 2 additions & 1 deletion cmd/api/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ func (app *application) createCommentHandler(w http.ResponseWriter, r *http.Requ
app.internalServerError(w, r, err)
return
}
user := app.getUserFromContext(r)

comment := &store.Comment{
Content: payload.Content,
PostID: post.ID,
UserID: post.UserID,
UserID: user.ID,
}

if err := app.store.Comments.Create(r.Context(), comment); err != nil {
Expand Down
3 changes: 2 additions & 1 deletion cmd/api/feeds.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ func (app *application) getFeedHandler(w http.ResponseWriter, r *http.Request) {
}

ctx := r.Context()
user := app.getUserFromContext(r)

feed, err := app.store.Posts.GetUserFeeds(ctx, "35", fq)
feed, err := app.store.Posts.GetUserFeeds(ctx, user.ID, fq)
if err != nil {
app.internalServerError(w, r, err)
return
Expand Down
26 changes: 26 additions & 0 deletions cmd/api/mailer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"fmt"
"strings"

"github.com/peterintech/psocial/internal/mailer"
)

func resolveNewMailer(cfg mailConfig) (mailer.Client, error) {
switch strings.ToLower(strings.TrimSpace(cfg.provider)) {
case "sendgrid":
return mailer.NewSendGridMailer(cfg.fromName, cfg.fromEmail, cfg.sendGrid.apiKey)
case "smtp":
return mailer.NewSMTPMailer(mailer.SMTPConfig{
Host: cfg.smtp.host,
Port: cfg.smtp.port,
Username: cfg.smtp.username,
Password: cfg.smtp.password,
FromName: cfg.fromName,
FromEmail: cfg.fromEmail,
})
default:
return nil, fmt.Errorf("unsupported MAIL_PROVIDER %q: expected sendgrid or smtp", cfg.provider)
}
}
54 changes: 54 additions & 0 deletions cmd/api/mailer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"strings"
"testing"

"github.com/peterintech/psocial/internal/mailer"
)

func TestResolveNewMailer(t *testing.T) {
t.Run("SMTP", func(t *testing.T) {
client, err := resolveNewMailer(mailConfig{
provider: "smtp",
fromName: "Psocial",
fromEmail: "sender@example.com",
smtp: smtpConfig{
host: "smtp.gmail.com",
port: 587,
username: "sender@example.com",
password: "app-password",
},
})
if err != nil {
t.Fatalf("resolveNewMailer returned an error: %v", err)
}
if _, ok := client.(*mailer.SMTPMailer); !ok {
t.Fatalf("expected SMTPMailer, got %T", client)
}
})

t.Run("SendGrid", func(t *testing.T) {
client, err := resolveNewMailer(mailConfig{
provider: "sendgrid",
fromName: "Psocial",
fromEmail: "sender@example.com",
sendGrid: sendGridConfig{
apiKey: "test-key",
},
})
if err != nil {
t.Fatalf("resolveNewMailer returned an error: %v", err)
}
if _, ok := client.(*mailer.SendGridMailer); !ok {
t.Fatalf("expected SendGridMailer, got %T", client)
}
})

t.Run("unsupported provider", func(t *testing.T) {
_, err := resolveNewMailer(mailConfig{provider: "unknown"})
if err == nil || !strings.Contains(err.Error(), "unsupported MAIL_PROVIDER") {
t.Fatalf("expected unsupported provider error, got %v", err)
}
})
}
Loading
Loading