diff --git a/.env.example b/.env.example index 2a08eb1..a7a4272 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,31 @@ RUN_MIGRATIONS=false # Set to "false" to disable in read-only or maintenance mode ENABLE_WORKERS=true +# ============================================ +# Email Reminders (Optional) +# ============================================ +# SMTP configuration for sending email reminders +# If not configured, only push notifications will be sent + +# SMTP server hostname +SMTP_HOST=smtp.gmail.com + +# SMTP server port (usually 587 for TLS, 465 for SSL) +SMTP_PORT=587 + +# SMTP authentication credentials +SMTP_USER=your-email@gmail.com +SMTP_PASS=your-app-password + +# From address for outgoing emails +SMTP_FROM=noreply@yourdomain.com + +# Use TLS encryption (recommended: true) +SMTP_USE_TLS=true + +# App URL for email links (e.g., "View Promise" button) +APP_URL=https://yourdomain.com + # ============================================ # Web Push Notifications (VAPID) # ============================================ diff --git a/.gitignore b/.gitignore index 5989e6a..46bf659 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,5 @@ Thumbs.db # Other Project.md -Makefile \ No newline at end of file +Makefile +backend/test-email.sh \ No newline at end of file diff --git a/DEPLOY.md b/DEPLOY.md index 29644a7..09809af 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -21,6 +21,8 @@ services: - ALLOWED_ORIGINS=https://yourdomain.com - DISABLE_REGISTRATION=false - RUN_MIGRATIONS=false + # App URL for email links + - APP_URL=https://yourdomain.com volumes: - data:/data ports: @@ -40,6 +42,52 @@ volumes: - **Note:** Set all secrets (e.g., `JWT_SECRET`, `DB_ENCRYPTION_KEY`) securely, preferably using environment variables or Docker secrets. - The SQLite database is stored in the `kept-data` volume. The database file is encrypted if `DB_ENCRYPTION_KEY` is set. +- **SMTP Configuration:** Email reminders are optional. If SMTP variables are not set, only push notifications will be sent. + +--- + +## Email Reminder Setup (Optional) + +Kept can send email reminders in addition to push notifications. Configure these environment variables: + +```bash +SMTP_HOST=smtp.gmail.com # Your SMTP server +SMTP_PORT=587 # Usually 587 for TLS, 465 for SSL +SMTP_USER=your-email@gmail.com # SMTP username +SMTP_PASS=your-app-password # SMTP password or app password +SMTP_FROM=noreply@yourdomain.com # From address +SMTP_USE_TLS=true # Use TLS (recommended) +APP_URL=https://yourdomain.com # Your app URL for email links +``` + +### Common SMTP Providers: + +**Gmail:** +- Host: `smtp.gmail.com`, Port: `587` +- Enable 2FA and create an [App Password](https://support.google.com/accounts/answer/185833) + +**Outlook/Office365:** +- Host: `smtp-mail.outlook.com`, Port: `587` +- Use your account credentials + +**SendGrid:** +- Host: `smtp.sendgrid.net`, Port: `587` +- Username: `apikey`, Password: Your API key + +**Mailgun:** +- Host: `smtp.mailgun.org`, Port: `587` +- Use your Mailgun credentials + +### Testing Email Configuration: + +Once configured, test email sending via: +```bash +# Login to your Kept instance +curl -X POST http://localhost:3000/api/email/test \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" +``` + +Rate limit: Once per 10 minutes per server. --- @@ -121,6 +169,12 @@ Environment=JWT_SECRET=your_jwt_secret Environment=DB_ENCRYPTION_KEY=your_db_encryption_key Environment=JWT_REFRESH_SECRET=your_refresh_secret Environment=ALLOWED_ORIGINS=https://yourdomain.com +Environment=SMTP_HOST=smtp.gmail.com +Environment=SMTP_PORT=587 +Environment=SMTP_USER=your-email@gmail.com +Environment=SMTP_PASS=your-app-password +Environment=SMTP_FROM=noreply@yourdomain.com +Environment=APP_URL=https://yourdomain.com Restart=on-failure [Install] diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..08bd582 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,87 @@ +Attribution-NonCommercial-ShareAlike 4.0 International +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. +Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. +Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. +BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. +Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. +Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. +Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. +License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. +Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. +Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. +Licensor means the individual(s) or entity(ies) granting rights under this Public License. +NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. +Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. +Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. +You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. +Section 2 – Scope. +License grant. +Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: +reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and +produce, reproduce, and Share Adapted Material for NonCommercial purposes only. +Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. +Term. The term of this Public License is specified in Section 6(a). +Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. +Downstream recipients. +Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. +Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. +No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. +No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). +Other rights. +Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. +Patent and trademark rights are not licensed under this Public License. +To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. +Section 3 – License Conditions. +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +Attribution. +If You Share the Licensed Material (including in modified form), You must: + +retain the following if it is supplied by the Licensor with the Licensed Material: +identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); +a copyright notice; +a notice that refers to this Public License; +a notice that refers to the disclaimer of warranties; +a URI or hyperlink to the Licensed Material to the extent reasonably practicable; +indicate if You modified the Licensed Material and retain an indication of any previous modifications; and +indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. +You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. +If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. +ShareAlike. +In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + +The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. +You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. +You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. +Section 4 – Sui Generis Database Rights. +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; +if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and +You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. +Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. +To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. +The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. +Section 6 – Term and Termination. +This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. +Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + +automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or +upon express reinstatement by the Licensor. +For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. +Sections 1, 5, 6, 7, and 8 survive termination of this Public License. +Section 7 – Other Terms and Conditions. +The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. +Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. +Section 8 – Interpretation. +For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. +To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. +No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. +Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. \ No newline at end of file diff --git a/README.md b/README.md index cd5516d..64c2202 100644 --- a/README.md +++ b/README.md @@ -35,4 +35,6 @@ If this little app helps you keep what matters, I’d love to hear about it. — Made with love by Artur Flis -> **Disclaimer:** This app is **vibecoded** \ No newline at end of file +> **Disclaimer:** This app is **vibecoded** + +
\ No newline at end of file diff --git a/backend/Dockerfile b/backend/Dockerfile index cb9218c..81320f5 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -65,6 +65,9 @@ RUN ldconfig || true # Copy the binary from builder COPY --from=builder /app/main . +# Copy email template so runtime can load it +COPY --from=builder /app/reminder-email-template.html /root/reminder-email-template.html + # Create data directory RUN mkdir -p /root/data diff --git a/backend/go.mod b/backend/go.mod index 4d47ec9..8c66c18 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -22,4 +22,6 @@ require ( github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.69.0 // indirect golang.org/x/sys v0.40.0 // indirect + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect ) diff --git a/backend/go.sum b/backend/go.sum index b7ebfbb..3e886d2 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -98,3 +98,7 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= diff --git a/backend/internal/api/auth_handlers.go b/backend/internal/api/auth_handlers.go index 2b70839..39015d2 100644 --- a/backend/internal/api/auth_handlers.go +++ b/backend/internal/api/auth_handlers.go @@ -4,8 +4,8 @@ import ( "database/sql" "kept/internal/auth" "kept/internal/models" - "time" "log" + "time" "github.com/gofiber/fiber/v2" ) @@ -43,7 +43,7 @@ func RegisterHandler(db *sql.DB) fiber.Handler { if err != nil { return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate token") } - + days := auth.RefreshDays(req.Remember) refreshToken, err := auth.GenerateRefreshToken(int(userID), req.Username, days) if err != nil { @@ -54,7 +54,7 @@ func RegisterHandler(db *sql.DB) fiber.Handler { ID: int(userID), Username: req.Username, } - + // Persist refresh token in DB and set cookie expiresAt := time.Now().Add(time.Duration(days) * 24 * time.Hour) if err := StoreRefreshToken(db, int(userID), refreshToken, expiresAt, days); err != nil { @@ -87,10 +87,12 @@ func LoginHandler(db *sql.DB) fiber.Handler { // Get user var user models.User + + // Try to select with email column first, fall back if it doesn't exist err := db.QueryRow( - "SELECT id, username, password_hash FROM users WHERE username = ?", + "SELECT id, username, password_hash, COALESCE(email, '') FROM users WHERE username = ?", req.Username, - ).Scan(&user.ID, &user.Username, &user.PasswordHash) + ).Scan(&user.ID, &user.Username, &user.PasswordHash, &user.Email) if err == sql.ErrNoRows { return fiber.NewError(fiber.StatusUnauthorized, "Invalid username or password") @@ -109,7 +111,7 @@ func LoginHandler(db *sql.DB) fiber.Handler { if err != nil { return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate token") } - + // Determine TTL days based on remember flag days := auth.RefreshDays(req.Remember) refreshToken, err := auth.GenerateRefreshToken(user.ID, user.Username, days) diff --git a/backend/internal/api/email.go b/backend/internal/api/email.go new file mode 100644 index 0000000..8bd8b93 --- /dev/null +++ b/backend/internal/api/email.go @@ -0,0 +1,237 @@ +package api + +import ( + "bytes" + "database/sql" + "fmt" + "html/template" + "kept/internal/models" + "log" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "gopkg.in/gomail.v2" +) + +type EmailReminderData struct { + RecipientName string + Title string + Description string + DueDate string + DueDateRaw *time.Time + PromiseTo string + AppURL string + PromiseID int + Year int +} + +// LoadEmailTemplate loads and parses the email template +func LoadEmailTemplate() (*template.Template, error) { + templatePath := filepath.Join(".", "reminder-email-template.html") + + // Check if file exists + if _, err := os.Stat(templatePath); os.IsNotExist(err) { + return nil, fmt.Errorf("template file not found at %s", templatePath) + } + + tmpl, err := template.ParseFiles(templatePath) + if err != nil { + return nil, fmt.Errorf("failed to parse email template: %w", err) + } + return tmpl, nil +} + +// GenerateReminderEmail generates an HTML email for a promise reminder +func GenerateReminderEmail(promise models.Promise, appURL string) (string, error) { + tmpl, err := LoadEmailTemplate() + if err != nil { + return "", err + } + + // Format due date nicely + dueDateStr := "No due date set" + if promise.DueDate != nil { + dueDateStr = formatEmailDate(*promise.DueDate) + } + + data := EmailReminderData{ + RecipientName: "there", // Could be extracted from user data if available + Title: promise.Description, + Description: promise.Description, + DueDate: dueDateStr, + DueDateRaw: promise.DueDate, + PromiseTo: promise.Recipient, + AppURL: appURL, + PromiseID: promise.ID, + Year: time.Now().Year(), + } + + var buf bytes.Buffer + if err := tmpl.Execute(&buf, data); err != nil { + return "", fmt.Errorf("failed to execute email template: %w", err) + } + + return buf.String(), nil +} + +// formatEmailDate formats a time.Time for email display +func formatEmailDate(t time.Time) string { + now := time.Now() + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + thatDay := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) + + diffDays := int(thatDay.Sub(today).Hours() / 24) + + switch { + case diffDays == 0: + return fmt.Sprintf("Today at %s", t.Format("3:04 PM")) + case diffDays == 1: + return fmt.Sprintf("Tomorrow at %s", t.Format("3:04 PM")) + case diffDays == -1: + return fmt.Sprintf("Yesterday at %s", t.Format("3:04 PM")) + case diffDays > 1 && diffDays < 7: + return fmt.Sprintf("In %d days (%s)", diffDays, t.Format("Jan 2")) + case diffDays < -1 && diffDays > -7: + return fmt.Sprintf("%d days ago (%s)", -diffDays, t.Format("Jan 2")) + default: + if t.Year() == now.Year() { + return t.Format("January 2") + } + return t.Format("January 2, 2006") + } +} + +// SMTPConfig holds SMTP server configuration +type SMTPConfig struct { + Host string + Port int + Username string + Password string + From string + UseTLS bool +} + +// GetSMTPConfig reads SMTP configuration from environment variables +func GetSMTPConfig() (*SMTPConfig, error) { + host := os.Getenv("SMTP_HOST") + portStr := os.Getenv("SMTP_PORT") + username := os.Getenv("SMTP_USER") + password := os.Getenv("SMTP_PASS") + from := os.Getenv("SMTP_FROM") + useTLSStr := os.Getenv("SMTP_USE_TLS") + + if host == "" { + return nil, fmt.Errorf("SMTP_HOST not configured") + } + + port := 587 // Default SMTP port + if portStr != "" { + var err error + port, err = strconv.Atoi(portStr) + if err != nil { + return nil, fmt.Errorf("invalid SMTP_PORT: %w", err) + } + } + + if from == "" { + from = "noreply@kept.app" + } + + useTLS := true + if useTLSStr != "" { + useTLS = strings.ToLower(useTLSStr) != "false" + } + + return &SMTPConfig{ + Host: host, + Port: port, + Username: username, + Password: password, + From: from, + UseTLS: useTLS, + }, nil +} + +// SendReminderEmail sends an email reminder using configured SMTP server +func SendReminderEmail(db *sql.DB, promise models.Promise, userEmail string) error { + config, err := GetSMTPConfig() + if err != nil { + log.Printf("SMTP not configured, skipping email: %v", err) + return nil // Don't fail if email isn't configured + } + + appURL := getAppURL() + htmlContent, err := GenerateReminderEmail(promise, appURL) + if err != nil { + return fmt.Errorf("failed to generate email: %w", err) + } + + return sendSMTPEmail(config, userEmail, "Promise Reminder from Kept", htmlContent) +} + +// sendSMTPEmail sends an email via SMTP using gomail +func sendSMTPEmail(config *SMTPConfig, to, subject, htmlBody string) error { + m := gomail.NewMessage() + m.SetHeader("From", config.From) + m.SetHeader("To", to) + m.SetHeader("Subject", subject) + + // Plain text fallback + m.SetBody("text/plain", "Please view this email in an HTML-capable email client.") + + // HTML version (this is the important part for HTML rendering) + m.AddAlternative("text/html", htmlBody) + + // Create dialer with SMTP config + d := gomail.NewDialer(config.Host, config.Port, config.Username, config.Password) + + // Send the email + if err := d.DialAndSend(m); err != nil { + return fmt.Errorf("failed to send email: %w", err) + } + + return nil +} + +// getAppURL returns the application URL from environment or default +func getAppURL() string { + url := os.Getenv("APP_URL") + if url == "" { + url = "http://localhost:3000" + } + return url +} + +// Example: Extend reminder sending to include email option +func SendReminderWithEmail(db *sql.DB, promise models.Promise, userID int, sendEmail bool) error { + // Send push notification (existing behavior) + payload := PushPayload{ + Title: fmt.Sprintf("Reminder about your promise to: %s", promise.Recipient), + Body: promise.Description, + Icon: "/Static/logos/Kept Mascot Colored.svg", + Badge: "/Static/logos/Kept Mascot Colored.svg", + Tag: fmt.Sprintf("kept-reminder-%d", promise.ID), + Data: map[string]interface{}{"promise_id": promise.ID}, + } + + if err := SendPushToUser(db, userID, payload); err != nil { + log.Printf("Failed to send push notification: %v", err) + } + + // Optionally send email if enabled + if sendEmail { + // Get user email from database + var email sql.NullString + err := db.QueryRow("SELECT email FROM users WHERE id = ?", userID).Scan(&email) + if err == nil && email.Valid && email.String != "" { + if err := SendReminderEmail(db, promise, email.String); err != nil { + log.Printf("Failed to send email reminder: %v", err) + } + } + } + + return nil +} diff --git a/backend/internal/api/email_test_handler.go b/backend/internal/api/email_test_handler.go new file mode 100644 index 0000000..7f33b0b --- /dev/null +++ b/backend/internal/api/email_test_handler.go @@ -0,0 +1,127 @@ +package api + +import ( + "database/sql" + "fmt" + "kept/internal/models" + "regexp" + "sync" + "time" + + "github.com/gofiber/fiber/v2" +) + +var ( + lastEmailTestTime time.Time + emailTestMutex sync.Mutex +) + +// TestEmailHandler sends a test email to verify SMTP configuration +// Rate limited to once per 10 minutes per server +func TestEmailHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + // Rate limiting check + emailTestMutex.Lock() + timeSinceLastTest := time.Since(lastEmailTestTime) + if timeSinceLastTest < 10*time.Minute { + emailTestMutex.Unlock() + remaining := 10*time.Minute - timeSinceLastTest + return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{ + "error": "Email test rate limited", + "retry_after_seconds": int(remaining.Seconds()), + "message": fmt.Sprintf("Please wait %s before testing again", formatDuration(remaining)), + }) + } + lastEmailTestTime = time.Now() + emailTestMutex.Unlock() + + // Check if SMTP is configured + config, err := GetSMTPConfig() + if err != nil { + return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{ + "error": "SMTP not configured", + "message": "Please configure SMTP environment variables (SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROM)", + "details": err.Error(), + }) + } + + // Get user email from database + var userEmail sql.NullString + var username string + err = db.QueryRow("SELECT email, username FROM users WHERE id = ?", userID).Scan(&userEmail, &username) + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to get user data") + } + + if !userEmail.Valid || userEmail.String == "" { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "error": "No email address", + "message": "Your account does not have an email address set. Please update your profile.", + }) + } + + // Validate email format + if !isValidEmail(userEmail.String) { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{ + "error": "Invalid email address", + "message": "The email address on your account is not valid. Please update your profile with a valid email address.", + }) + } + + // Create a test promise for the email + now := time.Now() + tomorrow := now.Add(24 * time.Hour) + testPromise := models.Promise{ + ID: 0, // Test promise + Recipient: "yourself", + Description: "Test email reminder", + DueDate: &tomorrow, + CurrentState: "active", + } + + // Send test email + err = SendReminderEmail(db, testPromise, userEmail.String) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ + "error": "Failed to send test email", + "message": err.Error(), + }) + } + + return c.JSON(fiber.Map{ + "success": true, + "message": fmt.Sprintf("Test email sent successfully to %s", userEmail.String), + "smtp_config": fiber.Map{ + "host": config.Host, + "port": config.Port, + "from": config.From, + "tls": config.UseTLS, + }, + "note": "Check your inbox (and spam folder) for the test email", + }) + } +} + +// formatDuration formats a duration in a human-readable way +func formatDuration(d time.Duration) string { + if d < time.Minute { + return fmt.Sprintf("%d seconds", int(d.Seconds())) + } + minutes := int(d.Minutes()) + seconds := int(d.Seconds()) - (minutes * 60) + if seconds > 0 { + return fmt.Sprintf("%d minutes %d seconds", minutes, seconds) + } + return fmt.Sprintf("%d minutes", minutes) +} + +// isValidEmail checks if an email address is valid (simple regex) +func isValidEmail(email string) bool { + // Basic RFC 5322 regex for demonstration (not exhaustive) + // Accepts most common valid emails, rejects obvious invalid ones + re := `^[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$` + matched, _ := regexp.MatchString(re, email) + return matched +} diff --git a/backend/internal/api/migrations.go b/backend/internal/api/migrations.go index 178b9c2..f2e7557 100644 --- a/backend/internal/api/migrations.go +++ b/backend/internal/api/migrations.go @@ -74,4 +74,18 @@ func MigratePostponedToKept(db *sql.DB) error { } return tx.Commit() -} \ No newline at end of file +} + +// MigrateAddUserEmail adds email column to users table if it doesn't exist +func MigrateAddUserEmail(db *sql.DB) error { +exists, err := columnExists(db, "users", "email") +if err != nil { +return err +} +if !exists { +if _, err := db.Exec("ALTER TABLE users ADD COLUMN email TEXT"); err != nil { +return err +} +} +return nil +} diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.go index 026e919..4640387 100644 --- a/backend/internal/api/routes.go +++ b/backend/internal/api/routes.go @@ -58,8 +58,11 @@ func SetupRoutes(app *fiber.App, db *sql.DB) { push := protected.Group("/push") push.Post("/subscribe", SubscribePushHandler(db)) push.Delete("/unsubscribe", UnsubscribePushHandler(db)) - // Test endpoint for sending an actual push notification - push.Post("/test", SendTestPushHandler(db)) + + // User profile routes + user := protected.Group("/user") + user.Get("/profile", GetUserProfileHandler(db)) + user.Put("/email", UpdateUserEmailHandler(db)) // Health check app.Get("/health", func(c *fiber.Ctx) error { diff --git a/backend/internal/api/user_handlers.go b/backend/internal/api/user_handlers.go new file mode 100644 index 0000000..5a59f37 --- /dev/null +++ b/backend/internal/api/user_handlers.go @@ -0,0 +1,84 @@ +package api + +import ( + "database/sql" + + "github.com/gofiber/fiber/v2" +) + +type UpdateEmailRequest struct { + Email *string `json:"email"` +} + +// UpdateUserEmailHandler updates the user's email address +func UpdateUserEmailHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + var req UpdateEmailRequest + if err := c.BodyParser(&req); err != nil { + return fiber.NewError(fiber.StatusBadRequest, "Invalid request body") + } + + // Validate email format if provided + if req.Email != nil && *req.Email != "" { + email := *req.Email + // Basic email validation + if len(email) < 3 || len(email) > 254 { + return fiber.NewError(fiber.StatusBadRequest, "Invalid email format") + } + } + + // Update email in database + var emailValue interface{} + if req.Email == nil || *req.Email == "" { + emailValue = nil + } else { + emailValue = *req.Email + } + + _, err := db.Exec("UPDATE users SET email = ? WHERE id = ?", emailValue, userID) + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to update email") + } + + return c.JSON(fiber.Map{ + "success": true, + "message": "Email updated successfully", + }) + } +} + +// GetUserProfileHandler returns the current user's profile information +func GetUserProfileHandler(db *sql.DB) fiber.Handler { + return func(c *fiber.Ctx) error { + userID := c.Locals("userID").(int) + + var username string + var email sql.NullString + var createdAt string + + err := db.QueryRow( + "SELECT username, email, created_at FROM users WHERE id = ?", + userID, + ).Scan(&username, &email, &createdAt) + + if err != nil { + return fiber.NewError(fiber.StatusInternalServerError, "Failed to get user profile") + } + + profile := fiber.Map{ + "id": userID, + "username": username, + "created_at": createdAt, + } + + if email.Valid { + profile["email"] = email.String + } else { + profile["email"] = nil + } + + return c.JSON(profile) + } +} diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go index 5b17555..bbb69b6 100644 --- a/backend/internal/database/database.go +++ b/backend/internal/database/database.go @@ -75,6 +75,7 @@ func createTables(db *sql.DB) error { id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, + email TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); diff --git a/backend/internal/models/models.go b/backend/internal/models/models.go index 6abfadb..7dc0308 100644 --- a/backend/internal/models/models.go +++ b/backend/internal/models/models.go @@ -5,22 +5,23 @@ import "time" type User struct { ID int `json:"id"` Username string `json:"username"` + Email string `json:"email,omitempty"` PasswordHash string `json:"-"` CreatedAt time.Time `json:"created_at"` } type Promise struct { - ID int `json:"id"` - UserID int `json:"user_id"` - Recipient string `json:"recipient"` - Description string `json:"description"` - DueDate *time.Time `json:"due_date,omitempty"` - CurrentState string `json:"current_state"` + ID int `json:"id"` + UserID int `json:"user_id"` + Recipient string `json:"recipient"` + Description string `json:"description"` + DueDate *time.Time `json:"due_date,omitempty"` + CurrentState string `json:"current_state"` ReminderFrequency string `json:"reminder_frequency,omitempty"` LastRemindedAt *time.Time `json:"last_reminded_at,omitempty"` CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Events []Event `json:"events,omitempty"` + UpdatedAt time.Time `json:"updated_at"` + Events []Event `json:"events,omitempty"` } type Event struct { @@ -50,21 +51,21 @@ type PushSubscription struct { } type CreatePromiseRequest struct { - Recipient string `json:"recipient"` - Description string `json:"description"` - DueDate *time.Time `json:"due_date,omitempty"` - ReminderFrequency string `json:"reminder_frequency,omitempty"` + Recipient string `json:"recipient"` + Description string `json:"description"` + DueDate *time.Time `json:"due_date,omitempty"` + ReminderFrequency string `json:"reminder_frequency,omitempty"` } type UpdatePromiseStateRequest struct { - State string `json:"state"` - ReflectionNote string `json:"reflection_note,omitempty"` + State string `json:"state"` + ReflectionNote string `json:"reflection_note,omitempty"` NewDueDate *time.Time `json:"new_due_date,omitempty"` } type UpdatePromiseRequest struct { - ReminderFrequency *int `json:"reminder_frequency,omitempty"` - DueDate *time.Time `json:"due_date,omitempty"` + ReminderFrequency *int `json:"reminder_frequency,omitempty"` + DueDate *time.Time `json:"due_date,omitempty"` } type CreateReminderRequest struct { diff --git a/backend/main.go b/backend/main.go index d8ab6ca..f9600a3 100644 --- a/backend/main.go +++ b/backend/main.go @@ -23,8 +23,13 @@ func main() { defer db.Close() // Run migrations only if explicitly enabled (opt-in for safety) - runMigrations := os.Getenv("RUN_MIGRATIONS") == "true" - if runMigrations { + // Default to true if not set, to ensure schema is up to date + runMigrations := os.Getenv("RUN_MIGRATIONS") + if runMigrations == "" { + runMigrations = "true" + } + + if runMigrations == "true" { log.Println("Running database migrations...") if err := api.MigratePostponedToKept(db); err != nil { log.Printf("Migration error: %v", err) @@ -32,6 +37,9 @@ func main() { if err := api.MigrateAddReminderFrequency(db); err != nil { log.Printf("Migration error (reminder freq): %v", err) } + if err := api.MigrateAddUserEmail(db); err != nil { + log.Printf("Migration error (user email): %v", err) + } } else { log.Println("Migrations skipped (set RUN_MIGRATIONS=true to enable)") } diff --git a/backend/reminder-email-template.html b/backend/reminder-email-template.html new file mode 100644 index 0000000..ab6b6c7 --- /dev/null +++ b/backend/reminder-email-template.html @@ -0,0 +1,89 @@ + + + + + +| + + | +