init
This commit is contained in:
commit
d69342b2e9
160 changed files with 28681 additions and 0 deletions
45
internal/db/sessions.go
Normal file
45
internal/db/sessions.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (db *DB) CreateSession(ctx context.Context, userID string) (*Session, error) {
|
||||
token := make([]byte, 32)
|
||||
if _, err := rand.Read(token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s := &Session{
|
||||
Token: hex.EncodeToString(token),
|
||||
UserID: userID,
|
||||
ExpiresAt: time.Now().Add(30 * 24 * time.Hour),
|
||||
}
|
||||
|
||||
_, err := db.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1, $2, $3)`,
|
||||
s.Token, s.UserID, s.ExpiresAt)
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (db *DB) ValidateSession(ctx context.Context, token string) (*Session, error) {
|
||||
var s Session
|
||||
err := db.pool.QueryRow(ctx,
|
||||
`SELECT token, user_id, expires_at FROM sessions
|
||||
WHERE token = $1 AND expires_at > NOW()`,
|
||||
token).Scan(&s.Token, &s.UserID, &s.ExpiresAt)
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &s, err
|
||||
}
|
||||
|
||||
func (db *DB) DeleteSession(ctx context.Context, token string) error {
|
||||
_, err := db.pool.Exec(ctx, `DELETE FROM sessions WHERE token = $1`, token)
|
||||
return err
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue