28 lines
721 B
Go
28 lines
721 B
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
var ErrInvalidSession = errors.New("invalid session")
|
|
|
|
// Authenticate resolves only an unexpired session belonging to this project.
|
|
func Authenticate(ctx context.Context, db *sql.DB, project, authorization string) (string, error) {
|
|
value, ok := strings.CutPrefix(authorization, "Bearer ")
|
|
if !ok || !tokenPattern.MatchString(value) {
|
|
return "", ErrInvalidSession
|
|
}
|
|
var id string
|
|
err := db.QueryRowContext(ctx, `
|
|
SELECT account_id::text FROM project_sessions
|
|
WHERE project=$1 AND token_hash=$2 AND expires_at>now()
|
|
`, project, digest(value)).Scan(&id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return "", ErrInvalidSession
|
|
}
|
|
return id, err
|
|
}
|