-- ===================================================================== -- 003_roster.sql : 허용 명단(allowlist) + 로그인 시 자동 역할·학급 배정 -- -- 하는 일 -- 1) allowed_users : 학생·교사·관리자 명단. 이 표에 없는 구글 계정은 로그인(최초 가입)이 막힙니다. -- 2) handle_new_user() 를 바꿈 : 명단에 있으면 역할(student/teacher/admin)·이름·학급을 자동으로 넣고, -- 명단에 없으면 'not_allowed' 오류로 가입을 거절합니다. -- 3) sync_roster() : 이미 가입한 사람의 역할·학급을 명단대로 다시 맞춤 (명단을 고친 뒤 실행) -- -- 실행 순서 (중요): 이 파일 실행 -> 08_import_roster.py 로 명단 적재 -> 그 다음에 구글로 로그인 -- (명단을 넣기 전에 로그인하면 관리자도 거절됩니다. 거절돼도 명단 적재 후 다시 로그인하면 됩니다.) -- 여러 번 실행해도 안전합니다. -- ===================================================================== create table if not exists allowed_users ( email text primary key check (email = lower(email)), -- 항상 소문자 name text, role user_role not null, school_year smallint not null default 2026, -- 학년도 (3월에 새 학년이 되면 새로 적재) grade smallint check (grade between 1 and 3), class_no smallint check (class_no >= 1), student_no smallint, -- 번호 (학생) subject text, -- 담당 과목 (교사) active boolean not null default true, -- false 로 바꾸면 신규 가입 불가 created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); drop trigger if exists trg_allowed_users_updated on allowed_users; create trigger trg_allowed_users_updated before update on allowed_users for each row execute function set_updated_at(); -- 명단은 개인정보: 앱 서버(service_role)만 다룹니다. 일반 로그인 사용자에게는 정책을 주지 않습니다. alter table allowed_users enable row level security; grant select, insert, update, delete on allowed_users to service_role; -- 한 사람의 학급 소속을 명단 기준으로 맞춤: 학생은 학급 구성원으로, 교사는 담임으로 create or replace function apply_roster_row(uid uuid, r allowed_users) returns void language plpgsql security definer set search_path = public as $$ declare cid uuid; begin if r.grade is null or r.class_no is null then return; end if; insert into classes (school_year, grade, class_no) values (r.school_year, r.grade, r.class_no) on conflict (school_year, grade, class_no) do nothing; select id into cid from classes where school_year = r.school_year and grade = r.grade and class_no = r.class_no; if r.role = 'student' then insert into class_members (class_id, student_id, student_no) values (cid, uid, r.student_no) on conflict (class_id, student_id) do update set student_no = excluded.student_no; elsif r.role = 'teacher' then update classes set homeroom_teacher_id = uid where id = cid; end if; end $$; -- 구글 로그인으로 auth.users 가 새로 생길 때: 명단에 있어야만 통과 create or replace function handle_new_user() returns trigger language plpgsql security definer set search_path = public as $$ declare r allowed_users; begin select * into r from allowed_users where email = lower(new.email) and active; if not found then raise exception 'not_allowed: 허용 명단에 없는 계정입니다.'; end if; insert into profiles (id, email, name, role) values ( new.id, lower(new.email), coalesce(r.name, new.raw_user_meta_data ->> 'full_name', new.raw_user_meta_data ->> 'name'), r.role ) on conflict (id) do nothing; perform apply_roster_row(new.id, r); return new; end $$; drop trigger if exists on_auth_user_created on auth.users; create trigger on_auth_user_created after insert on auth.users for each row execute function handle_new_user(); -- 이미 가입한 사람의 역할·이름·학급을 명단대로 다시 맞춤. 맞춘 사람 수를 돌려줌 create or replace function sync_roster() returns integer language plpgsql security definer set search_path = public as $$ declare a allowed_users; n integer := 0; begin for a in select * from allowed_users where active loop update profiles set role = a.role, name = coalesce(a.name, name) where lower(email) = a.email; if found then perform apply_roster_row((select id from profiles where lower(email) = a.email limit 1), a); n := n + 1; end if; end loop; return n; end $$; revoke execute on function sync_roster() from public, anon, authenticated; revoke execute on function apply_roster_row(uuid, allowed_users) from public, anon, authenticated; grant execute on function sync_roster() to service_role; grant execute on function apply_roster_row(uuid, allowed_users) to service_role;