Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Supabase Week Theory – Cloud Data Tier for Android: Supabase, SQL, Row Level Security, Auth and REST

Supabase Week – Cloud Data Tier for Android (extra week after Week 13) · 120 min read · 35 MCQs to check yourself

Fireship – Supabase in 100 Seconds

Supabase – Supabase Explained

Supabase – Authorization with Row Level Security (step by step)

Why this extra week?

Until week 13 our apps kept data on the phone (SharedPreferences) or read it from a public demo API. Real apps – campus portals, food delivery, banking – keep data in a cloud database that many users share, with sign-in so each person sees and changes only what they are allowed to.

This week adds that missing piece – the data tier – using Supabase, a free, open-source cloud backend built on PostgreSQL. Your course project (CampusPulse or your own idea) will use it.

Tier Where it runs In our project
Presentation The Android app Activities, fragments, layouts
Logic App + database rules Repository class, Row Level Security policies
Data The cloud Supabase PostgreSQL tables

1. Backend-as-a-Service (BaaS)

Building your own server means writing an API, hosting it, securing it and managing a database. A BaaS gives you all of this ready-made: a database, user accounts, an automatic API, file storage and more – you only design the tables and rules.

Supabase is an open-source BaaS (often called an open-source Firebase alternative). Every project gets:

Part What it does Used in our project?
Database A full PostgreSQL database (tables, SQL, constraints) ✅ events and feedback tables
Auth Sign-up / sign-in with email + password, Google, phone OTP…; issues JWT tokens ✅ email + password
Data API (PostgREST) Turns every table into a REST API automatically: /rest/v1/<table> ✅ via Retrofit
Realtime Pushes database changes to connected apps live Level-up idea
Storage Stores files (images, PDFs) in buckets Level-up idea (event posters)
Edge Functions Your own server code (TypeScript) running near users Level-up idea

Supabase vs Firebase (exam favourite)

Supabase Firebase (Firestore)
Database type Relational (PostgreSQL, SQL, tables, joins) NoSQL documents and collections
Open source Yes – can be self-hosted No
Security rules Row Level Security policies written in SQL Firestore Security Rules language
API Auto-generated REST (and GraphQL) SDKs
Best when Data has relations (users → events → feedback), you know SQL Simple document data, deep Google integration

2. Your project: URL and API keys

Each Supabase project has a Project URL like https://abcdxyz.supabase.co and API keys (Dashboard → Project Settings → API Keys):

Key Looks like Where it may be used
Publishable key sb_publishable_… Safe in the app – it only identifies your project. What it can do is controlled by Row Level Security.
Secret key sb_secret_… Never in an app or on GitHub – it bypasses Row Level Security. Server code only.
Legacy anon / service_role keys long eyJ… JWTs Older projects and tutorials use these; Supabase is replacing them with the keys above (deprecation announced for the end of 2026).

The publishable key goes in the apikey header of every request. A signed-in user's access token (a JWT) goes in the Authorization: Bearer … header.

3. Tables and SQL

You design tables in the Table Editor (spreadsheet-like) or the SQL Editor. Useful column types:

Type Use
uuid with default gen_random_uuid() Primary keys that are hard to guess
text Titles, descriptions, emails
int, double precision Ratings; latitude and longitude
timestamptz Date + time with time zone (event start time)
boolean Yes/no flags

Add constraints so bad data is rejected by the database itself, e.g. check (rating between 1 and 5) or not null.

4. Row Level Security (RLS) – the most important idea

With an automatic API, anyone with the publishable key could call /rest/v1/events. RLS decides, row by row, who may read or change data.

-- Everyone who is signed in can read events
create policy "read events" on events for select to authenticated using (true);
-- Users can add events only as themselves
create policy "add own events" on events for insert to authenticated with check (auth.uid() = user_id);
-- Users can delete only their own events
create policy "delete own events" on events for delete to authenticated using (auth.uid() = user_id);

⚠️ A table without RLS in the public schema can be read and changed by anyone who has your publishable key. Always enable RLS.

5. Supabase Auth and tokens

JWT (JSON Web Token) = a signed token with three parts header.payload.signature. The payload contains the user id (sub) and expiry (exp). The server checks the signature, so the app cannot fake it.

6. The REST API (PostgREST) in one table

Base: https://<project>.supabase.co/rest/v1/

Task Request
Read all rows, sorted GET /events?select=*&order=starts_at.asc
Filter GET /events?category=eq.Sports (also neq, gt, lt, gte, ilike)
Choose columns GET /events?select=id,title,starts_at
Insert POST /events with a JSON body; header Prefer: return=representation returns the saved row
Update PATCH /events?id=eq.<id> with the changed fields
Delete DELETE /events?id=eq.<id>

Every request needs the header apikey: <publishable key>; requests for a signed-in user also send Authorization: Bearer <access token>.

7. Calling Supabase from Android – two ways

Retrofit + REST (our choice) supabase-kt (official Kotlin client)
New things to learn Nothing – same as Lab 12 A new library (Ktor, plugins)
Language Java (our course) and Kotlin Kotlin only – cannot be used from a Java app
Shows how HTTP really works Yes – you see URLs, headers, JSON Hidden inside the library
Extra features Do it yourself (token refresh is ~10 lines) Realtime, Storage, session handling built in

Retrofit's enqueue() runs the network call on a background thread and delivers the answer to your Callback on the main thread, so the UI never freezes (week 14 – threading). Never call execute() on the main thread – Android throws NetworkOnMainThreadException.

8. Good practice and limits

Short and long questions

1. What are access tokens and refresh tokens? How does an app use them?

Model answer

After sign-in Supabase returns a short-lived access token (a JWT, about 1 hour) and a long-lived refresh token. The app sends the access token as Authorization: Bearer on each request. When a request returns 401 because it expired, the app calls /auth/v1/token?grant_type=refresh_token with the refresh token to get a new access token, then retries.

2. Differentiate the publishable key and the secret key.

Model answer

The publishable key (sb_publishable_…) identifies the project and is safe in apps; what it can do is limited by RLS. The secret key (sb_secret_…) bypasses RLS and gives full access, so it must only be used in trusted server code, never in an app or public repository.

3. Write a policy that allows signed-in users to delete only the events they created.

Model answer

create policy "delete own events" on public.events for delete to authenticated using (auth.uid() = user_id); — auth.uid() is the caller from the JWT, user_id is the owner stored in the row.

4. Why do we use an OkHttp interceptor with Retrofit for Supabase?

Model answer

Every request needs the apikey header. An interceptor adds it to all outgoing requests in one place instead of repeating @Header on every method, keeping the API interface clean and avoiding mistakes.

5. Explain the three-tier architecture of a mobile app that uses Supabase. Show where Auth, Row Level Security and the REST API fit, with a diagram.

Model answer

Presentation tier: the Android app (activities, fragments, layouts) shows data and takes input. Logic tier: the app's repository class (validation, token refresh) plus database rules – Row Level Security policies and CHECK constraints that run inside Supabase. Data tier: PostgreSQL tables in the Supabase cloud. Flow: App → HTTPS (Retrofit) → Supabase API gateway → Auth verifies the JWT → PostgREST converts the request to SQL → PostgreSQL applies RLS (auth.uid()) → returns JSON → app updates RecyclerView. Diagram: [Android UI] ⇄ [Repository/Retrofit] ⇄ (internet) ⇄ [Supabase: Auth | PostgREST | RLS] ⇄ [PostgreSQL tables]. Benefits: shared cloud data, security in the database, no custom server.

6. Compare Supabase and Firebase Firestore (any four points).

Model answer

Supabase uses relational PostgreSQL tables with SQL and joins; Firestore uses NoSQL documents and collections. Supabase is open source and can be self-hosted; Firebase is proprietary. Supabase secures data with Row Level Security policies in SQL; Firestore uses Security Rules. Supabase auto-generates a REST API; Firebase is used through SDKs.

7. What is Backend-as-a-Service? Name four services Supabase provides.

Model answer

A BaaS provides ready-made backend features so app developers do not build and host their own server. Supabase provides a PostgreSQL database, Auth (user sign-up/sign-in with JWTs), an automatic REST Data API (PostgREST), Realtime updates, file Storage and Edge Functions.

8. Write the REST requests to (a) read all events sorted by start time and (b) delete the event with id 7.

Model answer

(a) GET https://<project>.supabase.co/rest/v1/events?select=*&order=starts_at.asc (b) DELETE https://<project>.supabase.co/rest/v1/events?id=eq.7 — both with headers apikey: <publishable key> and Authorization: Bearer <access token>.

9. Design the Supabase tables and RLS policies for a campus events app where every signed-in user can read events, add events as themselves, and edit or delete only their own events. Write the SQL.

Model answer

create table public.events (id uuid primary key default gen_random_uuid(), created_at timestamptz not null default now(), user_id uuid not null default auth.uid() references auth.users(id) on delete cascade, title text not null check (char_length(title) between 3 and 120), description text, category text not null default 'General', starts_at timestamptz not null, venue text, lat double precision, lng double precision); alter table public.events enable row level security; create policy "read" on public.events for select to authenticated using (true); create policy "add own" on public.events for insert to authenticated with check (auth.uid() = user_id); create policy "edit own" on public.events for update to authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id); create policy "delete own" on public.events for delete to authenticated using (auth.uid() = user_id). Explanation: user_id defaults to the caller, RLS checks ownership on write, all signed-in users can read.

10. Differentiate between the using and with check clauses of a policy.

Model answer

using (...) filters existing rows: which rows a select, update or delete can see or affect. with check (...) validates new or changed rows: an insert or update is rejected if the new row does not satisfy the condition.

11. What is Row Level Security? Why must it be enabled on tables used by a mobile app?

Model answer

RLS is a PostgreSQL feature that checks policies for every row a user tries to read or write. Because the app ships the publishable key and the API is public, without RLS anyone with the key could read or change all rows. With RLS on, nothing is allowed until policies grant specific actions to specific users.

12. Describe the complete sign-up and sign-in flow of an Android app using Supabase Auth over REST, including token storage and refresh.

Model answer
  1. Sign-up: POST /auth/v1/signup with email, password and data (user_metadata such as full_name), header apikey. If email confirmation is ON the user must confirm first; otherwise a session is returned. 2) Sign-in: POST /auth/v1/token?grant_type=password returns access_token (JWT, ~1 h), refresh_token and user. 3) The app stores the tokens in SharedPreferences and sends Authorization: Bearer <access_token> with each data request. 4) On a 401 response, call /auth/v1/token?grant_type=refresh_token, save the new tokens and retry once; if refresh fails, send the user to the sign-in screen. 5) Sign-out: delete the saved tokens. Security: only the publishable key is in the app; RLS uses auth.uid() from the token.

13. What is a JWT? List its parts.

Model answer

A JSON Web Token is a compact signed token used to prove identity. It has three Base64URL parts separated by dots: header (algorithm), payload (claims such as sub = user id, exp = expiry) and signature, which lets the server verify it was not altered.

This lesson ends with a quiz of 35 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Assignment 3 (Weeks 10–13) – Course Notes and Announcements: Data, REST API and Messaging · Next: Supabase Week Lab – Create a Supabase Backend and Read/Write It from Android with Retrofit

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester