From 65e542a988c9a21c39896df5332fee6f0e099d97 Mon Sep 17 00:00:00 2001 From: Peter Phanouvong Date: Wed, 25 May 2022 15:12:08 +1000 Subject: [PATCH] error checking --- bundle.js | 2 +- src/handlers/callback.js | 1 - src/handlers/me.js | 7 ++++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/bundle.js b/bundle.js index d5f2bd4..eb6a125 100644 --- a/bundle.js +++ b/bundle.js @@ -1 +1 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("crypto-js");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=t(e);const a={user:null,isAuthenticated:!1,isLoading:!0,checkSession:null},o=()=>{throw new Error("Oops! Seems like you forgot to wrap your app in .")},n=e.createContext({...a,user:o,isLoading:o,isAuthenticated:o,checkSession:o});const c=new URL(`https://${process.env.KINDE_REDIRECT_URL}/api/auth/kinde_callback`),i=new URL(`https://${process.env.KINDE_DOMAIN}/logout`),d=new URL(`https://${process.env.KINDE_DOMAIN}/oauth2/token`),u=e=>{const r=new URL(`https://${process.env.KINDE_DOMAIN}/oauth2/auth`);return r.searchParams.append("response_type","code"),r.searchParams.append("client_id","reg@live"),r.searchParams.append("redirect_uri",c),r.searchParams.append("scope","openid offline"),e&&r.searchParams.append("start_page","registration"),r},h=u(),l=u(!0),p=require("crypto"),_=()=>p.randomBytes(28).toString("hex");function g(){const e=_(),t=function(e){return r.SHA256(e).toString(r.enc.Base64url)}(e);return{code_verifier:e,code_challenge:t}}var f=require("cookie");const y=(e,r,t)=>{const s=_(),{code_challenge:a,code_verifier:o}=g();return r.setHeader("Set-Cookie",f.serialize(`pkce-verifier-${s}`,o,{httpOnly:!0,maxAge:t})),{state:s,code_challenge:a}};var v=require("cookie");var k=require("cookie");var w=require("cookie");exports.AuthContext=n,exports.KindeProvider=({children:r,initialUser:t})=>{const[o,c]=e.useState({...a,user:t,isLoading:!t,isAuthenticated:!!t}),i="/api/auth/me",d=e.useCallback((async()=>{try{const e=await(async e=>{let r;try{r=await fetch(e)}catch{throw new RequestError(0)}if(r.ok)return r.json();r.status})(i);c((r=>({...r,user:e,error:void 0})))}catch(e){c((r=>({...r,error:e})))}}),[i]);e.useEffect((()=>{o.user||(async()=>{await d(),c((e=>({...e,isLoading:!1})))})()}),[o.user]);const{user:u,error:h,isLoading:l,isAuthenticated:p}=o;return s.default.createElement(n.Provider,{value:{user:u,error:h,isLoading:l,isAuthenticated:p}},r)},exports.handleAuth=()=>async function(e,r){let{query:{kindeAuth:t}}=e;switch(t=Array.isArray(t)?t[0]:t,t){case"login":return await(async(e,r)=>{const{state:t,code_challenge:s}=y(0,r,60);h.searchParams.set("state",t),h.searchParams.set("code_challenge",s),h.searchParams.set("code_challenge_method","S256"),r.redirect(h.href)})(0,r);case"register":return await(async(e,r)=>{const{state:t,code_challenge:s}=y(0,r,180);l.searchParams.set("state",t),l.searchParams.set("code_challenge",s),l.searchParams.set("code_challenge_method","S256"),r.redirect(l.href)})(0,r);case"me":return await(async(e,r)=>{const t=k.parse(e.headers.cookie||"").kinde_token,s=JSON.parse(t);if(t)try{const e=await fetch(`https://${process.env.KINDE_DOMAIN}/oauth2/user_profile`,{headers:new Headers({Authorization:"Bearer "+s.access_token})}),t=await e.json();r.send(t),console.log(t)}catch(e){console.log(e)}r.end()})(e,r);case"logout":return await(async(e,r)=>{r.setHeader("Set-Cookie",v.serialize("kinde_token",null,{httpOnly:!0,maxAge:0})),i.searchParams.set("redirect",process.env.KINDE_LOGOUT_URL?`https://${process.env.KINDE_LOGOUT_URL}`:`https://${process.env.KINDE_REDIRECT_URL}`),r.redirect(i.href)})(0,r);case"kinde_callback":return await(async(e,r)=>{const{code:t,state:s}=e.query,a=w.parse(e.headers.cookie||"")[`pkce-verifier-${s}`];if(a){try{const e=await fetch(d,{method:"POST",headers:new Headers({"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"}),body:new URLSearchParams({client_id:process.env.CLIENT_ID,client_secret:process.env.CLIENT_SECRET,code:t,code_verifier:a,grant_type:"authorization_code",redirect_uri:c})}),s=await e.json();console.log(s),r.setHeader("Set-Cookie",w.serialize("kinde_token",JSON.stringify(s),{httpOnly:!0,maxAge:Number(s.expires_in)}))}catch(e){console.log(e)}r.redirect(`https://${process.env.KINDE_REDIRECT_URL}`)}else r.redirect(`https://${process.env.KINDE_REDIRECT_URL}`)})(e,r);default:return r.status(404).end()}},exports.useAuth=()=>e.useContext(n); +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("crypto-js");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=r(e);const a={user:null,isAuthenticated:!1,isLoading:!0,checkSession:null},n=()=>{throw new Error("Oops! Seems like you forgot to wrap your app in .")},o=e.createContext({...a,user:n,isLoading:n,isAuthenticated:n,checkSession:n});const c=new URL(`https://${process.env.KINDE_REDIRECT_URL}/api/auth/kinde_callback`),i=new URL(`https://${process.env.KINDE_DOMAIN}/logout`),d=new URL(`https://${process.env.KINDE_DOMAIN}/oauth2/token`),u=e=>{const t=new URL(`https://${process.env.KINDE_DOMAIN}/oauth2/auth`);return t.searchParams.append("response_type","code"),t.searchParams.append("client_id","reg@live"),t.searchParams.append("redirect_uri",c),t.searchParams.append("scope","openid offline"),e&&t.searchParams.append("start_page","registration"),t},h=u(),l=u(!0),p=require("crypto"),_=()=>p.randomBytes(28).toString("hex");function f(){const e=_(),r=function(e){return t.SHA256(e).toString(t.enc.Base64url)}(e);return{code_verifier:e,code_challenge:r}}var g=require("cookie");const y=(e,t,r)=>{const s=_(),{code_challenge:a,code_verifier:n}=f();return t.setHeader("Set-Cookie",g.serialize(`pkce-verifier-${s}`,n,{httpOnly:!0,maxAge:r})),{state:s,code_challenge:a}};var v=require("cookie");var k=require("cookie");var w=require("cookie");exports.AuthContext=o,exports.KindeProvider=({children:t,initialUser:r})=>{const[n,c]=e.useState({...a,user:r,isLoading:!r,isAuthenticated:!!r}),i="/api/auth/me",d=e.useCallback((async()=>{try{const e=await(async e=>{let t;try{t=await fetch(e)}catch{throw new RequestError(0)}if(t.ok)return t.json();t.status})(i);c((t=>({...t,user:e,error:void 0})))}catch(e){c((t=>({...t,error:e})))}}),[i]);e.useEffect((()=>{n.user||(async()=>{await d(),c((e=>({...e,isLoading:!1})))})()}),[n.user]);const{user:u,error:h,isLoading:l,isAuthenticated:p}=n;return s.default.createElement(o.Provider,{value:{user:u,error:h,isLoading:l,isAuthenticated:p}},t)},exports.handleAuth=()=>async function(e,t){let{query:{kindeAuth:r}}=e;switch(r=Array.isArray(r)?r[0]:r,r){case"login":return await(async(e,t)=>{const{state:r,code_challenge:s}=y(0,t,60);h.searchParams.set("state",r),h.searchParams.set("code_challenge",s),h.searchParams.set("code_challenge_method","S256"),t.redirect(h.href)})(0,t);case"register":return await(async(e,t)=>{const{state:r,code_challenge:s}=y(0,t,180);l.searchParams.set("state",r),l.searchParams.set("code_challenge",s),l.searchParams.set("code_challenge_method","S256"),t.redirect(l.href)})(0,t);case"me":return await(async(e,t)=>{const r=k.parse(e.headers.cookie||"").kinde_token;if(r){const e=JSON.parse(r);try{const r=await fetch(`https://${process.env.KINDE_DOMAIN}/oauth2/user_profile`,{headers:new Headers({Authorization:"Bearer "+e.access_token})}),s=await r.json();t.send(s)}catch(e){console.log(e)}}else t.status(401).send("Unauthorized")})(e,t);case"logout":return await(async(e,t)=>{t.setHeader("Set-Cookie",v.serialize("kinde_token",null,{httpOnly:!0,maxAge:0})),i.searchParams.set("redirect",process.env.KINDE_LOGOUT_URL?`https://${process.env.KINDE_LOGOUT_URL}`:`https://${process.env.KINDE_REDIRECT_URL}`),t.redirect(i.href)})(0,t);case"kinde_callback":return await(async(e,t)=>{const{code:r,state:s}=e.query,a=w.parse(e.headers.cookie||"")[`pkce-verifier-${s}`];if(a){try{const e=await fetch(d,{method:"POST",headers:new Headers({"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"}),body:new URLSearchParams({client_id:process.env.CLIENT_ID,client_secret:process.env.CLIENT_SECRET,code:r,code_verifier:a,grant_type:"authorization_code",redirect_uri:c})}),s=await e.json();t.setHeader("Set-Cookie",w.serialize("kinde_token",JSON.stringify(s),{httpOnly:!0,maxAge:Number(s.expires_in)}))}catch(e){console.log(e)}t.redirect(`https://${process.env.KINDE_REDIRECT_URL}`)}else t.redirect(`https://${process.env.KINDE_REDIRECT_URL}`)})(e,t);default:return t.status(404).end()}},exports.useAuth=()=>e.useContext(o); diff --git a/src/handlers/callback.js b/src/handlers/callback.js index 71a6aa1..18dfb14 100644 --- a/src/handlers/callback.js +++ b/src/handlers/callback.js @@ -28,7 +28,6 @@ export const callback = async (req, res) => { const data = await response.json(); // check token claims - console.log(data); // save token res.setHeader( "Set-Cookie", diff --git a/src/handlers/me.js b/src/handlers/me.js index c7ce8d4..412ab7e 100644 --- a/src/handlers/me.js +++ b/src/handlers/me.js @@ -2,8 +2,9 @@ var cookie = require("cookie"); export const me = async (req, res) => { const kinde_token = cookie.parse(req.headers.cookie || "")["kinde_token"]; - const token = JSON.parse(kinde_token); + if (kinde_token) { + const token = JSON.parse(kinde_token); try { const response = await fetch( `https://${process.env.KINDE_DOMAIN}/oauth2/user_profile`, @@ -15,10 +16,10 @@ export const me = async (req, res) => { ); const data = await response.json(); res.send(data); - console.log(data); } catch (err) { console.log(err); } + } else { + res.status(401).send("Unauthorized"); } - res.end(); };