paint-brush
Nantsi indlela abaPhuhlisi abanokuqinisekisa ngayo ukuba iDatha enovakalelo ayifikeleli kwesinye isixhobo ngengozinge@dougsillars1
Imbali entsha

Nantsi indlela abaPhuhlisi abanokuqinisekisa ngayo ukuba iDatha enovakalelo ayifikeleli kwesinye isixhobo ngengozi

nge Doug8m2024/12/25
Read on Terminal Reader

Inde kakhulu; Ukufunda

Abaphuhlisi kufuneka baqinisekise ukuba idatha ebuthathaka egcinwe kwisicelo ayiziswa ngempazamo kwelinye iqela. Esi sifundo siya kukuhamba ngendlela yokwakha iRemix app usebenzisa uMabhalane njengomaleko wobunyani. Emva koko sisebenzisa uKhuseleko lweNqanaba loMqolo ukusuka kwiNeon ukukhusela idatha yomthengi.
featured image - Nantsi indlela abaPhuhlisi abanokuqinisekisa ngayo ukuba iDatha enovakalelo ayifikeleli kwesinye isixhobo ngengozi
Doug HackerNoon profile picture
0-item

Ngaba ukhe wayifumana ipasile yommelwane wakho kumnyango wakho wangaphambili? (Mhlawumbi uyivule ngempazamo?) Mhlawumbi ukhe wanelizwi elinovakalelo elishiyelwe omnye umntu? Njengabaphuhlisi besicelo, ngumsebenzi wakho ukuqinisekisa ukuba idatha ebuthathaka egcinwe kwisicelo sakho ayiziswa ngempazamo kwelinye iqela.


Kukho iindlela ezininzi ezikhoyo zokugcina idatha yomthengi ngokukhuselekileyo, kwaye ezininzi zintsonkothe kakhulu kwaye kunzima ukuziphumeza. Ngokufanelekileyo, umntu unokukhusela yonke idatha yomthengi kwisiseko sedatha enye-ukugcina uyilo lwesici silula kwaye sikhuselekile.


Ukhuseleko lwenqanaba lomqolo (RLS) kukukwazi ukukhusela nokulawula ukufikelela kwimigca ethile yedatha ngaphakathi kwetafile yedatha. Sisixhobo esinamandla esikuvumela ukuba ugcine yonke idatha yomthengi wakho kwisiseko sedatha enye ngaphandle kwenkxalabo malunga nokuvuza kwedatha kuzo zonke iiakhawunti. Nangona kunjalo, ukuphumeza ngokuchanekileyo i-RLS inokuba yinkqubo ekhohlisayo equka ukudibanisa iinkcukacha zokungena kunye neemvume zedatha yakho. I-Neon Gunyazisa le nkqubo ngokudibanisa ngokuzenzekelayo uqinisekiso olusuka kumboneleli wakho we-OAuth kunye nesiseko sedatha sakho sePostgreSQL.


I-Neon Authorise isebenzisa umaleko wakho wobubhali okhoyo ukuchonga wonke umsebenzisi ongeneyo kwaye inxulumanise yonke idata ekwidatabase yakho ngeenkcukacha zabo zokungena. Oku kuqinisekisa ukuba idatha egcinwe kwi-database inokufumaneka kuphela ngabasebenzisi abangenileyo-kwaye kuphela abasebenzisi abangenileyo abanokubona idatha yabo.


Esi sifundo siya kukuhamba ngendlela yokwakha iRemix app usebenzisa uMabhalane njengomaleko wobunyani. UMabhalane sisixhobo sobubhali bokuqinisekisa kunye nolawulo lomsebenzisi. Uza kusebenzisa iNeon Postgres njengomaleko wedatha yakho kwaye uxhathise iNeon Gunyazisa ukukhusela yonke idatha yomthengi ngamnye ongeneyo. Umqolo ngamnye kwitheyibhile uya kutyumba i-userID, ebonelelwa nguMabhalane. Kuphela abo baqinisekisiweyo ngeID yomsebenzisi banokusebenzisana nedatha emgceni.


Isicelo sethu sesampula silula-sirekhoda yonke into yokungena kwi-database ye-RLS, usebenzisa i-userID. Xa iphepha lilayishiwe, ukungena kwe-10 yokugqibela yomsebenzisi oqinisekisiweyo kuya kuboniswa, kwaye akukho datha yabasebenzisi (igcinwe kwitafile efanayo yePostgreSQL) iya kuvela. Masiqalise!

Ukwenza iRemix app


Qala ngokudala isicelo seRemix kunye nokufaka ukuxhomekeka usebenzisa i-snippet yekhowudi engezantsi. Ukufumana imiyalelo ethe vetshe, jonga kwiRemix isikhokelo sokuqalisa ngokukhawuleza .

 ##make a directory and initialise your NPM project mkdir neon-authorize-remix-clerk-app cd neon-authorize-remix-clerk-app npm init -y ## install runtime dependecies for Remix npm i @remix-run/node @remix-run/react @remix-run/serve isbot@4 react react-dom @remix-run/router drizzle-orm npm install @neondatabase/serverless npm install @clerk/remix npm i -D @remix-run/dev vite


Ekubeni i-Remix isebenzisa i-Vite, isixhobo sokwakha iJavascript, yenza vite.config.js kwi-root directory:


 import { vitePlugin as remix } from "@remix-run/dev"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [remix()], });


Phambi kokwenza naluphi na uphuhliso, kufuneka senze iiakhawunti kuMabhalane kunye noNeon ukuze basebenzise iinkonzo zabo:


Ukudala uMabhalane kunye neemeko zeNeon

Unobhala

Sayina ungene kuMabhalane wedeshibhodi ukwenza iprojekthi entsha.

  1. Kukhangelo olusekhohlo, khetha amaqhosha e-API .

    1. Kwibhokisi yokuKhuphela okuKhawuleza, khetha i-Remix, kwaye ukope izinto eziguquguqukayo zokusingqongileyo.
    2. Zincamathelise kwifayile .env kwikhowudi yakho.
  2. Kukhangelo olusekhohlo, khetha “ iitemplates zeJWT.

    1. Yenza ithempleyithi (ndiyibize ngegama elithi " neon-remix ").
    2. Khuphela i -URL ye-JWKS Endpoint ukuze uyisebenzise kamva.

Neon

  1. Ngena kwiNeon console kwaye wenze iprojekthi entsha.

  2. Ukusuka kwimenyu yokukhangela ekhohlo, khetha Gunyazisa .

  3. Yenza umboneleli omtsha kwaye uncamathisele i -URL kaNobhala we-JWKS oyikope kuMabhalane ngaphambili.


Nje ukuba wenze umzekelo, cofa "Qalisa." Iphaneli esecaleni iya kuvula ngothotho lwamanyathelo ukugqiba udibaniso lwakho lweNeon Gunyazisa.

Useto lokuqalisa lubonelela ngamanyathelo okuseta iprojekthi yoGunyaziso esisiseko noMabhalane.

 1. Set up Neon Extension and Roles Privileges. Run these steps in the Dashboard. 2. Grant privileges to the roles in the neondb database. 

Ukumisela uKhuseleko lweNqanaba loMqolo

Ikhowudi enikiweyo yeye app todos. Esikhundleni sokusebenzisa ikhowudi ye-boilerplate enikeziweyo evela kwi-Neon kwi-app ye-todos, siya kwenza i login_history table kwaye sisete i-RLS kuyo. Vula i-SQL Editor kwideshibhodi ye-Neon kwaye usebenzise ikhowudi engezantsi. Itheyibhile login_history iya kusetyenziswa ukugcina amaxesha okungena kumsebenzisi ngamnye.


Qaphela ukuba login_history inezintlu ezintathu nje: i-id, user_id, kunye ne-login_at. Imihlathi emibini yokugqibela iya kubonisa amagama angeniswayo akutsha nje kwisicelo.


 CREATE TABLE login_history ( id bigint generated by default as identity primary key, user_id text not null default (auth.user_id()), login_at timestamp not null default now() ); -- 1st enable row level security for your table ALTER TABLE login_history ENABLE ROW LEVEL SECURITY; -- 2nd create policies for your table CREATE POLICY "Individuals can add login." ON login_history FOR INSERT TO authenticated WITH CHECK ((select auth.user_id()) = user_id); CREATE POLICY "Individuals can view their own logins. " ON login_history FOR SELECT TO authenticated USING ((select auth.user_id()) = user_id);


Yongeza uguqulo olunikiweyo lokusingqongileyo kwi .env yakho



Nje ukuba la manyathelo okuseta egqityiwe, .env yakho kufuneka ibe nezinto ezine eziguquguqukayo: ezimbini zisuka kuMabhalane kwaye ezimbini zisuka kuNeon:

 CLERK_PUBLISHABLE_KEY=pk_test_.... CLERK_SECRET_KEY=sk_test_... # Database owner connection string DATABASE_URL='postgresql://neondb_owner:...' # Neon "authenticated" role connection string DATABASE_AUTHENTICATED_URL='postgresql://authenticated@ep-...


Ukwakha iRemix app

Isicelo ngoku sikulungele ukwakhiwa. Ikhowudi epheleleyo iyafumaneka kwiGitHub , kodwa ezona mpawu zibalulekileyo ziphawulwe apha. Undoqo wesicelo ukwi- app/routes/_index.tsx :


 export const loader: LoaderFunction = async (args) => { const { userId, getToken } = await getAuth(args); if (!userId) { return redirect("/sign-in"); } const authToken = await getToken(); console.log(userId); if (!authToken) { return null; } const DATABASE_AUTHENTICATED_URL= process.env.NEXT_PUBLIC_DATABASE_AUTHENTICATED_URL; try { const sql = neon(DATABASE_AUTHENTICATED_URL ?? '', { authToken, }); const loginResponse = await sql(`INSERT INTO login_history ("user_id") VALUES ($1) RETURNING *`,[userId]); // Retrieve last 10 logins const last10LoginsResponse = await sql(`SELECT * FROM login_history WHERE user_id = $1 ORDER BY login_at DESC LIMIT 10`, [userId]); console.log(`loginResponse: ${JSON.stringify(loginResponse)}`); return last10LoginsResponse as Array<LoginHistory>; } catch (error) { console.error(`Error inserting into login_history table: ${error.message}`); console.error(`Error details: ${JSON.stringify(error)}`); throw error; } }

I LoaderFunction kwi _index.tsx ifayile igqibezela imisebenzi kumncedisi phambi kokunikezela ngephepha kumxhasi. Kwesi sicelo, umlayishi wenza okuninzi ukuphakamisa okunzima kwe-app.


Umsebenzi kuqala ujonga ukuba umsebenzisi akalogwanga kwaye uphinde uqondise umsebenzisi kwi /sign-in . Iphepha lokungena lingacwangciswa kwideshibhodi kaMabhalane ukuze amkele iindidi zokungena ezahlukeneyo, ezinje ngoGoogle kunye nokungena kwe-imeyile:


Ukwenza iphepha lokungena, yiya kuMabhalane wedeshibhodi kwaye usete iindlela zokungena eziyimfuneko zeprojekthi.


Ukuba umsebenzisi ungene, umsebenzi ubuyisela i userId kunye authToken kuNobhala. La maxabiso abalulekile ukuqinisekisa ukuba umsebenzisi ungenile, kwaye ke ungasebenzisa i- userId ukugcwalisa umqolo ngamnye kwisiseko sedatha yakho.


Ukuze wenze utshintsho kwi-RLS-ekhuselweyo, kufuneka utsale i DATABASE_AUTHENTCATED_URL ukusuka kwizinto eziguquguqukayo zemekobume.

Ingcinga engundoqo yokuphumeza ukhuseleko lwe-RLS ingaphakathi kwi- LoaderFunction . Umzekelo we-SQL Neon uqaliswa kusetyenziswa izinto eziguquguqukayo zokusingqongileyo kunye nethokheni ye-auth. Umsebenzi loginResponse wenza umnxeba we-SQL kwaye ufake i-user_id (kunye nexesha langoku) kwisiseko sedatha ye-PostgreSQL, emva koko i last10LoginsResponse function ibuza i-DB ye-10 yokungena kwangoku.


Ekugqibeleni, i- last10LoginsResponse ibuyiswa kumsebenzi wokulayisha.


Index() umsebenzi kwifayile ye _index.tsx inika ubeko lwephepha njengoko kubonisiwe kwisiqwengana esingezantsi:


 export default function Index() { const logins = useLoaderData(); return ( <div> <h1>Signed in</h1> <p>You are signed in!</p> <p> <UserButton /></p> <div> <h1>Recent Logins</h1> {logins?.map((logins) => ( <li key={logins.id}> {logins.user_id} login at: {logins.login_at} </li> ))} </div> <p>< SignOutButton > Sign Out</ SignOutButton ></p> </div> ); }

Ikhowudi engentla ifumana impendulo kwi- LoaderFunction , equlethe i-10 yokugqibela yokungena. Le mpendulo yakha iphepha elixelela umsebenzisi ukuba bangenile, dwelisa amagama abo okugqibela ali-10, kwaye ibonisa iqhosha lokuPhuma njengoko kubonisiwe ngezantsi:

Yabuya impendulo


Kulo mzekelo, i user_id iyaboniswa ukubonisa ngokucacileyo ukuba kuphela idatha yokungena yomsebenzisi ongeneyo ebonakalayo.

Usebenzisa ifestile ye-incognito, ungangena ngeakhawunti yesibini kaGoogle, kwaye ujonge idatha yecala necala kubasebenzisi abohlukeneyo:



Qaphela ukuba amaxesha okungena ayadibana, kodwa ngokusebenzisa uKhuseleko lweNqanaba lokuLawulwa kwisiseko sedatha, uyakuthintela ukuvuza kwedatha kwii-akhawunti. Imiqolo inokutsalwa kuphela kwaye iboniswe kumsebenzisi oqinisekisiweyo.


Ukuqukumbela

Ukugcina idatha yabucala yinto ebalulekileyo yokusetyenziswa. Njengoko izicelo zihlala zigcina ulwazi lwabucala, kufuneka lukhuselwe ukugcina idatha kwizandla ezichanekileyo. Abathengi banokhuseleko oluthe kratya olusemthethweni olufana ne-GDPR, kwaye izixhobo ezifana ne-Neon Authorise zenza kube lula ukuphumeza uKhuseleko lweNqanaba loMqolo ukukhusela idatha yomthengi wakho.


Kule post, siye sahamba ngamanyathelo afunekayo ukwenza uKhuseleko lweNqanaba loMqolo kwi-database ye-Neon. Ukusebenzisa i-RLS ngedatha yomthengi wethu kuqinisekisa ukuba ngumsebenzisi ongene kuphela oneziqinisekiso zokukhupha idatha yakhe.


Yongeza uKhuseleko loMaleko kwi-app yakho namhlanje ngeNeon.