feat(auth): #154 send verification mails
This commit is contained in:
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 ""
|
||||
}
|
||||
Reference in New Issue
Block a user