feat(auth): #154 send verification mails
This commit was merged in pull request #155.
This commit is contained in:
41
handler.go
41
handler.go
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"me-fit/middleware"
|
"me-fit/middleware"
|
||||||
"me-fit/service"
|
"me-fit/service"
|
||||||
|
"me-fit/template/mail"
|
||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
@@ -14,23 +15,37 @@ func getHandler(db *sql.DB) http.Handler {
|
|||||||
|
|
||||||
router.HandleFunc("/", service.HandleIndexAnd404(db))
|
router.HandleFunc("/", service.HandleIndexAnd404(db))
|
||||||
|
|
||||||
router.HandleFunc("/mail", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
utils.SendWelcomeMail("timwundenberg@outlook.de")
|
|
||||||
})
|
|
||||||
|
|
||||||
// Serve static files (CSS, JS and images)
|
// Serve static files (CSS, JS and images)
|
||||||
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
||||||
|
|
||||||
router.HandleFunc("/workout", service.HandleWorkoutPage(db))
|
router.Handle("/workout", auth(db, service.HandleWorkoutPage(db)))
|
||||||
router.HandleFunc("POST /api/workout", service.HandleWorkoutNewComp(db))
|
router.Handle("POST /api/workout", auth(db, service.HandleWorkoutNewComp(db)))
|
||||||
router.HandleFunc("GET /api/workout", service.HandleWorkoutGetComp(db))
|
router.Handle("GET /api/workout", auth(db, service.HandleWorkoutGetComp(db)))
|
||||||
router.HandleFunc("DELETE /api/workout/{id}", service.HandleWorkoutDeleteComp(db))
|
router.Handle("DELETE /api/workout/{id}", auth(db, service.HandleWorkoutDeleteComp(db)))
|
||||||
|
|
||||||
router.HandleFunc("/auth/signin", service.HandleSignInPage(db))
|
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
|
||||||
router.HandleFunc("/auth/signup", service.HandleSignUpPage(db))
|
router.Handle("/auth/signin", service.HandleSignInPage(db))
|
||||||
router.HandleFunc("/api/auth/signup", service.HandleSignUpComp(db))
|
router.Handle("/auth/signup", service.HandleSignUpPage(db))
|
||||||
router.HandleFunc("/api/auth/signin", service.HandleSignInComp(db))
|
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(db)) // Hint for the user to verify their email
|
||||||
router.HandleFunc("/api/auth/signout", service.HandleSignOutComp(db))
|
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(db)) // The link contained in the email
|
||||||
|
router.Handle("/api/auth/signup", service.HandleSignUpComp(db))
|
||||||
|
router.Handle("/api/auth/signin", service.HandleSignInComp(db))
|
||||||
|
router.Handle("/api/auth/signout", service.HandleSignOutComp(db))
|
||||||
|
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(db))
|
||||||
|
|
||||||
|
if utils.Environment == "dev" {
|
||||||
|
router.HandleFunc("/mail/", handleMails)
|
||||||
|
}
|
||||||
|
|
||||||
return middleware.Logging(middleware.EnableCors(router))
|
return middleware.Logging(middleware.EnableCors(router))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func handleMails(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/mail/register" {
|
||||||
|
mail.Register("test-code").Render(r.Context(), w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func auth(db *sql.DB, h http.Handler) http.Handler {
|
||||||
|
return middleware.EnsureValidSession(db, h)
|
||||||
|
}
|
||||||
|
|||||||
59
middleware/auth.go
Normal file
59
middleware/auth.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"me-fit/utils"
|
||||||
|
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func EnsureValidSession(db *sql.DB, next http.Handler) http.Handler {
|
||||||
|
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
// handled, redirected := handleSignInAndOutRoutes(db, w, r)
|
||||||
|
// if handled {
|
||||||
|
// if !redirected {
|
||||||
|
// next.ServeHTTP(w, r)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
|
||||||
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
if user == nil || !user.SessionValid {
|
||||||
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.URL.Path != "/auth/verify" && !user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.WithValue(r.Context(), utils.ContextKeyUser, user)
|
||||||
|
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// func handleSignInAndOutRoutes(db *sql.DB, w http.ResponseWriter, r *http.Request) (bool, bool) {
|
||||||
|
// if r.URL.Path != "/auth/signin" && r.URL.Path != "/auth/signup" && r.URL.Path != "/api/auth/verify-resend" {
|
||||||
|
// return false, false
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// sessionId := getSessionID(r)
|
||||||
|
// user := verifySession(db, sessionId)
|
||||||
|
// if user == nil || !user.SessionValid {
|
||||||
|
// return true, false
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if user.EmailVerified {
|
||||||
|
// utils.DoRedirect(w, r, "/")
|
||||||
|
// } else {
|
||||||
|
// utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return true, true
|
||||||
|
// }
|
||||||
2
migration/003_user_mail_verification.up.sql
Normal file
2
migration/003_user_mail_verification.up.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
|
||||||
|
ALTER TABLE user ADD COLUMN email_verified_at DATETIME DEFAULT NULL;
|
||||||
167
service/auth.go
167
service/auth.go
@@ -13,37 +13,92 @@ import (
|
|||||||
|
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
"me-fit/template/auth"
|
"me-fit/template/auth"
|
||||||
|
tempMail "me-fit/template/mail"
|
||||||
|
"me-fit/types"
|
||||||
|
"me-fit/utils"
|
||||||
|
|
||||||
"github.com/a-h/templ"
|
"github.com/a-h/templ"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"golang.org/x/crypto/argon2"
|
"golang.org/x/crypto/argon2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type User struct {
|
|
||||||
id uuid.UUID
|
|
||||||
email string
|
|
||||||
}
|
|
||||||
|
|
||||||
func HandleSignInPage(db *sql.DB) http.HandlerFunc {
|
func HandleSignInPage(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
user := utils.GetUserFromSession(db, r)
|
||||||
signIn := auth.SignInOrUp(true)
|
if user == nil || !user.SessionValid {
|
||||||
template.Layout(signIn, user_comp).Render(r.Context(), w)
|
userComp := UserInfoComp(nil)
|
||||||
|
signIn := auth.SignInOrUpComp(true)
|
||||||
|
template.Layout(signIn, userComp).Render(r.Context(), w)
|
||||||
|
return
|
||||||
|
} else if !user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignUpPage(db *sql.DB) http.HandlerFunc {
|
func HandleSignUpPage(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
user := utils.GetUserFromSession(db, r)
|
||||||
signIn := auth.SignInOrUp(false)
|
if user == nil || !user.SessionValid {
|
||||||
template.Layout(signIn, user_comp).Render(r.Context(), w)
|
userComp := UserInfoComp(nil)
|
||||||
|
signUpComp := auth.SignInOrUpComp(false)
|
||||||
|
template.Layout(signUpComp, userComp).Render(r.Context(), w)
|
||||||
|
return
|
||||||
|
} else if !user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func UserInfoComp(user *User) templ.Component {
|
func HandleSignUpVerifyPage(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
if user == nil || !user.SessionValid {
|
||||||
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
userComp := UserInfoComp(user)
|
||||||
|
signIn := auth.VerifyComp()
|
||||||
|
template.Layout(signIn, userComp).Render(r.Context(), w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleSignUpVerifyResponsePage(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
code := r.URL.Query().Get("code")
|
||||||
|
if code == "" {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userId, err := uuid.Parse(code)
|
||||||
|
if err != nil {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.Exec("UPDATE user SET email_verified = true, email_verified_at = datetime() WHERE user_uuid = ?", userId)
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserInfoComp(user *types.User) templ.Component {
|
||||||
|
|
||||||
if user != nil {
|
if user != nil {
|
||||||
return auth.UserComp(user.email)
|
return auth.UserComp(user.Email)
|
||||||
} else {
|
} else {
|
||||||
return auth.UserComp("")
|
return auth.UserComp("")
|
||||||
}
|
}
|
||||||
@@ -108,7 +163,10 @@ func HandleSignUpComp(db *sql.DB) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Add("HX-Redirect", "/")
|
// Send verification email as a goroutine
|
||||||
|
go sendVerificationEmail(db, r, userId.String(), email)
|
||||||
|
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,10 +178,13 @@ func HandleSignInComp(db *sql.DB) http.HandlerFunc {
|
|||||||
var result bool = true
|
var result bool = true
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
var userId uuid.UUID
|
var (
|
||||||
var savedHash []byte
|
userId uuid.UUID
|
||||||
var salt []byte
|
savedHash []byte
|
||||||
err := db.QueryRow("SELECT user_uuid, password, salt FROM user WHERE email = ?", email).Scan(&userId, &savedHash, &salt)
|
salt []byte
|
||||||
|
emailVerified bool
|
||||||
|
)
|
||||||
|
err := db.QueryRow("SELECT user_uuid, password, salt, email_verified FROM user WHERE email = ?", email).Scan(&userId, &savedHash, &salt, &emailVerified)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
result = false
|
result = false
|
||||||
}
|
}
|
||||||
@@ -153,7 +214,11 @@ func HandleSignInComp(db *sql.DB) http.HandlerFunc {
|
|||||||
time.Sleep(time.Duration(timeToWait) * time.Millisecond)
|
time.Sleep(time.Duration(timeToWait) * time.Millisecond)
|
||||||
|
|
||||||
if result {
|
if result {
|
||||||
w.Header().Add("HX-Redirect", "/")
|
if !emailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
|
} else {
|
||||||
|
utils.DoRedirect(w, r, "/")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
auth.Error("Invalid email or password").Render(r.Context(), w)
|
auth.Error("Invalid email or password").Render(r.Context(), w)
|
||||||
}
|
}
|
||||||
@@ -162,14 +227,16 @@ func HandleSignInComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
id := getSessionID(r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
|
||||||
_, err := db.Exec("DELETE FROM session WHERE session_id = ?", id)
|
if user != nil {
|
||||||
|
_, err := db.Exec("DELETE FROM session WHERE session_id = ?", user.SessionId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Could not delete session: %v", err)
|
slog.Error("Could not delete session: %v", err)
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
c := http.Cookie{
|
c := http.Cookie{
|
||||||
Name: "id",
|
Name: "id",
|
||||||
@@ -186,6 +253,29 @@ func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func HandleVerifyResendComp(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
if user == nil || !user.SessionValid || user.EmailVerified {
|
||||||
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sendVerificationEmail(db, r, user.Id.String(), user.Email)
|
||||||
|
|
||||||
|
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendVerificationEmail(db *sql.DB, r *http.Request, userId string, email string) {
|
||||||
|
registerComp := tempMail.Register(userId)
|
||||||
|
|
||||||
|
var writer strings.Builder
|
||||||
|
|
||||||
|
registerComp.Render(r.Context(), &writer)
|
||||||
|
utils.SendMail(email, "Welcome to ME-FIT", writer.String())
|
||||||
|
}
|
||||||
|
|
||||||
func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) bool {
|
func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) bool {
|
||||||
var session_id_bytes []byte = make([]byte, 32)
|
var session_id_bytes []byte = make([]byte, 32)
|
||||||
_, err := rand.Reader.Read(session_id_bytes)
|
_, err := rand.Reader.Read(session_id_bytes)
|
||||||
@@ -223,41 +313,6 @@ func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sq
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSessionID(r *http.Request) string {
|
|
||||||
for _, c := range r.Cookies() {
|
|
||||||
if c.Name == "id" {
|
|
||||||
return c.Value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func verifySessionAndReturnUser(db *sql.DB, r *http.Request) *User {
|
|
||||||
sessionId := getSessionID(r)
|
|
||||||
if sessionId == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var user User
|
|
||||||
var createdAt time.Time
|
|
||||||
|
|
||||||
err := db.QueryRow(`
|
|
||||||
SELECT u.user_uuid, u.email, s.created_at
|
|
||||||
FROM session s
|
|
||||||
INNER JOIN user u ON s.user_uuid = u.user_uuid
|
|
||||||
WHERE session_id = ?`, sessionId).Scan(&user.id, &user.email, &createdAt)
|
|
||||||
if err != nil {
|
|
||||||
slog.Warn("Could not verify session: " + err.Error())
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if createdAt.Add(time.Duration(8 * time.Hour)).Before(time.Now()) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &user
|
|
||||||
}
|
|
||||||
|
|
||||||
func getHashPassword(password string, salt []byte) []byte {
|
func getHashPassword(password string, salt []byte) []byte {
|
||||||
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
|
"me-fit/utils"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/a-h/templ"
|
"github.com/a-h/templ"
|
||||||
@@ -10,8 +11,10 @@ import (
|
|||||||
|
|
||||||
func HandleIndexAnd404(db *sql.DB) http.HandlerFunc {
|
func HandleIndexAnd404(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
|
||||||
var comp templ.Component = nil
|
var comp templ.Component = nil
|
||||||
userComp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
userComp := UserInfoComp(user)
|
||||||
|
|
||||||
if r.URL.Path != "/" {
|
if r.URL.Path != "/" {
|
||||||
comp = template.Layout(template.NotFound(), userComp)
|
comp = template.Layout(template.NotFound(), userComp)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
"me-fit/template/workout"
|
"me-fit/template/workout"
|
||||||
|
"me-fit/utils"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -13,9 +14,9 @@ import (
|
|||||||
|
|
||||||
func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := verifySessionAndReturnUser(db, r)
|
user := utils.GetUser(r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
http.Redirect(w, r, "/auth/signin", http.StatusSeeOther)
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,9 +29,9 @@ func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleWorkoutNewComp(db *sql.DB) http.HandlerFunc {
|
func HandleWorkoutNewComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := verifySessionAndReturnUser(db, r)
|
user := utils.GetUser(r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
w.Header().Add("HX-Redirect", "/auth/signin")
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,7 +64,7 @@ func HandleWorkoutNewComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var rowId int
|
var rowId int
|
||||||
err = db.QueryRow("INSERT INTO workout (user_id, date, type, sets, reps) VALUES (?, ?, ?, ?, ?) RETURNING rowid", user.id, date, typeStr, sets, reps).Scan(&rowId)
|
err = db.QueryRow("INSERT INTO workout (user_id, date, type, sets, reps) VALUES (?, ?, ?, ?, ?) RETURNING rowid", user.Id, date, typeStr, sets, reps).Scan(&rowId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error(err.Error())
|
slog.Error(err.Error())
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
@@ -83,13 +84,13 @@ func HandleWorkoutNewComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleWorkoutGetComp(db *sql.DB) http.HandlerFunc {
|
func HandleWorkoutGetComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := verifySessionAndReturnUser(db, r)
|
user := utils.GetUser(r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
w.Header().Add("HX-Redirect", "/auth/signin")
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := db.Query("SELECT rowid, date, type, sets, reps FROM workout WHERE user_id = ? ORDER BY date desc", user.id)
|
rows, err := db.Query("SELECT rowid, date, type, sets, reps FROM workout WHERE user_id = ? ORDER BY date desc", user.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@@ -120,9 +121,9 @@ func HandleWorkoutGetComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleWorkoutDeleteComp(db *sql.DB) http.HandlerFunc {
|
func HandleWorkoutDeleteComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := verifySessionAndReturnUser(db, r)
|
user := utils.GetUser(r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
w.Header().Add("HX-Redirect", "/auth/signin")
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,7 +133,7 @@ func HandleWorkoutDeleteComp(db *sql.DB) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
res, err := db.Exec("DELETE FROM workout WHERE user_id = ? AND rowid = ?", user.id, rowId)
|
res, err := db.Exec("DELETE FROM workout WHERE user_id = ? AND rowid = ?", user.Id, rowId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
templ SignInOrUp(isSignIn bool) {
|
templ SignInOrUpComp(isSignIn bool) {
|
||||||
<form
|
<form
|
||||||
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
||||||
hx-target="#sign-in-or-up-error"
|
hx-target="#sign-in-or-up-error"
|
||||||
|
|||||||
20
template/auth/verify.templ
Normal file
20
template/auth/verify.templ
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
templ VerifyComp() {
|
||||||
|
<main>
|
||||||
|
<div class="flex flex-col items-center justify-center h-screen">
|
||||||
|
<h2 class="text-6xl mb-10">
|
||||||
|
Verify your email
|
||||||
|
</h2>
|
||||||
|
<p class="text-lg text-center">
|
||||||
|
We have sent you an email with a link to verify your account.
|
||||||
|
</p>
|
||||||
|
<p class="text-lg text-center">
|
||||||
|
Please check your inbox/spam and click on the link to verify your account.
|
||||||
|
</p>
|
||||||
|
<button class="btn mt-8" hx-get="/api/auth/verify-resend" hx-sync="this:drop" hx-swap="outerHTML">
|
||||||
|
resend verification email
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
}
|
||||||
19
template/mail/register.templ
Normal file
19
template/mail/register.templ
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package mail;
|
||||||
|
|
||||||
|
import "me-fit/utils"
|
||||||
|
|
||||||
|
templ Register(mailCode string) {
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"/>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||||
|
<title>Welcome</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h4>Thank you for Sign Up!</h4>
|
||||||
|
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/verify-email?code=" + mailCode) }>here</a> to verify your account.</p>
|
||||||
|
<p>Kind regards</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
}
|
||||||
11
types/types.go
Normal file
11
types/types.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import "github.com/google/uuid"
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
Id uuid.UUID
|
||||||
|
Email string
|
||||||
|
SessionId string
|
||||||
|
EmailVerified bool
|
||||||
|
SessionValid bool
|
||||||
|
}
|
||||||
12
utils/env.go
12
utils/env.go
@@ -14,6 +14,7 @@ var (
|
|||||||
SmtpFromMail string
|
SmtpFromMail string
|
||||||
SmtpFromName string
|
SmtpFromName string
|
||||||
BaseUrl string
|
BaseUrl string
|
||||||
|
Environment string
|
||||||
)
|
)
|
||||||
|
|
||||||
func MustInitEnv() {
|
func MustInitEnv() {
|
||||||
@@ -24,6 +25,7 @@ func MustInitEnv() {
|
|||||||
SmtpFromMail = os.Getenv("SMTP_FROM_MAIL")
|
SmtpFromMail = os.Getenv("SMTP_FROM_MAIL")
|
||||||
SmtpFromName = os.Getenv("SMTP_FROM_NAME")
|
SmtpFromName = os.Getenv("SMTP_FROM_NAME")
|
||||||
BaseUrl = os.Getenv("BASE_URL")
|
BaseUrl = os.Getenv("BASE_URL")
|
||||||
|
Environment = os.Getenv("ENVIRONMENT")
|
||||||
|
|
||||||
if SmtpHost == "" {
|
if SmtpHost == "" {
|
||||||
log.Fatal("SMTP_HOST must be set")
|
log.Fatal("SMTP_HOST must be set")
|
||||||
@@ -46,12 +48,10 @@ func MustInitEnv() {
|
|||||||
if BaseUrl == "" {
|
if BaseUrl == "" {
|
||||||
log.Fatal("BASE_URL must be set")
|
log.Fatal("BASE_URL must be set")
|
||||||
}
|
}
|
||||||
|
if Environment == "" {
|
||||||
|
log.Fatal("ENVIRONMENT must be set")
|
||||||
|
}
|
||||||
|
|
||||||
slog.Info("BASE_URL is " + BaseUrl)
|
slog.Info("BASE_URL is " + BaseUrl)
|
||||||
slog.Info("SMTP_HOST is " + SmtpHost)
|
slog.Info("ENVIRONMENT is " + Environment)
|
||||||
slog.Info("SMTP_PORT is " + SmtpPort)
|
|
||||||
slog.Info("SMTP_USER is " + SmtpUser)
|
|
||||||
slog.Info("SMTP_PASS is " + SmtpPass)
|
|
||||||
slog.Info("SMTP_FROM_MAIL is " + SmtpFromMail)
|
|
||||||
slog.Info("SMTP_FROM_NAME is " + SmtpFromName)
|
|
||||||
}
|
}
|
||||||
|
|||||||
72
utils/http.go
Normal file
72
utils/http.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
|
"me-fit/types"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ContextKey string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ContextKeyUser ContextKey = "user_id"
|
||||||
|
)
|
||||||
|
|
||||||
|
func DoRedirect(w http.ResponseWriter, r *http.Request, url string) {
|
||||||
|
isHtmx := r.Header.Get("HX-Request") == "true"
|
||||||
|
if isHtmx {
|
||||||
|
w.Header().Add("HX-Redirect", url)
|
||||||
|
} else {
|
||||||
|
http.Redirect(w, r, url, http.StatusSeeOther)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUser(r *http.Request) *types.User {
|
||||||
|
user := r.Context().Value(ContextKeyUser)
|
||||||
|
if user != nil {
|
||||||
|
return user.(*types.User)
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUserFromSession(db *sql.DB, r *http.Request) *types.User {
|
||||||
|
sessionId := getSessionID(r)
|
||||||
|
if sessionId == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var user types.User
|
||||||
|
var createdAt time.Time
|
||||||
|
|
||||||
|
user.SessionId = sessionId
|
||||||
|
|
||||||
|
err := db.QueryRow(`
|
||||||
|
SELECT u.user_uuid, u.email, u.email_verified, s.created_at
|
||||||
|
FROM session s
|
||||||
|
INNER JOIN user u ON s.user_uuid = u.user_uuid
|
||||||
|
WHERE session_id = ?`, sessionId).Scan(&user.Id, &user.Email, &user.EmailVerified, &createdAt)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("Could not verify session: " + err.Error())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if createdAt.Add(time.Duration(8 * time.Hour)).Before(time.Now()) {
|
||||||
|
user.SessionValid = false
|
||||||
|
} else {
|
||||||
|
user.SessionValid = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return &user
|
||||||
|
}
|
||||||
|
|
||||||
|
func getSessionID(r *http.Request) string {
|
||||||
|
for _, c := range r.Cookies() {
|
||||||
|
if c.Name == "id" {
|
||||||
|
return c.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -1,19 +1,15 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log/slog"
|
"fmt"
|
||||||
"net/smtp"
|
"net/smtp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SendWelcomeMail(to string) {
|
func SendMail(to string, subject string, message string) error {
|
||||||
|
|
||||||
auth := smtp.PlainAuth("", SmtpUser, SmtpPass, SmtpHost)
|
auth := smtp.PlainAuth("", SmtpUser, SmtpPass, SmtpHost)
|
||||||
|
|
||||||
msg := "From: " + SmtpFromName + " <" + SmtpFromMail + ">\nTo: " + to + "\nSubject: Welcome to me-fit\n\nWelcome to me-fit!"
|
msg := fmt.Sprintf("From: %v <%v>\nTo: %v\nSubject: %v\nMIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n%v", SmtpFromName, SmtpFromMail, to, subject, message)
|
||||||
|
|
||||||
err := smtp.SendMail(SmtpHost+":"+SmtpPort, auth, SmtpFromMail, []string{to}, []byte(msg))
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("Could not send mail: " + err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
|
return smtp.SendMail(SmtpHost+":"+SmtpPort, auth, SmtpFromMail, []string{to}, []byte(msg))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user