본문 바로가기
카테고리 없음

[Swift + Supabase] 인증, 약관 동의 구현

by dev.py 2025. 5. 5.

1. Supabase 특징

  • PostgreSQL 기반의 데이터베이스
  • Row Level Security (RLS) 정책을 통한 유저 권한 관리
  • REST,  OAuth, Log 등 백엔드의 기능을 기본적으로 제공하여 별도의 서버 필요 X 
  • 사용 문서가 정말 잘 되어 있어 빠르게 학습 가능

 

2. Swift 

1. Client 초기화

class SupabaseManager {
    static let shared = SupabaseManager()
    let supabase: SupabaseClient

    private init() {
        let supabaseUrl = URL(string: Bundle.main.object(forInfoDictionaryKey: "SUPABASE_URL") as! String)!
        let supabaseKey = Bundle.main.object(forInfoDictionaryKey: "SUPABASE_KEY") as! String
        supabase = SupabaseClient(supabaseURL: supabaseUrl, supabaseKey: supabaseKey)
    }
}

2. 동의 여부 확인

func hasAgreed(to term: TermName) async throws -> Bool {
    let termId = try await getTermId(to: term)
    let userId = supabase.auth.currentUser?.id
    let userTerms = try await supabase
        .from("user_terms")
        .select()
        .eq("user_id", value: userId)
        .eq("terms_id", value: termId)
        .execute()
        .value

    return !userTerms.isEmpty
}

 

 

3. Supabase DB 생성 및 RLS 설정

1.DB 생성

1. Terms - 약관 메타 정보 테이블

create table public.terms (
  id uuid primary key default gen_random_uuid(),
  title text not null,
  version int,
  is_required boolean default true,
  created_at timestamp default now()
);

2. user_terms - 유저가 어떤 약관에 동의했는지 저장

create table public.user_terms (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references auth.users(id) on delete cascade,
  terms_id uuid references public.terms(id) on delete cascade,
  agreed_at timestamp default now()
);

 

 

3. RLS 설정

1. terms RLS 설정

일반 유저들은 조회만 가능

create policy "Allow read for authenticated users"
on public.terms
for select
to authenticated
using (auth.uid() is not null);

 

서버만 CUD(Create/Update/Delete) 가능

create policy "Allow CUD for service role only"
on public.terms
for all
to service_role
using (true)
with check (true);

2. user_terms RLS 설정

로그인한 유저만 자기 데이터만 조회 가능

create policy "Allow user to view their own terms"
on public.user_terms
for select
to authenticated
using (auth.uid() = user_id);

 

로그인한 유저만 자기 user_id로 삽입 가능

create policy "Allow user to insert their own terms"
on public.user_terms
for insert
to authenticated
with check (auth.uid() = user_id);

 

일반 유저는 금지, 서버만 Update, Delete 가능 

create policy "Allow service role full access"
on public.user_terms
for all
to service_role
using (true)
with check (true);