67 lines
2.1 KiB
Go
67 lines
2.1 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"log"
|
|
|
|
"code.lila.network/adoralaura/go-urlsh/models"
|
|
)
|
|
|
|
// 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
|
|
}
|
|
|
|
count, err := models.DB.NewSelect().Model((*models.Session)(nil)).Where("cookie = ?", val).Count(context.Background())
|
|
if err != nil {
|
|
log.Printf("Error checking cookie validity for cookie %v\n", val)
|
|
return false
|
|
}
|
|
if count < 1 {
|
|
return false
|
|
} else {
|
|
return true
|
|
}
|
|
}
|
|
|
|
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
|
|
|
|
}
|