2024-11-06 18:47:22 +01:00
|
|
|
package tokens
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
2024-11-08 16:04:43 +01:00
|
|
|
"encoding/base64"
|
2024-11-06 18:47:22 +01:00
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.qowevisa.me/Qowevisa/fin-check-api/db"
|
|
|
|
)
|
|
|
|
|
|
|
|
func CreateSessionFromToken(token string, userID uint) error {
|
2024-11-08 16:04:43 +01:00
|
|
|
sessionID := getSessionIDFromToken(token)
|
2024-11-06 18:47:22 +01:00
|
|
|
dbc := db.Connect()
|
|
|
|
session := &db.Session{
|
|
|
|
ID: string(sessionID),
|
|
|
|
UserID: userID,
|
|
|
|
ExpireAt: time.Now().Add(time.Hour),
|
|
|
|
}
|
|
|
|
if err := dbc.Create(session).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func ValidateSessionToken(token string) bool {
|
2024-11-08 16:04:43 +01:00
|
|
|
sessionID := getSessionIDFromToken(token)
|
2024-11-06 18:47:22 +01:00
|
|
|
dbc := db.Connect()
|
|
|
|
session := &db.Session{}
|
2024-11-08 16:06:31 +01:00
|
|
|
if err := dbc.Find(session, db.Session{ID: sessionID}).Error; err != nil {
|
2024-11-06 18:47:22 +01:00
|
|
|
log.Printf("DBERROR: %v\n", err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if session.ID == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if session.ExpireAt.Unix() < time.Now().Unix() {
|
|
|
|
dbc.Delete(session)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return session.ID != ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetSession(token string) (*db.Session, error) {
|
2024-11-08 16:04:43 +01:00
|
|
|
sessionID := getSessionIDFromToken(token)
|
2024-11-06 18:47:22 +01:00
|
|
|
dbc := db.Connect()
|
|
|
|
session := &db.Session{}
|
2024-11-08 16:04:43 +01:00
|
|
|
if err := dbc.Find(session, db.Session{ID: sessionID}).Error; err != nil {
|
2024-11-06 18:47:22 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return session, nil
|
|
|
|
}
|
2024-11-08 16:04:43 +01:00
|
|
|
|
|
|
|
func getSessionIDFromToken(token string) string {
|
|
|
|
salt := []byte("w40DJV3v1flySvFdxHWbBSJsIOaakkVs5FG7brq4oi1#nEz2fEZxpUfyBwkkww7f")
|
|
|
|
bytes := sha256.New().Sum(append(salt, []byte(token)...))
|
|
|
|
return base64.URLEncoding.EncodeToString(bytes)
|
|
|
|
}
|