45 lines
No EOL
1.9 KiB
PL/PgSQL
45 lines
No EOL
1.9 KiB
PL/PgSQL
-- Création de la table pour stocker les tokens d'accès sécurisés
|
|
CREATE TABLE auto_declaration_tokens (
|
|
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
|
|
token TEXT NOT NULL UNIQUE,
|
|
salarie_id UUID NOT NULL REFERENCES salaries(id) ON DELETE CASCADE,
|
|
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
|
used BOOLEAN DEFAULT FALSE,
|
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
|
used_at TIMESTAMP WITH TIME ZONE,
|
|
created_by UUID REFERENCES auth.users(id),
|
|
email_sent BOOLEAN DEFAULT FALSE,
|
|
email_sent_at TIMESTAMP WITH TIME ZONE
|
|
);
|
|
|
|
-- Index pour les performances
|
|
CREATE INDEX idx_auto_declaration_tokens_token ON auto_declaration_tokens(token);
|
|
CREATE INDEX idx_auto_declaration_tokens_expires ON auto_declaration_tokens(expires_at);
|
|
CREATE INDEX idx_auto_declaration_tokens_salarie ON auto_declaration_tokens(salarie_id);
|
|
|
|
-- Fonction pour nettoyer automatiquement les tokens expirés
|
|
CREATE OR REPLACE FUNCTION cleanup_expired_tokens()
|
|
RETURNS void AS $$
|
|
BEGIN
|
|
DELETE FROM auto_declaration_tokens
|
|
WHERE expires_at < NOW() - INTERVAL '7 days';
|
|
END;
|
|
$$ LANGUAGE plpgsql;
|
|
|
|
-- Planifier le nettoyage automatique (optionnel, nécessite pg_cron)
|
|
-- SELECT cron.schedule('cleanup-expired-tokens', '0 2 * * *', 'SELECT cleanup_expired_tokens();');
|
|
|
|
-- Sécurité RLS (Row Level Security)
|
|
ALTER TABLE auto_declaration_tokens ENABLE ROW LEVEL SECURITY;
|
|
|
|
-- Politique pour que seuls les utilisateurs authentifiés puissent créer des tokens
|
|
CREATE POLICY "Users can create tokens" ON auto_declaration_tokens
|
|
FOR INSERT WITH CHECK (auth.role() = 'authenticated');
|
|
|
|
-- Politique pour que seuls les créateurs puissent voir leurs tokens
|
|
CREATE POLICY "Users can view their tokens" ON auto_declaration_tokens
|
|
FOR SELECT USING (created_by = auth.uid() OR auth.role() = 'service_role');
|
|
|
|
-- Politique pour la mise à jour (marquer comme utilisé)
|
|
CREATE POLICY "Tokens can be marked as used" ON auto_declaration_tokens
|
|
FOR UPDATE USING (true); |