diff options
| author | 2025-10-23 01:15:26 +0700 | |
|---|---|---|
| committer | 2025-10-23 01:15:26 +0700 | |
| commit | 0d261d2f7d080b610f50102576073e334a89e8cb (patch) | |
| tree | 3f86877a48cdb02486d6b5cb771a420c82c7eacf | |
| parent | 695889f42896c1e3f1290a588ac1c5483d0124f0 (diff) | |
| download | web-0d261d2f7d080b610f50102576073e334a89e8cb.tar.gz web-0d261d2f7d080b610f50102576073e334a89e8cb.zip | |
feat: email linking
41 files changed, 970 insertions, 240 deletions
diff --git a/.github/workflows/build-and-deploy-prod.yml b/.github/workflows/build-and-deploy-prod.yml index a180d39..27457c3 100644 --- a/.github/workflows/build-and-deploy-prod.yml +++ b/.github/workflows/build-and-deploy-prod.yml @@ -75,4 +75,4 @@ jobs: ANSIBLE_HOST_KEY_CHECKING: False working-directory: ./deploy run: | - ansible-playbook -i inventory.yml -l prod playbook.yml --private-key ~/.ssh/id_ed25519 -u svc_github -e saya_today_web_auth_salt=${{ secrets.AUTH_SALT }} -e saya_today_web_b2_key_id=${{ secrets.B2_KEY_ID }} -e saya_today_web_b2_application_key=${{ secrets.B2_APPLICATION_KEY }} -e saya_today_web_environment=prod -e saya_today_web_tag=${{ github.ref_name }} + ansible-playbook -i inventory.yml -l prod playbook.yml --private-key ~/.ssh/id_ed25519 -u svc_github -e saya_today_web_auth_salt=${{ secrets.AUTH_SALT }} -e saya_today_web_b2_key_id=${{ secrets.B2_KEY_ID }} -e saya_today_web_b2_application_key=${{ secrets.B2_APPLICATION_KEY }} -e saya_today_web_environment=prod -e saya_today_web_tag=${{ github.ref_name }} -e saya_today_web_mail_salt=${{ secrets.MAIL_SALT }} -e saya_today_web_mail_host=${{ secrets.MAIL_HOST }} -e saya_today_web_mail_address=${{ secrets.MAIL_ADDRESS }} -e saya_today_web_mail_username=${{ secrets.MAIL_USERNAME }} -e saya_today_web_mail_password=${{ secrets.MAIL_PASSWORD }} diff --git a/.github/workflows/build-and-deploy-stage.yml b/.github/workflows/build-and-deploy-stage.yml index 0aea0a4..5d8709d 100644 --- a/.github/workflows/build-and-deploy-stage.yml +++ b/.github/workflows/build-and-deploy-stage.yml @@ -86,4 +86,4 @@ jobs: ANSIBLE_HOST_KEY_CHECKING: False working-directory: ./deploy run: | - ansible-playbook -i inventory.yml -l stage playbook.yml --private-key ~/.ssh/id_ed25519 -u svc_github -e saya_today_web_auth_salt=${{ secrets.AUTH_SALT }} -e saya_today_web_b2_key_id=${{ secrets.B2_KEY_ID }} -e saya_today_web_b2_application_key=${{ secrets.B2_APPLICATION_KEY }} -e saya_today_web_environment=stage -e saya_today_web_tag=commit-${{ steps.ghss_vars.outputs.sha_short }} + ansible-playbook -i inventory.yml -l stage playbook.yml --private-key ~/.ssh/id_ed25519 -u svc_github -e saya_today_web_auth_salt=${{ secrets.AUTH_SALT }} -e saya_today_web_b2_key_id=${{ secrets.B2_KEY_ID }} -e saya_today_web_b2_application_key=${{ secrets.B2_APPLICATION_KEY }} -e saya_today_web_environment=stage -e saya_today_web_tag=commit-${{ steps.ghss_vars.outputs.sha_short }} -e saya_today_web_mail_salt=${{ secrets.MAIL_SALT }} -e saya_today_web_mail_host=${{ secrets.MAIL_HOST }} -e saya_today_web_mail_address=${{ secrets.MAIL_ADDRESS }} -e saya_today_web_mail_username=${{ secrets.MAIL_USERNAME }} -e saya_today_web_mail_password=${{ secrets.MAIL_PASSWORD }} diff --git a/config/config.go b/config/config.go index f57b5cd..d5dab2d 100644 --- a/config/config.go +++ b/config/config.go @@ -15,6 +15,7 @@ type Config struct { LocalePath string `json:"LocalePath" yaml:"localePath" validate:"required,filepath"` AvailableLanguages []AvailableLanguageConfig `json:"AvailableLanguages" yaml:"availableLanguages" validate:"required"` Auth AuthConfig `json:"Auth" yaml:"auth" validate:"required"` + Mail MailConfig `json:"Mail" yaml:"mail" validate:"required"` } type BlogPagesConfig struct { @@ -60,6 +61,16 @@ type Sqlite3Config struct { DSN string `json:"DSN" yaml:"dsn" validate:"required"` } +type MailConfig struct { + ClientHost string `json:"ClientHost" yaml:"clientHost" validate:"required"` + MailHost string `json:"MailHost" yaml:"mailHost" validate:"required"` + PublicName string `json:"PublicName" yaml:"publicName" validate:"required"` + MailAddress string `json:"MailAddress" yaml:"mailAddress" validate:"required"` + Username string `json:"Username" yaml:"username" validate:"required"` + Password string `json:"Password" yaml:"password" validate:"required"` + Salt string `json:"Salt" yaml:"salt" validate:"required"` +} + func LoadConfig(path string, config *Config) error { fileBytes, err := os.ReadFile(path) if err != nil { diff --git a/config/config.local.yaml b/config/config.local.yaml index 6d0abf3..008fa93 100644 --- a/config/config.local.yaml +++ b/config/config.local.yaml @@ -34,3 +34,11 @@ auth: config: dsn: 'file:/tmp/auth.db?cache=shared&mode=rwc' salt: '123' +mail: + clientHost: '127.0.0.1:3000' + mailHost: '${MAIL_HOST}' + publicName: 'LOCAL.SAYA.TODAY' + mailAddress: '${MAIL_ADDRESS}' + username: '${MAIL_USERNAME}' + password: '${MAIL_PASSWORD}' + salt: '${MAIL_SALT}' diff --git a/config/config.prod.yaml b/config/config.prod.yaml index 38981a8..4c0f425 100644 --- a/config/config.prod.yaml +++ b/config/config.prod.yaml @@ -34,3 +34,11 @@ auth: config: dsn: 'file:/data/auth.db?cache=private&mode=rwc&_locking_mode=EXCLUSIVE&_mutex=no&_auto_vacuum=2' salt: '${AUTH_SALT}' +mail: + clientHost: '${FQDN}' + mailHost: '${MAIL_HOST}' + publicName: 'SAYA.TODAY' + mailAddress: '${MAIL_ADDRESS}' + username: '${MAIL_USERNAME}' + password: '${MAIL_PASSWORD}' + salt: '${MAIL_SALT}' diff --git a/config/config.stage.yaml b/config/config.stage.yaml index b05edaf..003ec05 100644 --- a/config/config.stage.yaml +++ b/config/config.stage.yaml @@ -34,3 +34,11 @@ auth: config: dsn: 'file:/data/auth.db?cache=private&mode=rwc&_locking_mode=EXCLUSIVE&_mutex=no&_auto_vacuum=2' salt: '${AUTH_SALT}' +mail: + clientHost: '${FQDN}' + mailHost: '${MAIL_HOST}' + publicName: 'DEMO.SAYA.TODAY' + mailAddress: '${MAIL_ADDRESS}' + username: '${MAIL_USERNAME}' + password: '${MAIL_PASSWORD}' + salt: '${MAIL_SALT}' diff --git a/deploy/inventory.yml b/deploy/inventory.yml index dde952e..a1ecf5d 100644 --- a/deploy/inventory.yml +++ b/deploy/inventory.yml @@ -7,6 +7,7 @@ all: saya_today_web_name: sayana-web saya_today_web_hostname: sayana-web saya_today_web_ipv4_address: 172.16.0.18 + saya_today_web_listen_address: saya.today stage: hosts: @@ -15,3 +16,4 @@ all: saya_today_web_name: sayana-demo saya_today_web_hostname: sayana-demo saya_today_web_ipv4_address: 172.16.0.17 + saya_today_web_listen_address: demo.saya.today diff --git a/deploy/playbook.yml b/deploy/playbook.yml index dfceaf7..ff54078 100644 --- a/deploy/playbook.yml +++ b/deploy/playbook.yml @@ -18,6 +18,11 @@ B2_APPLICATION_KEY: "{{ saya_today_web_b2_application_key }}" ENVIRONMENT: "{{ saya_today_web_environment }}" AUTH_SALT: "{{ saya_today_web_auth_salt }}" + MAIL_HOST: "{{ saya_today_web_mail_host }}" + MAIL_USERNAME: "{{ saya_today_web_mail_username }}" + MAIL_PASSWORD: "{{ saya_today_web_mail_password }}" + MAIL_SALT: "{{ saya_today_web_mail_salt }}" + FQDN: "{{ saya_today_web_listen_address }}" network_mode: caddy networks: - name: caddy @@ -33,7 +33,8 @@ require ( github.com/stretchr/testify v1.10.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasthttp v1.65.0 // indirect + github.com/wneessen/go-mail v0.7.2 // indirect go.uber.org/atomic v1.7.0 // indirect golang.org/x/sys v0.35.0 // indirect - golang.org/x/text v0.28.0 // indirect + golang.org/x/text v0.29.0 // indirect ) @@ -59,6 +59,8 @@ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6Kllzaw github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.65.0 h1:j/u3uzFEGFfRxw79iYzJN+TteTJwbYkru9uDp3d0Yf8= github.com/valyala/fasthttp v1.65.0/go.mod h1:P/93/YkKPMsKSnATEeELUCkG8a7Y+k99uxNHVbKINr4= +github.com/wneessen/go-mail v0.7.2 h1:xxPnhZ6IZLSgxShebmZ6DPKh1b6OJcoHfzy7UjOkzS8= +github.com/wneessen/go-mail v0.7.2/go.mod h1:+TkW6QP3EVkgTEqHtVmnAE/1MRhmzb8Y9/W3pweuS+k= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= @@ -72,6 +74,8 @@ golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go new file mode 100644 index 0000000..450b818 --- /dev/null +++ b/internal/mailer/mailer.go @@ -0,0 +1,281 @@ +package mailer + +import ( + "crypto/rand" + "database/sql" + "encoding/base64" + "encoding/binary" + "fmt" + "log/slog" + "strconv" + "strings" + "sync" + "time" + + "github.com/SayaAndy/saya-today-web/internal/templatemanager" + "github.com/SayaAndy/saya-today-web/locale" + "github.com/dgraph-io/ristretto/v2" + "github.com/gofiber/fiber/v2" + "github.com/wneessen/go-mail" + "golang.org/x/crypto/argon2" +) + +type Mailer struct { + verificationCodes *ristretto.Cache[uint64, string] + db *sql.DB + tm *templatemanager.TemplateManager + mailClient *mail.Client + clientHost string + mailAddress string + publicName string + salt []byte + + lostMailMap map[string]struct { + Dur time.Duration + End time.Time + CodeExpiry time.Time + } + lostMailMapMutex sync.RWMutex + + hashMap map[string][]byte + hashMapMutex sync.RWMutex + + l map[string]*locale.LocaleConfig +} + +func NewMailer(db *sql.DB, clientHost string, mailHost string, publicName string, mailAddress string, username string, password string, salt []byte, localization map[string]*locale.LocaleConfig) (*Mailer, error) { + verificationCodes, err := ristretto.NewCache(&ristretto.Config[uint64, string]{ + NumCounters: 10000, + MaxCost: 1 << 20, // 1 MB + BufferItems: 64, + TtlTickerDurationInSec: 3600, + }) + if err != nil { + return nil, fmt.Errorf("fail to initialize cache for verification codes: %w", err) + } + + tm, err := templatemanager.NewTemplateManager(templatemanager.TemplateManagerTemplates{ + Name: "new-post", + Files: []string{"views/layouts/general-mail.html", "views/messages/new-post.html"}, + }, templatemanager.TemplateManagerTemplates{ + Name: "verify-email", + Files: []string{"views/layouts/general-mail.html", "views/messages/verify-email.html"}, + }) + if err != nil { + return nil, fmt.Errorf("fail to initialize template manager for message templating: %w", err) + } + + mailClient, err := mail.NewClient(mailHost, + mail.WithSMTPAuth(mail.SMTPAuthAutoDiscover), mail.WithTLSPortPolicy(mail.TLSMandatory), + mail.WithUsername(username), mail.WithPassword(password), + ) + if err != nil { + return nil, fmt.Errorf("fail to initialize mail client: %w", err) + } + + return &Mailer{ + verificationCodes: verificationCodes, + db: db, + clientHost: clientHost, + tm: tm, + mailClient: mailClient, + mailAddress: mailAddress, + publicName: publicName, + salt: salt, + hashMap: make(map[string][]byte), + lostMailMap: make(map[string]struct { + Dur time.Duration + End time.Time + CodeExpiry time.Time + }, 0), + l: localization}, nil +} + +func (m *Mailer) GetHash(id string) []byte { + m.hashMapMutex.RLock() + if val, ok := m.hashMap[id]; ok { + m.hashMapMutex.RUnlock() + slog.Debug("gave an old hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(val))) + return val + } + m.hashMapMutex.RUnlock() + + m.hashMapMutex.Lock() + defer m.hashMapMutex.Unlock() + + if val, ok := m.hashMap[id]; ok { + slog.Debug("gave a newly generated hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(val))) + return val + } + + m.hashMap[id] = argon2.IDKey([]byte(id), m.salt, 1, 64*1024, 4, 32) + slog.Debug("generated hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(m.hashMap[id]))) + return m.hashMap[id] +} + +func (m *Mailer) IsAllowedToRetryVerification(userId string) (retryAllowed bool, whenAllowed time.Time, codeExpiry time.Time) { + m.lostMailMapMutex.RLock() + defer m.lostMailMapMutex.RUnlock() + previous, ok := m.lostMailMap[userId] + if ok && previous.End.After(time.Now()) { + return false, previous.End, previous.CodeExpiry + } + return true, time.Time{}, previous.CodeExpiry +} + +func (m *Mailer) MailIsTaken(email string) (bool, error) { + tx, err := m.db.Begin() + if err != nil { + return false, fmt.Errorf("failed to initialize transaction with db: %s", err) + } + + var rows *sql.Rows + if rows, err = tx.Query(`SELECT email FROM user_email_table WHERE email=? LIMIT 1;`, email); err != nil { + tx.Rollback() + return false, fmt.Errorf("failed to query user-email settings in db: %s", err) + } + defer tx.Commit() + defer rows.Close() + + return rows.Next(), nil +} + +func (m *Mailer) GetInfo(userId string) (email string, lang string, err error) { + hash := m.GetHash(userId) + + tx, err := m.db.Begin() + if err != nil { + return "", "", fmt.Errorf("failed to initialize transaction with db: %s", err) + } + + var rows *sql.Rows + if rows, err = tx.Query(`SELECT email, lang FROM user_email_table WHERE user_id=? LIMIT 1;`, hash); err != nil { + tx.Rollback() + return "", "", fmt.Errorf("failed to query user-email settings in db: %s", err) + } + defer tx.Commit() + defer rows.Close() + + if !rows.Next() { + return "", "", nil + } + + if err = rows.Scan(&email, &lang); err != nil { + return "", "", fmt.Errorf("failed to scan the result from user-email settings query: %s", err) + } + return +} + +func (m *Mailer) SendVerificationCode(userId string, address string, lang string) error { + message := mail.NewMsg() + + if err := message.EnvelopeFrom(m.mailAddress); err != nil { + return fmt.Errorf("failed to set ENVELOPE FROM address: %w", err) + } + if err := message.FromFormat(m.publicName, m.mailAddress); err != nil { + return fmt.Errorf("failed to set formatted FROM address: %w", err) + } + if err := message.To(address); err != nil { + return fmt.Errorf("failed to set TO address: %w", err) + } + + message.SetMessageID() + message.SetDate() + message.SetBulk() + + dur := 1 * time.Minute + m.lostMailMapMutex.Lock() + if previous, ok := m.lostMailMap[userId]; ok { + if time.Now().Before(previous.End) { + m.lostMailMapMutex.Unlock() + return fmt.Errorf("user is not allowed to send another verification code until %s", previous.End) + } + dur = 2 * m.lostMailMap[userId].Dur + } + m.lostMailMap[userId] = struct { + Dur time.Duration + End time.Time + CodeExpiry time.Time + }{Dur: dur, End: time.Now().Add(dur), CodeExpiry: time.Now().Add(time.Hour)} + m.lostMailMapMutex.Unlock() + + verificationCodeBytes := make([]byte, 8) + rand.Read(verificationCodeBytes) + verificationCode := binary.LittleEndian.Uint64(verificationCodeBytes) + + verificationInfo := fmt.Sprintf("%s.%s", base64.RawStdEncoding.EncodeToString([]byte(userId)), base64.RawStdEncoding.EncodeToString([]byte(address))) + m.verificationCodes.Set(verificationCode, verificationInfo, int64(len(verificationInfo)+8)) + + message.Subject(m.l[lang].Mail.VerifyEmail.Subject) + + msg, err := m.tm.Render("verify-email", fiber.Map{ + "L": m.l[lang], + "Lang": lang, + "VerificationCode": fmt.Sprintf("%X", verificationCode), + "ClientHost": m.clientHost, + }) + if err != nil { + return fmt.Errorf("failed to render message body: %w", err) + } + + message.SetBodyString(mail.TypeTextHTML, string(msg)) + if err := m.mailClient.DialAndSend(message); err != nil { + return fmt.Errorf("failed to send verification code message: %w", err) + } + slog.Debug("verification code message successfully delivered", slog.String("address", address), slog.String("user_id", userId)) + return nil +} + +func (m *Mailer) Verify(verificationCodeEncoded string, lang string) error { + verificationCode, err := strconv.ParseUint(verificationCodeEncoded, 16, 64) + if err != nil { + return fmt.Errorf("failed to decode verification code from 8-byte hex: %w", err) + } + + verificationInfo, _ := m.verificationCodes.Get(verificationCode) + if verificationInfo == "" { + return fmt.Errorf("failed to get verification info by its code (might be absent, might be empty)") + } + + verificationSegments := strings.Split(verificationInfo, ".") + if len(verificationSegments) != 2 { + m.verificationCodes.Del(verificationCode) + return fmt.Errorf("invalid format of verification info: expected %d segments, got %d", 2, len(verificationSegments)) + } + + userId, err := base64.RawStdEncoding.DecodeString(verificationSegments[0]) + if err != nil { + m.verificationCodes.Del(verificationCode) + delete(m.lostMailMap, verificationSegments[0]) + return fmt.Errorf("could not decode user id: %s", err) + } + + address, err := base64.RawStdEncoding.DecodeString(verificationSegments[1]) + if err != nil { + m.verificationCodes.Del(verificationCode) + delete(m.lostMailMap, verificationSegments[0]) + return fmt.Errorf("could not decode address: %s", err) + } + + tx, err := m.db.Begin() + if err != nil { + return fmt.Errorf("failed to initialize transaction with db: %s", err) + } + + if _, err = tx.Exec(`INSERT INTO user_email_table(user_id, email, lang) VALUES(?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET + email=excluded.email, + lang=excluded.lang;`, m.GetHash(string(userId)), address, lang); err != nil { + tx.Rollback() + return fmt.Errorf("failed to configure user-email settings in db: %s", err) + } + + if err = tx.Commit(); err != nil { + tx.Rollback() + return fmt.Errorf("failed to commit transaction to db: %s", err) + } + + m.verificationCodes.Del(verificationCode) + delete(m.lostMailMap, verificationSegments[0]) + return nil +} diff --git a/internal/router/api-v1-blog-search.go b/internal/router/api-v1-blog-search.go index ab5425c..5b1d14d 100644 --- a/internal/router/api-v1-blog-search.go +++ b/internal/router/api-v1-blog-search.go @@ -17,7 +17,7 @@ import ( ) func init() { - tm.Add("catalogue-blog-cards", "views/partials/catalogue-blog-cards.html", "views/partials/catalogue-blog-card-tags.html") + assert(0, tm.Add("catalogue-blog-cards", "views/partials/catalogue-blog-cards.html", "views/partials/catalogue-blog-card-tags.html")) } func Api_V1_BlogSearch(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client) func(c *fiber.Ctx) error { diff --git a/internal/router/api-v1-email-is-in-verification.go b/internal/router/api-v1-email-is-in-verification.go new file mode 100644 index 0000000..83c783c --- /dev/null +++ b/internal/router/api-v1-email-is-in-verification.go @@ -0,0 +1,58 @@ +package router + +import ( + "fmt" + "net/url" + "strings" + + "github.com/SayaAndy/saya-today-web/locale" + "github.com/gofiber/fiber/v2" +) + +func init() { + assert(0, tm.Add("personal-page-status", "views/partials/personal-page-status.html")) +} + +func Api_V1_Email_IsInVerification(l map[string]*locale.LocaleConfig) func(c *fiber.Ctx) error { + return func(c *fiber.Ctx) error { + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + + id := c.IP() + lang := "en" + + var referer, path string + var pathParts []string + var urlStruct *url.URL + var err error + + referer = c.Get("Referer", "") + if referer == "" { + goto skipFetchingLang + } + + urlStruct, err = url.ParseRequestURI(referer) + if err != nil { + goto skipFetchingLang + } + + path = urlStruct.EscapedPath() + pathParts = strings.Split(strings.Trim(path, "/"), "/") + if len(pathParts) == 0 { + goto skipFetchingLang + } + + lang = pathParts[0] + + skipFetchingLang: + isAllowed, whenAllowed, codeExpiry := Mailer.IsAllowedToRetryVerification(id) + if !isAllowed { + return api_v1_email_sendStatusHtml(c, "email-message", l, "Neutral", fiber.StatusOK, lang, strings.ReplaceAll(l[lang].UserProfile.DelayTilVerification, "{}", whenAllowed.Format("2006-01-02 15:04:05 MST")), map[string]string{ + "striked-end-time": fmt.Sprint(whenAllowed.UnixMilli()), + "code-expiry-time": fmt.Sprint(codeExpiry.UnixMilli()), + }) + } + return api_v1_email_sendStatusHtml(c, "email-message", l, "OK", fiber.StatusOK, lang, "", map[string]string{ + "code-expiry-time": fmt.Sprint(codeExpiry.UnixMilli()), + }) + } +} diff --git a/internal/router/api-v1-email-send-verification-code.go b/internal/router/api-v1-email-send-verification-code.go new file mode 100644 index 0000000..2cde1bd --- /dev/null +++ b/internal/router/api-v1-email-send-verification-code.go @@ -0,0 +1,98 @@ +package router + +import ( + "fmt" + "html/template" + "log/slog" + "net/url" + "strings" + + "github.com/SayaAndy/saya-today-web/locale" + "github.com/gofiber/fiber/v2" +) + +func init() { + assert(0, tm.Add("personal-page-status", "views/partials/personal-page-status.html")) +} + +func Api_V1_Email_SendVerificationCode(l map[string]*locale.LocaleConfig) func(c *fiber.Ctx) error { + return func(c *fiber.Ctx) error { + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + + referer := c.Get("Referer", "") + if referer == "" { + return c.Status(fiber.ErrBadRequest.Code).SendString("'Referer' header is empty") + } + + urlStruct, err := url.ParseRequestURI(referer) + if err != nil { + return c.Status(fiber.ErrBadRequest.Code).SendString(fmt.Sprintf("'Referer' header is invalid: %s", err.Error())) + } + + path := urlStruct.EscapedPath() + pathParts := strings.Split(strings.Trim(path, "/"), "/") + if len(pathParts) != 2 { + return c.Status(fiber.ErrBadRequest.Code).SendString("'Referer' header is invalid: expect format '/{lang}/user'") + } + + lang := pathParts[0] + id := c.IP() + + email := c.FormValue("email") + if email == "" { + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.EmailEmpty, map[string]string{}) + } + + isTaken, err := Mailer.MailIsTaken(email) + if err != nil { + slog.Error("failed to check if address is already taken", slog.String("error", err.Error())) + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.VerificationCodeSendingError, map[string]string{}) + } + if isTaken { + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.EmailTaken, map[string]string{}) + } + + if isAllowed, whenAllowed, _ := Mailer.IsAllowedToRetryVerification(id); !isAllowed { + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, strings.ReplaceAll(l[lang].UserProfile.DelayTilVerification, "{}", whenAllowed.Format("2006-01-02 15:04:05 MST")), map[string]string{ + "striked-end-time": fmt.Sprint(whenAllowed.UnixMilli()), + }) + } + + if previousEmail, _, _ := Mailer.GetInfo(id); previousEmail == email { + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.EmailAlreadyValidated, map[string]string{}) + } + + if err = Mailer.SendVerificationCode(id, email, lang); err != nil { + slog.Error("failed to send a verification code", slog.String("error", err.Error())) + return api_v1_email_sendStatusHtml(c, "email-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.VerificationCodeSendingError, map[string]string{}) + } + + _, endTime, codeExpiry := Mailer.IsAllowedToRetryVerification(id) + return api_v1_email_sendStatusHtml(c, "email-message", l, "OK", fiber.StatusOK, lang, strings.ReplaceAll(l[lang].UserProfile.VerificationCodeSent, "{}", endTime.Format("2006-01-02 15:04:05 MST")), map[string]string{ + "striked-end-time": fmt.Sprint(endTime.UnixMilli()), + "code-expiry-time": fmt.Sprint(codeExpiry.UnixMilli()), + }) + } +} + +func api_v1_email_sendStatusHtml(c *fiber.Ctx, divId string, l map[string]*locale.LocaleConfig, status string, code int, lang string, message string, dataAttributes map[string]string) error { + sterileDataset := make(map[string]interface{}) + for k, v := range dataAttributes { + sterileDataset[k] = template.HTMLAttr(fmt.Sprintf("data-%s=\"%s\"", k, template.HTMLEscapeString(v))) + } + + content, err := tm.Render("personal-page-status", fiber.Map{ + "L": l[lang], + "Status": status, + "Message": message, + "StatusId": divId, + "DataAttributes": sterileDataset, + }) + if err != nil { + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + slog.Error("failed to render the email status message", slog.String("error", err.Error()), slog.String("div_id", divId), slog.String("message", message)) + return c.Status(fiber.ErrInternalServerError.Code).SendString("Failed to render the email status message, please ask administrator for a more detailed cause") + } + c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8) + return c.Status(code).Send(content) +} diff --git a/internal/router/api-v1-email-verify.go b/internal/router/api-v1-email-verify.go new file mode 100644 index 0000000..fad174b --- /dev/null +++ b/internal/router/api-v1-email-verify.go @@ -0,0 +1,52 @@ +package router + +import ( + "fmt" + "log/slog" + "net/url" + "strings" + + "github.com/SayaAndy/saya-today-web/locale" + "github.com/gofiber/fiber/v2" +) + +func init() { + assert(0, tm.Add("personal-page-status", "views/partials/personal-page-status.html")) +} + +func Api_V1_Email_Verify(l map[string]*locale.LocaleConfig) func(c *fiber.Ctx) error { + return func(c *fiber.Ctx) error { + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + + referer := c.Get("Referer", "") + if referer == "" { + return c.Status(fiber.ErrBadRequest.Code).SendString("'Referer' header is empty") + } + + urlStruct, err := url.ParseRequestURI(referer) + if err != nil { + return c.Status(fiber.ErrBadRequest.Code).SendString(fmt.Sprintf("'Referer' header is invalid: %s", err.Error())) + } + + path := urlStruct.EscapedPath() + pathParts := strings.Split(strings.Trim(path, "/"), "/") + if len(pathParts) != 2 { + return c.Status(fiber.ErrBadRequest.Code).SendString("'Referer' header is invalid: expect format '/{lang}/user'") + } + + lang := pathParts[0] + + verificationCode := c.FormValue("email_code") + if verificationCode == "" { + return api_v1_email_sendStatusHtml(c, "verification-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.VerificationEmpty, map[string]string{}) + } + + if err = Mailer.Verify(verificationCode, lang); err != nil { + slog.Error("verification code is invalid", slog.String("verification_code", verificationCode), slog.String("error", err.Error())) + return api_v1_email_sendStatusHtml(c, "verification-message", l, "Failed", fiber.ErrUnprocessableEntity.Code, lang, l[lang].UserProfile.VerificationFailed, map[string]string{}) + } + return api_v1_email_sendStatusHtml(c, "verification-message", l, "OK", fiber.StatusOK, lang, l[lang].UserProfile.VerificationSuccess, map[string]string{ + "hide-verification-panel": "true", + }) + } +} diff --git a/internal/router/api-v1-general-page-body.go b/internal/router/api-v1-general-page-body.go index fe21957..6f856d3 100644 --- a/internal/router/api-v1-general-page-body.go +++ b/internal/router/api-v1-general-page-body.go @@ -1,6 +1,7 @@ package router import ( + "bytes" "fmt" "html/template" "log/slog" @@ -14,15 +15,18 @@ import ( "github.com/SayaAndy/saya-today-web/config" "github.com/SayaAndy/saya-today-web/internal/b2" "github.com/SayaAndy/saya-today-web/internal/factgiver" + "github.com/SayaAndy/saya-today-web/internal/frontmatter" + "github.com/SayaAndy/saya-today-web/internal/mailer" "github.com/SayaAndy/saya-today-web/locale" "github.com/gofiber/fiber/v2" "github.com/yuin/goldmark" ) var FactGiver *factgiver.FactGiver +var Mailer *mailer.Mailer func init() { - tm.Add("general-page-body", "views/partials/general-page-body.html") + assert(0, tm.Add("general-page-body", "views/partials/general-page-body.html")) } func Api_V1_GeneralPage_Body(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client, md goldmark.Markdown) func(c *fiber.Ctx) error { @@ -39,15 +43,16 @@ func Api_V1_GeneralPage_Body(l map[string]*locale.LocaleConfig, langs []config.A } path := urlStruct.EscapedPath() + trimmedPath := strings.Trim(path, "/") - cacheKey := fmt.Sprintf("body.%s", path) - if val, ok := PCache.Get(cacheKey); val != nil && ok { + cacheKey := fmt.Sprintf("body.%s", trimmedPath) + if val, ok := PCache.Get(cacheKey); !strings.HasSuffix(trimmedPath, "user") && val != nil && ok { c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8) return c.Status(fiber.StatusOK).Type("html").Send(val) } lang := "" - pathParts := strings.Split(strings.Trim(path, "/"), "/") + pathParts := strings.Split(trimmedPath, "/") if len(pathParts) == 1 && pathParts[0] == "" { pathParts = []string{} } @@ -123,6 +128,17 @@ func Api_V1_GeneralPage_Body(l map[string]*locale.LocaleConfig, langs []config.A values["Title"] = l[lang].BlogSearch.Header additionalTemplates = append(additionalTemplates, "views/pages/blog-catalogue.html") + } else if len(pathParts) == 2 && pathParts[1] == "user" { + values["Title"] = l[lang].UserProfile.Header + + email, _, err := Mailer.GetInfo(c.IP()) + if err != nil { + slog.Error("get info from mailer about a client", slog.String("error", err.Error())) + } + values["Email"] = email + values["EmailCode"] = c.Query("email_code") + + additionalTemplates = append(additionalTemplates, "views/pages/user-page.html") } else if len(pathParts) == 3 && pathParts[1] == "blog" { metadata, parsedMarkdown, err := readBlogPost(md, b2Client, lang+"/"+pathParts[2]) if err != nil { @@ -174,3 +190,17 @@ func Api_V1_GeneralPage_Body(l map[string]*locale.LocaleConfig, langs []config.A return c.Status(fiber.StatusOK).Type("html").Send(content) } } + +func readBlogPost(md goldmark.Markdown, b2Client *b2.B2Client, sourceName string) (metadata *frontmatter.Metadata, html string, err error) { + metadata, markdown, err := b2Client.ReadFrontmatter(sourceName + ".md") + if err != nil { + return nil, "", fmt.Errorf("failed to read a frontmatter file: %w", err) + } + + var buf bytes.Buffer + if err := md.Convert(markdown, &buf); err != nil { + return nil, "", fmt.Errorf("convert source context from md to html: %w", err) + } + + return metadata, buf.String(), nil +} diff --git a/internal/router/api-v1-general-page-bottom-embeds.go b/internal/router/api-v1-general-page-bottom-embeds.go index 0a2030f..b408187 100644 --- a/internal/router/api-v1-general-page-bottom-embeds.go +++ b/internal/router/api-v1-general-page-bottom-embeds.go @@ -14,7 +14,7 @@ import ( ) func init() { - tm.Add("general-page-bottom-embeds", "views/partials/general-page-bottom-embeds.html") + assert(0, tm.Add("general-page-bottom-embeds", "views/partials/general-page-bottom-embeds.html")) } func Api_V1_GeneralPage_BottomEmbeds(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client) func(c *fiber.Ctx) error { @@ -63,6 +63,8 @@ func Api_V1_GeneralPage_BottomEmbeds(l map[string]*locale.LocaleConfig, langs [] if len(pathParts) == 2 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-catalogue.html") + } else if len(pathParts) == 2 && pathParts[1] == "user" { + additionalTemplates = append(additionalTemplates, "views/pages/user-page.html") } else if len(pathParts) == 3 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-page.html") } else if len(pathParts) == 1 { diff --git a/internal/router/api-v1-general-page-footer.go b/internal/router/api-v1-general-page-footer.go index 2030b3b..99d899a 100644 --- a/internal/router/api-v1-general-page-footer.go +++ b/internal/router/api-v1-general-page-footer.go @@ -13,7 +13,7 @@ import ( ) func init() { - tm.Add("general-page-footer", "views/partials/general-page-footer.html") + assert(0, tm.Add("general-page-footer", "views/partials/general-page-footer.html")) } func Api_V1_GeneralPage_Footer(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig) func(c *fiber.Ctx) error { @@ -63,6 +63,8 @@ func Api_V1_GeneralPage_Footer(l map[string]*locale.LocaleConfig, langs []config if len(pathParts) == 2 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-catalogue.html") + } else if len(pathParts) == 2 && pathParts[1] == "user" { + additionalTemplates = append(additionalTemplates, "views/pages/user-page.html") } else if len(pathParts) == 3 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-page.html") } else if len(pathParts) == 1 { diff --git a/internal/router/api-v1-general-page-header.go b/internal/router/api-v1-general-page-header.go index a2c832b..768417d 100644 --- a/internal/router/api-v1-general-page-header.go +++ b/internal/router/api-v1-general-page-header.go @@ -14,7 +14,7 @@ import ( ) func init() { - tm.Add("general-page-header", "views/partials/general-page-header.html") + assert(0, tm.Add("general-page-header", "views/partials/general-page-header.html")) } func Api_V1_GeneralPage_Header(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client) func(c *fiber.Ctx) error { @@ -65,6 +65,9 @@ func Api_V1_GeneralPage_Header(l map[string]*locale.LocaleConfig, langs []config if len(pathParts) == 2 && pathParts[1] == "blog" { values["Title"] = l[lang].BlogSearch.Header additionalTemplates = append(additionalTemplates, "views/pages/blog-catalogue.html") + } else if len(pathParts) == 2 && pathParts[1] == "user" { + values["Title"] = l[lang].UserProfile.Header + additionalTemplates = append(additionalTemplates, "views/pages/user-page.html") } else if len(pathParts) == 3 && pathParts[1] == "blog" { metadata, _, err := b2Client.ReadFrontmatter(lang + "/" + pathParts[2] + ".md") if err != nil { diff --git a/internal/router/api-v1-general-page-top-embeds.go b/internal/router/api-v1-general-page-top-embeds.go index 544e3a4..f3e480b 100644 --- a/internal/router/api-v1-general-page-top-embeds.go +++ b/internal/router/api-v1-general-page-top-embeds.go @@ -13,7 +13,7 @@ import ( ) func init() { - tm.Add("general-page-top-embeds", "views/partials/general-page-top-embeds.html") + assert(0, tm.Add("general-page-top-embeds", "views/partials/general-page-top-embeds.html")) } func Api_V1_GeneralPage_TopEmbeds(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig) func(c *fiber.Ctx) error { @@ -63,6 +63,8 @@ func Api_V1_GeneralPage_TopEmbeds(l map[string]*locale.LocaleConfig, langs []con if len(pathParts) == 2 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-catalogue.html") + } else if len(pathParts) == 2 && pathParts[1] == "user" { + additionalTemplates = append(additionalTemplates, "views/pages/user-page.html") } else if len(pathParts) == 3 && pathParts[1] == "blog" { additionalTemplates = append(additionalTemplates, "views/pages/blog-page.html") } else if len(pathParts) == 1 { diff --git a/internal/router/api-v1-general-page.go b/internal/router/api-v1-general-page.go index a77fc5e..c8b4362 100644 --- a/internal/router/api-v1-general-page.go +++ b/internal/router/api-v1-general-page.go @@ -1,6 +1,7 @@ package router import ( + "fmt" "log/slog" "strings" @@ -10,7 +11,7 @@ import ( ) func init() { - tm.Add("general-page", "views/layouts/general-page.html") + assert(0, tm.Add("general-page", "views/layouts/general-page.html")) } func Api_V1_GeneralPage(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig) func(c *fiber.Ctx) error { @@ -34,7 +35,8 @@ func Api_V1_GeneralPage(l map[string]*locale.LocaleConfig, langs []config.Availa } langIsAvailable: - cacheKey := "general-page." + lang + queryString := string(c.Request().URI().QueryString()) + cacheKey := fmt.Sprintf("general-page.%s?%s", lang, queryString) if val, ok := PCache.Get(cacheKey); val != nil && ok { c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8) return c.Status(fiber.StatusOK).Type("html").Send(val) @@ -43,7 +45,7 @@ func Api_V1_GeneralPage(l map[string]*locale.LocaleConfig, langs []config.Availa content, err := tm.Render("general-page", fiber.Map{ "L": l[lang], "Lang": lang, - "QueryString": string(c.Request().URI().QueryString()), + "QueryString": queryString, }) if err != nil { slog.Warn("failed to generate div", slog.String("path", path), slog.String("error", err.Error())) diff --git a/internal/router/api-v1-like.go b/internal/router/api-v1-like.go index 327dafa..323c457 100644 --- a/internal/router/api-v1-like.go +++ b/internal/router/api-v1-like.go @@ -13,7 +13,7 @@ import ( ) func init() { - tm.Add("blog-page-like-button", "views/partials/blog-page-like-button.html") + assert(0, tm.Add("blog-page-like-button", "views/partials/blog-page-like-button.html")) } func Api_V1_Like_Put(l map[string]*locale.LocaleConfig, b2 *b2.B2Client) func(c *fiber.Ctx) error { diff --git a/internal/router/lang-blog-title.go b/internal/router/lang-blog-title.go deleted file mode 100644 index 6e80671..0000000 --- a/internal/router/lang-blog-title.go +++ /dev/null @@ -1,86 +0,0 @@ -package router - -import ( - "bytes" - "fmt" - "html/template" - "log/slog" - "strconv" - "strings" - - "github.com/SayaAndy/saya-today-web/config" - "github.com/SayaAndy/saya-today-web/internal/b2" - "github.com/SayaAndy/saya-today-web/internal/frontmatter" - "github.com/SayaAndy/saya-today-web/locale" - "github.com/gofiber/fiber/v2" - "github.com/yuin/goldmark" -) - -func init() { - tm.Add("blog-page", "views/layouts/general-page.html", "views/pages/blog-page.html") -} - -func Lang_Blog_Title(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client, md goldmark.Markdown) func(c *fiber.Ctx) error { - return func(c *fiber.Ctx) error { - ip := c.IP() - slog.Debug("client entering blog page", slog.String("ip", ip), slog.String("page", c.Path())) - - lang := c.Params("lang") - for _, availableLang := range langs { - if availableLang.Name == lang { - goto langIsAvailable - } - } - return c.Status(fiber.ErrNotFound.Code).SendString(fmt.Sprintf("server does not support '%s' language", lang)) - - langIsAvailable: - metadata, parsedMarkdown, err := readBlogPost(md, b2Client, lang+"/"+c.Params("title")) - if err != nil { - c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) - return c.Status(fiber.ErrNotFound.Code).SendString(fmt.Sprintf("failed to find '%s' post", c.Params("title"))) - } - - geolocationParts := strings.Split(metadata.Geolocation, " ") - var x, y, areaError string - if len(geolocationParts) >= 2 { - x = geolocationParts[0] - y = geolocationParts[1] - } - if len(geolocationParts) >= 3 { - areaError = geolocationParts[2] - } - - content, err := tm.Render("blog-page", fiber.Map{ - "Title": metadata.Title, - "PublishedDate": metadata.PublishedTime.Format("2006-01-02 15:04:05 -07:00"), - "PublishedYear": strconv.Itoa(metadata.PublishedTime.Year()), - "ParsedMarkdown": template.HTML(parsedMarkdown), - "MapLocationX": x, - "MapLocationY": y, - "MapLocationAreaMeters": areaError, - "Lang": lang, - "QueryString": string(c.Request().URI().QueryString()), - }) - if err != nil { - slog.Warn("failed to generate page", slog.String("page", "/"+lang+"/blog/"+c.Params("title")), slog.String("error", err.Error())) - c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) - return c.Status(fiber.ErrInternalServerError.Code).SendString("failed to generate page") - } - - return c.Type("html").Send(content) - } -} - -func readBlogPost(md goldmark.Markdown, b2Client *b2.B2Client, sourceName string) (metadata *frontmatter.Metadata, html string, err error) { - metadata, markdown, err := b2Client.ReadFrontmatter(sourceName + ".md") - if err != nil { - return nil, "", fmt.Errorf("failed to read a frontmatter file: %w", err) - } - - var buf bytes.Buffer - if err := md.Convert(markdown, &buf); err != nil { - return nil, "", fmt.Errorf("convert source context from md to html: %w", err) - } - - return metadata, buf.String(), nil -} diff --git a/internal/router/lang-blog.go b/internal/router/lang-blog.go deleted file mode 100644 index 960ac3d..0000000 --- a/internal/router/lang-blog.go +++ /dev/null @@ -1,98 +0,0 @@ -package router - -import ( - "fmt" - "log/slog" - "net/url" - "regexp" - "slices" - "strings" - - "github.com/SayaAndy/saya-today-web/config" - "github.com/SayaAndy/saya-today-web/internal/b2" - "github.com/SayaAndy/saya-today-web/locale" - "github.com/gofiber/fiber/v2" -) - -func init() { - tm.Add("blog-catalogue", "views/layouts/general-page.html", "views/pages/blog-catalogue.html") -} - -func Lang_Blog(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client) func(c *fiber.Ctx) error { - return func(c *fiber.Ctx) error { - lang := c.Params("lang") - for _, availableLang := range langs { - if availableLang.Name == lang { - goto langIsAvailable - } - } - return c.Status(fiber.ErrNotFound.Code).SendString(fmt.Sprintf("server does not support '%s' language", lang)) - - langIsAvailable: - querySort := c.Query("sort") - if querySort == "" { - querySort = "publicationDateDesc" - } - - encodedQuery := c.Request().URI().QueryString() - re, err := regexp.Compile(`tags\[\]=([\w]+)`) - if err != nil { - slog.Warn("failed to generate regex for tags gathering", slog.String("error", err.Error())) - c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) - return c.Status(fiber.ErrInternalServerError.Code).SendString("failed to generate regex for tags gathering") - } - decodedQuery, _ := url.QueryUnescape(string(encodedQuery)) - matches := re.FindAllStringSubmatch(decodedQuery, -1) - - queryTags := make([]string, 0, len(matches)) - for _, match := range matches { - queryTags = append(queryTags, string(match[1])) - } - - pages, err := b2Client.Scan(lang + "/") - status := fiber.StatusOK - if err != nil { - status = fiber.StatusPartialContent - pages = []*b2.BlogPage{} - } - - tagsMap := make(map[string]int) - for _, page := range pages { - for _, tag := range page.Metadata.Tags { - tagsMap[tag]++ - } - } - slog.Debug("enlist pages for catalogue", slog.Int("tag_count", len(tagsMap)), slog.Int("page_count", len(pages)), slog.String("path", c.Path())) - - type Tag struct { - Name string `json:"Name" yaml:"name"` - Count int `json:"Count" yaml:"count"` - } - - tagsArray := make([]Tag, 0, len(tagsMap)) - for tag, count := range tagsMap { - tagsArray = append(tagsArray, Tag{tag, count}) - } - slices.SortFunc(tagsArray, func(a Tag, b Tag) int { - return strings.Compare(a.Name, b.Name) - }) - - content, err := tm.Render("blog-catalogue", fiber.Map{ - "QuerySort": querySort, - "QueryTags": strings.Join(queryTags, ","), - "QueryString": string(c.Request().URI().QueryString()), - "Tags": tagsArray, - "Lang": lang, - "L": l[lang], - "PublishedYear": "2025", - "Title": l[lang].BlogSearch.Header, - }) - if err != nil { - slog.Warn("failed to generate page", slog.String("path", c.Path()), slog.String("error", err.Error())) - c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) - return c.Status(fiber.ErrInternalServerError.Code).SendString("failed to generate page") - } - - return c.Type("html").Status(status).Send(content) - } -} diff --git a/internal/router/lang-map.go b/internal/router/lang-map.go index a744f02..619b05b 100644 --- a/internal/router/lang-map.go +++ b/internal/router/lang-map.go @@ -13,7 +13,7 @@ import ( ) func init() { - tm.Add("global-map", "views/pages/global-map.html") + assert(0, tm.Add("global-map", "views/pages/global-map.html")) } func Lang_Map(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig, b2Client *b2.B2Client) func(c *fiber.Ctx) error { diff --git a/internal/router/root.go b/internal/router/root.go deleted file mode 100644 index f4a0692..0000000 --- a/internal/router/root.go +++ /dev/null @@ -1,27 +0,0 @@ -package router - -import ( - "log/slog" - - "github.com/SayaAndy/saya-today-web/config" - "github.com/gofiber/fiber/v2" -) - -func init() { - tm.Add("index", "views/index.html") -} - -func Root(localeCfg []config.AvailableLanguageConfig) func(c *fiber.Ctx) error { - return func(c *fiber.Ctx) error { - content, err := tm.Render("index", fiber.Map{ - "AvailableLanguages": localeCfg, - }) - if err != nil { - slog.Warn("failed to generate page", slog.String("page", "/"), slog.String("error", err.Error())) - c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) - return c.Status(fiber.ErrInternalServerError.Code).SendString("failed to generate page") - } - - return c.Type("html").Send(content) - } -} diff --git a/internal/templatemanager/templatemanager.go b/internal/templatemanager/templatemanager.go index eebc297..bafdee5 100644 --- a/internal/templatemanager/templatemanager.go +++ b/internal/templatemanager/templatemanager.go @@ -31,6 +31,7 @@ var templateFuncMap = template.FuncMap{ } return items }, + "replace": strings.ReplaceAll, } func NewTemplateManager(templates ...TemplateManagerTemplates) (*TemplateManager, error) { diff --git a/locale/localization.en.yaml b/locale/localization.en.yaml index e93ab00..49d21ee 100644 --- a/locale/localization.en.yaml +++ b/locale/localization.en.yaml @@ -25,3 +25,30 @@ HomePage: Metadata: Published: 'Published' Action: 'Took place on' +Mail: + VerifyEmail: + Subject: 'Verification Link for SAYA.TODAY is waiting for you!' + Welcome: 'Greetings!' + Intro: 'There are 2 ways for us to validate your profile:' + GotoLink: 'Go by this link:' + InputCode: "Or input this code on the personal page:" + IfRandom: 'If you are unsure what this letter this, you can ignore it, and also, if you are interested, you may visit my site :)' + NewPost: + Subject: 'New post arrived at SAYA.TODAY!' +UserProfile: + Header: 'Personal Settings' + EmailHeader: 'E-Mail' + VerificationCodeHeader: 'Verification Code' + TypeEmail: 'Please type your email' + SendCodeButton: 'Send Code' + VerifyButton: 'Verify' + VerificationCodeSent: 'Verification code sent! Please check your e-mail. Your next verification attempt will be possible on {}.' + DelayTilVerification: 'You have already requested the verification before! Please wait until {} for a new verification request.' + FailedEmailRender: 'Failed to render the email status message, please ask administrator for a more detailed cause.' + VerificationCodeSendingError: 'Failed to send a verification code, please ask administrator for a more detailed cause.' + EmailAlreadyValidated: 'You already have this E-Mail validated.' + EmailTaken: 'This E-Mail is already taken.' + EmailEmpty: 'E-Mail is unset or empty.' + VerificationSuccess: 'Success! You are now able to subscribe with your new e-mail.' + VerificationFailed: 'Verification code is invalid, please ask administrator for a more detailed cause.' + VerificationEmpty: 'Verification code is unset or empty.' diff --git a/locale/localization.go b/locale/localization.go index 7dbb554..9022b50 100644 --- a/locale/localization.go +++ b/locale/localization.go @@ -8,11 +8,13 @@ import ( ) type LocaleConfig struct { - TagsLabel string `yaml:"TagsLabel" json:"TagsLabel"` - BlogSearch BlogSearchConfig `yaml:"BlogSearch" json:"BlogSearch"` - GlobalMap GlobalMapConfig `yaml:"GlobalMap" json:"GlobalMap"` - HomePage HomePageConfig `yaml:"HomePage" json:"HomePage"` - Metadata MetadataConfig `yaml:"Metadata" json:"Metadata"` + TagsLabel string `yaml:"TagsLabel" json:"TagsLabel"` + BlogSearch BlogSearchConfig `yaml:"BlogSearch" json:"BlogSearch"` + GlobalMap GlobalMapConfig `yaml:"GlobalMap" json:"GlobalMap"` + HomePage HomePageConfig `yaml:"HomePage" json:"HomePage"` + Metadata MetadataConfig `yaml:"Metadata" json:"Metadata"` + Mail MailConfig `yaml:"Mail" json:"Mail"` + UserProfile UserProfileConfig `yaml:"UserProfile" json:"UserProfile"` } type BlogSearchConfig struct { @@ -49,6 +51,43 @@ type MetadataConfig struct { Published string `yaml:"Published" json:"Published"` } +type MailConfig struct { + VerifyEmail VerifyEmailConfig `yaml:"VerifyEmail" json:"VerifyEmail"` + NewPost NewPostConfig `yaml:"NewPost" json:"NewPost"` +} + +type VerifyEmailConfig struct { + Subject string `yaml:"Subject" json:"Subject"` + Welcome string `yaml:"Welcome" json:"Welcome"` + Intro string `yaml:"Intro" json:"Intro"` + GotoLink string `yaml:"GotoLink" json:"GotoLink"` + InputCode string `yaml:"InputCode" json:"InputCode"` + IfRandom string `yaml:"IfRandom" json:"IfRandom"` +} + +type NewPostConfig struct { + Subject string `yaml:"Subject" json:"Subject"` +} + +type UserProfileConfig struct { + Header string `yaml:"Header" json:"Header"` + EmailHeader string `yaml:"EmailHeader" json:"EmailHeader"` + VerificationCodeHeader string `yaml:"VerificationCodeHeader" json:"VerificationCodeHeader"` + TypeEmail string `yaml:"TypeEmail" json:"TypeEmail"` + SendCodeButton string `yaml:"SendCodeButton" json:"SendCodeButton"` + VerifyButton string `yaml:"VerifyButton" json:"VerifyButton"` + VerificationCodeSent string `yaml:"VerificationCodeSent" json:"VerificationCodeSent"` + DelayTilVerification string `yaml:"DelayTilVerification" json:"DelayTilVerification"` + FailedEmailRender string `yaml:"FailedEmailRender" json:"FailedEmailRender"` + VerificationCodeSendingError string `yaml:"VerificationCodeSendingError" json:"VerificationCodeSendingError"` + EmailAlreadyValidated string `yaml:"EmailAlreadyValidated" json:"EmailAlreadyValidated"` + EmailTaken string `yaml:"EmailTaken" json:"EmailTaken"` + EmailEmpty string `yaml:"EmailEmpty" json:"EmailEmpty"` + VerificationSuccess string `yaml:"VerificationSuccess" json:"VerificationSuccess"` + VerificationFailed string `yaml:"VerificationFailed" json:"VerificationFailed"` + VerificationEmpty string `yaml:"VerificationEmpty" json:"VerificationEmpty"` +} + func LoadConfig(path string, config *LocaleConfig) error { fileBytes, err := os.ReadFile(path) if err != nil { diff --git a/locale/localization.ru.yaml b/locale/localization.ru.yaml index a1a9a6c..fe6d55f 100644 --- a/locale/localization.ru.yaml +++ b/locale/localization.ru.yaml @@ -25,3 +25,30 @@ HomePage: Metadata: Published: 'Опубликовано' Action: 'Время действия' +Mail: + VerifyEmail: + Subject: 'Ссылка для верификации для подтверждения вашей почты SAYA.TODAY' + Welcome: 'Приветствую!' + Intro: 'Есть 2 способа, чтобы подтвердить свою электронную почту:' + GotoLink: 'Перейти по этой ссылке:' + InputCode: 'Либо ввести этот код на странице подписок:' + IfRandom: 'Если ты не понимаешь, что это за спам, можешь проигнорировать это письмо, а ещё, если интересно, можешь посетить мой сайт :)' + NewPost: + Subject: 'Новый пост на SAYA.TODAY!' +UserProfile: + Header: 'Личные настройки' + EmailHeader: 'E-Mail' + VerificationCodeHeader: 'Код верификации' + TypeEmail: 'Пожалуйста, введите свою почту' + SendCodeButton: 'Отправить код' + VerifyButton: 'Верифицировать' + VerificationCodeSent: 'Выслали вам код верификации! Проверьте свою почту. Следующая попытка верификации будет возможна {}.' + DelayTilVerification: 'Вы уже запрашивали недавно верификацию! Дождитесь {} для новой попытки.' + FailedEmailRender: 'Неудачная попытка создать электронное письмо, более подробно спрашивайте у администратора.' + VerificationCodeSendingError: 'Неудачная попытка прислать код для верификации, более подробно спрашивайте у администратора.' + EmailAlreadyValidated: 'Эту почту вы уже подтверждали.' + EmailTaken: 'Эта почта уже занята.' + EmailEmpty: 'Почта не введена.' + VerificationSuccess: 'Поздравляем! Теперь по этой почте можно подписаться на блог.' + VerificationFailed: 'Код для верификации невалиден, при вопросах, пожалуйста, обращайтесь к администратору.' + VerificationEmpty: 'Код для верификации не введён.' @@ -13,6 +13,7 @@ import ( "github.com/SayaAndy/saya-today-web/internal/b2" "github.com/SayaAndy/saya-today-web/internal/factgiver" "github.com/SayaAndy/saya-today-web/internal/glightbox" + "github.com/SayaAndy/saya-today-web/internal/mailer" "github.com/SayaAndy/saya-today-web/internal/router" "github.com/SayaAndy/saya-today-web/internal/tailwind" "github.com/SayaAndy/saya-today-web/locale" @@ -144,9 +145,17 @@ func main() { os.Exit(1) } + router.Mailer, err = mailer.NewMailer(db, cfg.Mail.ClientHost, cfg.Mail.MailHost, + cfg.Mail.PublicName, cfg.Mail.MailAddress, cfg.Mail.Username, cfg.Mail.Password, []byte(cfg.Mail.Salt), localization) + if err != nil { + slog.Error("fail to initialize mailer", slog.String("error", err.Error())) + os.Exit(1) + } + app.Get("/", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang<len(2)>", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang/map", router.Lang_Map(localization, availableLanguages, b2Client)) + app.Get("/:lang/user", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang/blog", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang/blog/:title", router.Api_V1_GeneralPage(localization, availableLanguages)) @@ -159,6 +168,9 @@ func main() { app.Get("/api/v1/general-page/footer", router.Api_V1_GeneralPage_Footer(localization, availableLanguages)) app.Get("/api/v1/general-page/top-embeds", router.Api_V1_GeneralPage_TopEmbeds(localization, availableLanguages)) app.Get("/api/v1/general-page/bottom-embeds", router.Api_V1_GeneralPage_BottomEmbeds(localization, availableLanguages, b2Client)) + app.Post("/api/v1/email/send-verification-code", router.Api_V1_Email_SendVerificationCode(localization)) + app.Post("/api/v1/email/verify", router.Api_V1_Email_Verify(localization)) + app.Get("/api/v1/email/is-in-verification", router.Api_V1_Email_IsInVerification(localization)) app.Static("/", "./static") diff --git a/migrations/2_create_subscription_tables.down.sql b/migrations/2_create_subscription_tables.down.sql new file mode 100644 index 0000000..d9a369e --- /dev/null +++ b/migrations/2_create_subscription_tables.down.sql @@ -0,0 +1,4 @@ +DROP INDEX IF EXISTS user_email_table_email_uindex; +DROP TABLE IF EXISTS user_email_table; +DROP TABLE IF EXISTS subscription_user_to_tags_table; +DROP TABLE IF EXISTS subscription_tag_to_users_table; diff --git a/migrations/2_create_subscription_tables.up.sql b/migrations/2_create_subscription_tables.up.sql new file mode 100644 index 0000000..e6e905a --- /dev/null +++ b/migrations/2_create_subscription_tables.up.sql @@ -0,0 +1,18 @@ +CREATE TABLE IF NOT EXISTS user_email_table ( + user_id VARCHAR(32) NOT NULL PRIMARY KEY, + email VARCHAR(64) NOT NULL, + lang VARCHAR(2) NOT NULL +) WITHOUT ROWID; + +CREATE UNIQUE INDEX user_email_table_email_uindex +ON user_email_table(email); + +CREATE TABLE IF NOT EXISTS subscription_user_to_tags_table ( + user_id VARCHAR(32) NOT NULL PRIMARY KEY, + tags TEXT NOT NULL +) WITHOUT ROWID; + +CREATE TABLE IF NOT EXISTS subscription_tag_to_users_table ( + tag VARCHAR(32) NOT NULL PRIMARY KEY, + user_ids TEXT NOT NULL +) WITHOUT ROWID; diff --git a/static/input.css b/static/input.css index 4fcadd1..cc88959 100644 --- a/static/input.css +++ b/static/input.css @@ -9,6 +9,7 @@ html { font-size: 12px; + --crossed-out: url("data:image/svg+xml,<svg id='patternId' width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'><defs><pattern id='a' patternUnits='userSpaceOnUse' width='30' height='30' patternTransform='scale(1) rotate(65)'><rect x='0' y='0' width='100%' height='100%' fill='%232b2b3100' /><path d='M30 15L22.5 30 15 15 22.5 0zm-15 0L7.5 30 0 15 7.5 0z' stroke-width='0.6' stroke='%23ffffffff' fill='none' /></pattern></defs><rect width='800%' height='800%' transform='translate(0,0)' fill='url(%23a)' /></svg>"); --noise-image: url(data:image/png;base64,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); --split-left-background: unset; --split-left-repeat: no-repeat; @@ -179,6 +180,27 @@ a:hover, .linklike:hover { text-decoration: underline; } +form.disabled::before, +form.htmx-request::before { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: var(--main-hard-color); + background-size: 0.5rem 0.5rem; + mask-image: var(--crossed-out); + opacity: 1; + transition: opacity 0.3s; + z-index: 25; +} + +form.disabled input, +form.htmx-request input { + filter: grayscale(1); +} + .bg-interlocked-hexagons { background-image: var(--interlocked-hexagons-background); background-repeat: var(--interlocked-hexagons-background-repeat); diff --git a/views/layouts/general-mail.html b/views/layouts/general-mail.html new file mode 100644 index 0000000..c73a1ec --- /dev/null +++ b/views/layouts/general-mail.html @@ -0,0 +1,82 @@ +<!DOCTYPE html> +<html lang="en"> + <meta charset="UTF-8"> + <head> + <style> +@font-face { + font-family: 'Philosopher'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url(https://fonts.gstatic.com/s/philosopher/v21/vEFV2_5QCwIS4_Dhez5jcWBuT0020Nqf.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: 'Philosopher'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url(https://fonts.gstatic.com/s/philosopher/v21/vEFV2_5QCwIS4_Dhez5jcWBqT0020NqfZ7c.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} + +html { + font-family: 'Philosopher', sans-serif; + color: #343b58; + --noise-image: url(data:image/png;base64,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); +} + +body { + background-color: #e3e6ff; +} + +a { + color: #c3caff !important; + text-decoration: underline; +} + +a:hover { + color: #d1d6ff !important; +} + +.header { + width: 100%; + padding: 8px 8px 8px 32px; + font-size: 48px; + font-family: 'Philosopher'; + color: white; + text-shadow: -2px 0 #343b58, 0 2px #343b58, 2px 0 #343b58, 0 -2px #343b58; + background: url("data:image/svg+xml,<svg width='160' height='160' xmlns='http://www.w3.org/2000/svg'><defs><pattern id='a' patternUnits='userSpaceOnUse' width='40' height='80' patternTransform='scale(2) rotate(0)'><rect x='0' y='0' width='100%' height='100%' fill='%23e3e6ffff'/><path d='M-10 7.5l20 5 20-5 20 5' stroke-linejoin='round' stroke-linecap='round' stroke-width='4' stroke='%238c4351ff' fill='none'/><path d='M-10 27.5l20 5 20-5 20 5' stroke-linejoin='round' stroke-linecap='round' stroke-width='4' stroke='%23385f0dff' fill='none'/><path d='M-10 47.5l20 5 20-5 20 5' stroke-linejoin='round' stroke-linecap='round' stroke-width='4' stroke='%23006c86ff' fill='none'/><path d='M-10 67.5l20 5 20-5 20 5' stroke-linejoin='round' stroke-linecap='round' stroke-width='4' stroke='%235a3e8eff' fill='none'/></pattern></defs><rect width='800%' height='800%' transform='translate(0,0)' fill='url(%23a)'/></svg>"); + background-color: #e3e6ff; + background-size: contain; + background-repeat: repeat; +} + +.content { + margin: 0rem 32px 32px 32px; + padding: 16px; + font-size: 24px; + text-shadow: -1px 0 #343b58, 0 1px #343b58, 1px 0 #343b58, 0 -1px #343b58; + color: white; + background-color: #c3caff; + background-image: var(--noise-image); +} + +.outlier { + padding-inline: 4px; + background-color: #6c6e75; + background-image: var(--noise-image); +} + </style> + </head> + + <body> + <div id="header" class="header"> + saya.today + </div> + + <div id="content" class="content"> + {{ block "body" . }}{{ end }} + </div> + </body> +</html> diff --git a/views/layouts/general-page.html b/views/layouts/general-page.html index 5760b88..48a0f16 100644 --- a/views/layouts/general-page.html +++ b/views/layouts/general-page.html @@ -174,18 +174,21 @@ <div class="flex flex-col [@media(max-height:32rem)]:flex-row"> <div id="sidebar" class="bg-sidebar flex sticky flex-col z-20 w-[100dvw] xs:w-[90dvw] sm:w-[80dvw] md:w-[75dvw] lg:w-[70dvw] xl:w-[65dvw] 2xl:w-[60dvw] [@media(max-height:32rem)]:w-[5rem] h-[5rem] [@media(max-height:32rem)]:h-[100dvh] shadow-[0_0_1rem_black]"> <div class="text-[3rem] text-stroke-(--sidebar-stroke-color) text-stroke-[0.1dvw] flex flex-row [@media(max-height:32rem)]:flex-col gap-0 relative z-20"> - <a href="/{{ .Lang }}" id="sidebar-home-button" class="w-[5rem] h-[5rem]"> + <a href="./" id="sidebar-back-button" class="w-[5rem] h-[5rem] hidden"> + <i onclick="return changeUrl('/../', true);" class="fas fa-circle-left flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> + </a> + <a href="/{{ .Lang }}" id="sidebar-home-button" class="w-[5rem] h-[5rem] hidden"> <i onclick="return changeUrl('/{{ .Lang }}');" class="fas fa-home flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> - <a href="/{{ .Lang }}/blog" id="sidebar-blog-button" class="w-[5rem] h-[5rem]"> + <a href="/{{ .Lang }}/blog" id="sidebar-blog-button" class="w-[5rem] h-[5rem] hidden"> <i onclick="return changeUrl('/{{ .Lang }}/blog');" class="fas fa-search flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> - <a href="/{{ .Lang }}/map" id="sidebar-map-button" class="w-[5rem] h-[5rem]"> + <a href="/{{ .Lang }}/map" id="sidebar-map-button" class="w-[5rem] h-[5rem] hidden"> <i class="fas fa-map flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> <i onclick="toggleThemeWheel();" id="sidebar-theme-button" class="fas fa-swatchbook flex w-[5rem] h-[5rem] content-center text-center text-sidebar hover:bg-background-dark cursor-pointer transition-colors duration-300 rounded-lg"></i> - <a href="./" id="sidebar-back-button" class="w-[5rem] h-[5rem]"> - <i onclick="return changeUrl('/../', true);" class="fas fa-circle-left flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> + <a href="/{{ .Lang }}/user" id="sidebar-user-button" class="w-[5rem] h-[5rem] hidden"> + <i onclick="return changeUrl('/{{ .Lang }}/user');" class="fas fa-user flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> </div> <div class="theme-wheel" id="theme-wheel"> @@ -201,6 +204,7 @@ sidebarMapButton = document.getElementById("sidebar-map-button"); sidebarBlogButton = document.getElementById("sidebar-blog-button"); sidebarBackButton = document.getElementById("sidebar-back-button"); + sidebarUserButton = document.getElementById("sidebar-user-button"); function updateSidebar() { if (location.pathname == "" || location.pathname == "/") { @@ -208,17 +212,21 @@ sidebarMapButton.classList.add('hidden'); sidebarBlogButton.classList.add('hidden'); sidebarBackButton.classList.add('hidden'); + sidebarUserButton.classList.add('hidden'); } else { sidebarHomeButton.classList.remove('hidden'); sidebarMapButton.classList.remove('hidden'); sidebarBlogButton.classList.remove('hidden'); sidebarBackButton.classList.remove('hidden'); + sidebarUserButton.classList.remove('hidden'); lang = location.pathname.split("/")[1]; sidebarHomeButton.setAttribute('href', `/${lang}`); sidebarHomeButton.firstElementChild.setAttribute('onclick', `return changeUrl('/${lang}', false);`); sidebarMapButton.setAttribute('href', `/${lang}/map`); sidebarBlogButton.setAttribute('href', `/${lang}/blog`); sidebarBlogButton.firstElementChild.setAttribute('onclick', `return changeUrl('/${lang}/blog', false);`); + sidebarUserButton.setAttribute('href', `/${lang}/user`); + sidebarUserButton.firstElementChild.setAttribute('onclick', `return changeUrl('/${lang}/user', false);`); } } window.addEventListener("popstate", updateSidebar); diff --git a/views/messages/new-post.html b/views/messages/new-post.html new file mode 100644 index 0000000..4fbfc02 --- /dev/null +++ b/views/messages/new-post.html @@ -0,0 +1,3 @@ +{{ define "body" }} +<p>Новый пост ёпта.</p> +{{ end }}
\ No newline at end of file diff --git a/views/messages/verify-email.html b/views/messages/verify-email.html new file mode 100644 index 0000000..dd6ef33 --- /dev/null +++ b/views/messages/verify-email.html @@ -0,0 +1,10 @@ +{{ define "body" }} +<p>{{ .L.Mail.VerifyEmail.Welcome }}</p> +<p>{{ .L.Mail.VerifyEmail.Intro }}</p> +<ol> + <li>{{ .L.Mail.VerifyEmail.GotoLink }} <a href="https://{{ .ClientHost }}/{{ .Lang }}/user?email_code={{ .VerificationCode }}" class="outlier">>>></a></li> + <li>{{ .L.Mail.VerifyEmail.InputCode }} <span class="outlier">{{ .VerificationCode }}</span><span></li> +</ol> +<p>{{ .L.Mail.VerifyEmail.IfRandom }}</p> +<a href="https://{{ .ClientHost }}" class="outlier">{{ .ClientHost }}</a> +{{ end }}
\ No newline at end of file diff --git a/views/pages/global-map.html b/views/pages/global-map.html index d0433e9..8be99bf 100644 --- a/views/pages/global-map.html +++ b/views/pages/global-map.html @@ -44,6 +44,9 @@ <div id="sidebar" class="bg-sidebar block fixed shadow-[0_0_0.4rem_black] z-1001 w-[5rem] h-auto"> <div class="text-[3rem] text-stroke-(--sidebar-stroke-color) text-stroke-[0.1dvw] flex flex-col gap-0 relative z-1001"> + <a href="./" class="w-[5rem] h-[5rem]"> + <i class="fas fa-circle-left flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> + </a> <a href="/{{ .Lang }}" class="w-[5rem] h-[5rem]"> <i class="fas fa-home flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> @@ -54,8 +57,8 @@ <i class="fas fa-map flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> <i onclick="toggleThemeWheel();" id="theme-button" class="fas fa-swatchbook flex w-[5rem] h-[5rem] content-center text-center text-sidebar hover:bg-background-dark cursor-pointer transition-colors duration-300 rounded-lg"></i> - <a href="./" class="w-[5rem] h-[5rem]"> - <i class="fas fa-circle-left flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> + <a href="/{{ .Lang }}/user" id="sidebar-user-button" class="w-[5rem] h-[5rem]"> + <i onclick="return changeUrl('/{{ .Lang }}/user');" class="fas fa-user flex w-full h-full content-center text-center text-sidebar hover:bg-background-dark transition-colors duration-300 rounded-lg"></i> </a> </div> <div class="theme-wheel" id="theme-wheel"> diff --git a/views/pages/user-page.html b/views/pages/user-page.html new file mode 100644 index 0000000..1632670 --- /dev/null +++ b/views/pages/user-page.html @@ -0,0 +1,96 @@ +{{ define "body" }} +<div class="bg-background-light flex flex-col inset-shadow-[0_0_0.4rem_black] px-8 py-4 overflow-y-auto"> + <form id="email-form" class="w-full mb-2 flex flex-col relative" + hx-get="/api/v1/email/is-in-verification" hx-target="#email-message" hx-swap="outerHTML" hx-trigger="load" hx-indicator="this"> + <div class="flex flex-row w-full mb-4 z-21"> + <div class="flex flex-col flex-3/5 grow-0"> + <label class="block text-main-medium font-bold mb-1 z-22"> + {{ .L.UserProfile.EmailHeader }} + </label> + <input class="bg-(--background-medium-color) appearance-none border-(--background-medium-color) rounded ml-6 mr-4 py-2 px-4 text-main-medium leading-tight inset-shadow-[0_0_0.4rem_black] focus:outline-none focus:bg-(--background-light-color) focus:text-main-hard z-22" + id="email-input" name="email" type="text" value="{{ .Email }}" placeholder="{{ .L.UserProfile.TypeEmail }}" maxlength="64" + data-validated-email="{{ .Email }}" onchange="checkIfValidated(this);"> + </div> + </div> + <button class="w-1/3 mx-auto bg-(--main-hard-color) hover:bg-(--main-medium-color) active:bg-(--main-soft-color) active:inset-shadow-[0.2em_0.2em_0.2rem_black] transition-colors transition-300 text-(--background-light-color) font-bold py-2 px-4 rounded z-22" + hx-post="/api/v1/email/send-verification-code" hx-target="#email-message" hx-swap="outerHTML" hx-indicator="#email-form"> + {{ .L.UserProfile.SendCodeButton }} + </button> + </form> + <div id="email-message"></div> + <hr class="my-2 border-t-4 border-dotted border-main-hard"> + <form id="email-verification-form" class="w-full mb-2 flex flex-col relative hidden" + {{ if .EmailCode }}hx-post="/api/v1/email/verify" hx-target="#verification-message" hx-swap="outerHTML" hx-trigger="load" hx-indicator="this"{{ end }}> + <div class="flex flex-row w-full mb-4 z-21"> + <div class="flex flex-col flex-2/5 grow-0"> + <label class="block text-main-medium font-bold ml-1 z-22"> + {{ .L.UserProfile.VerificationCodeHeader }} + </label> + <input class="bg-(--background-medium-color) appearance-none border-(--background-medium-color) rounded ml-6 mr-4 py-2 px-4 text-main-medium leading-tight inset-shadow-[0_0_0.4rem_black] focus:outline-none focus:bg-(--background-light-color) focus:text-main-hard z-22" + name="email_code" type="text" value="{{ .EmailCode }}" placeholder="0123456789ABCDEF" maxlength="16"> + </div> + </div> + <button class="w-1/3 mx-auto bg-(--main-hard-color) hover:bg-(--main-medium-color) active:bg-(--main-soft-color) active:inset-shadow-[0.2em_0.2em_0.2rem_black] transition-colors transition-300 text-(--background-light-color) font-bold py-2 px-4 rounded z-22" + hx-post="/api/v1/email/verify" hx-target="#verification-message" hx-swap="outerHTML" hx-indicator="#email-verification-form"> + {{ .L.UserProfile.VerifyButton }} + </button> + </form> + <div id="verification-message"></div> +</div> + +<script> +htmx.on("htmx:beforeSwap", (e) => { + if (e.detail.xhr.status === 422) { + e.detail.shouldSwap = true; + e.detail.isError = false; + } +}); + +var formAllowTimeout; +var verificationHideTimeout; + +var url = new URL(window.location.href); +url.searchParams.delete('email_code'); +window.history.pushState({}, '', url.toString()); + +htmx.on("htmx:afterSwap", (e) => { + emailMessage = htmx.find("#email-message"); + verificationMessage = htmx.find("#verification-message"); + emailForm = htmx.find("#email-form"); + emailVerificationForm = htmx.find("#email-verification-form"); + tryAgainTimeDiff = parseInt(emailMessage.dataset.strikedEndTime || "0") - new Date().getTime(); + verificationWaitingTimeDiff = parseInt(emailMessage.dataset.codeExpiryTime || "0") - new Date().getTime(); + + if (tryAgainTimeDiff > 0) { + emailForm.classList.add("disabled"); + formAllowTimeout = setTimeout(() => { + emailForm.classList.remove("disabled"); + emailMessage.classList.add("hidden"); + }, tryAgainTimeDiff); + } else { + emailForm.classList.remove("disabled"); + } + + if (verificationWaitingTimeDiff > 0) { + verificationHideTimeout = setTimeout(() => emailVerificationForm.classList.add("hidden"), verificationWaitingTimeDiff); + emailVerificationForm.classList.remove("hidden"); + } else { + emailVerificationForm.classList.add("hidden"); + } + + if ((verificationMessage.dataset.hideVerificationPanel || "false") == "true") { + emailVerificationForm.classList.add("hidden"); + } +}); + +function checkIfValidated(elem) { + if ((elem.dataset.validatedEmail != "") && (elem.value == elem.dataset.validatedEmail)) { + elem.classList.add("!bg-green-300/20"); + } else { + elem.classList.remove("!bg-green-300/20"); + } +} + +checkIfValidated(htmx.find("#email-input")); +</script> +{{ end }}
\ No newline at end of file diff --git a/views/partials/personal-page-status.html b/views/partials/personal-page-status.html new file mode 100644 index 0000000..a4e47c2 --- /dev/null +++ b/views/partials/personal-page-status.html @@ -0,0 +1,12 @@ +<div id="{{ .StatusId }}" class='z-26 w-full inset-shadow-[0_0_0.4rem_black] + {{if eq .Status "OK"}}bg-green-700 text-green-100 + {{else if eq .Status "Failed"}}bg-red-700 text-red-100 + {{else}}bg-background-dark text-main-soft{{end}} + {{if eq .Message ""}}hidden{{end}} + py-2 px-4 text-center' + {{- range $_, $val := .DataAttributes }} + {{ $val }} + {{- end }} + > + {{ .Message }} +</div>
\ No newline at end of file |