chore(auth): add test for retrieving session from db #181
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s
This commit is contained in:
@@ -10,13 +10,20 @@ import (
|
||||
)
|
||||
|
||||
func MustRunMigrations(db *sql.DB) {
|
||||
mustRunMigrationsInternal(db, "")
|
||||
}
|
||||
func MustRunMigrationsTest(db *sql.DB, pathPrefix string) {
|
||||
mustRunMigrationsInternal(db, "../")
|
||||
}
|
||||
|
||||
func mustRunMigrationsInternal(db *sql.DB, pathPrefix string) {
|
||||
driver, err := sqlite3.WithInstance(db, &sqlite3.Config{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
m, err := migrate.NewWithDatabaseInstance(
|
||||
"file://./migration/",
|
||||
"file://./"+pathPrefix+"migration/",
|
||||
"",
|
||||
driver)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"me-fit/types"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
@@ -61,39 +59,10 @@ func GetUser(r *http.Request) *types.User {
|
||||
}
|
||||
}
|
||||
|
||||
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()) {
|
||||
return nil
|
||||
} else {
|
||||
return &user
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func getSessionID(r *http.Request) string {
|
||||
func GetSessionID(r *http.Request) types.SessionId {
|
||||
for _, c := range r.Cookies() {
|
||||
if c.Name == "id" {
|
||||
return c.Value
|
||||
return types.SessionId(c.Value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
|
||||
Reference in New Issue
Block a user