go-urlsh/internal/db/cookie.go

68 lines
2.1 KiB
Go
Raw Permalink Normal View History

2023-04-27 12:34:24 +02:00
package db
import (
"context"
2024-05-04 17:06:01 +02:00
"database/sql"
"fmt"
2023-04-27 12:34:24 +02:00
"log"
2024-05-04 17:06:01 +02:00
"code.lila.network/adoralaura/go-urlsh/models"
2023-04-27 12:34:24 +02:00
)
// IsCookieValid checks the database if Cookie val is valid.
//
// Returns true if it's valid, false if not.
func IsCookieValid(val string) bool {
if val == "" {
return false
}
2023-06-16 14:30:27 +02:00
count, err := models.DB.NewSelect().Model((*models.Session)(nil)).Where("cookie = ?", val).Count(context.Background())
2023-04-27 12:34:24 +02:00
if err != nil {
log.Printf("Error checking cookie validity for cookie %v\n", val)
return false
}
if count < 1 {
return false
} else {
return true
}
}
2024-05-04 17:06:01 +02:00
func GetUserFromCookie(cookie string) (models.User, error) {
var session models.Session
var user models.User
err := models.DB.NewSelect().Model(&session).Where("cookie = ?", cookie).Scan(context.Background())
if err != nil {
if err == sql.ErrNoRows {
return models.User{}, fmt.Errorf("[GetUserFromCookie] Session %v not found", cookie)
} else {
return models.User{}, fmt.Errorf("[GetUserFromCookie] Error querying session %v from database: %v", cookie, err)
}
}
err = models.DB.NewSelect().Model(&user).Where("username = ?", session.UserName).Scan(context.Background())
if err != nil {
return models.User{}, fmt.Errorf("[GetUserFromCookie] Error querying user %v from database: %v", session.UserName, err)
}
return user, nil
}
func GetUserFromMFACookie(cookie string) (models.User, error) {
var transaction models.MFALoginTransaction
var user models.User
err := models.DB.NewSelect().Model(&transaction).Where("sessionkey = ?", cookie).Scan(context.Background())
if err != nil {
if err == sql.ErrNoRows {
return models.User{}, fmt.Errorf("[GetUserFromMFACookie] MFA Transaction %v not found", cookie)
} else {
return models.User{}, fmt.Errorf("[GetUserFromMFACookie] Error querying MFA Transaction %v from database: %v", cookie, err)
}
}
err = models.DB.NewSelect().Model(&user).Where("username = ?", transaction.UserName).Scan(context.Background())
if err != nil {
return models.User{}, fmt.Errorf("[GetUserFromMFACookie] Error querying user %v from database: %v", transaction.UserName, err)
}
return user, nil
}