@gvanleemputten/react-netlify-identity-gotrue
Version:
A pure React (hooks-based) API to Netlify Identity / GoTrue, fully implementing all auth workflows
1 lines • 6.29 kB
JavaScript
module.exports=function(e){var t={};function o(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,o),r.l=!0,r.exports}return o.m=e,o.c=t,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=1)}([function(e,t){e.exports=require("react")},function(e,t,o){"use strict";o.r(t),o.d(t,"default",(function(){return u})),o.d(t,"useIdentityContext",(function(){return l}));var n=o(0),r=o.n(n);const s=/(confirmation|invite|recovery|email_change|access)_token=([^&]+)/,a=/^#\/?/;const i=({url:e})=>{const[t,o]=Object(n.useState)(),[r,i]=Object(n.useState)(),[c,l]=Object(n.useState)(),[u,d]=Object(n.useState)(),[f,p]=Object(n.useState)(),[m,g]=Object(n.useState)(),[y,h]=Object(n.useState)(),b=Object(n.useMemo)(()=>e+"/.netlify/identity",[e]),w=Object(n.useCallback)(async(e,t)=>{if(!r)throw new Error("Cannot authorizedFetch while logged out");return fetch(e,{...t,headers:{...null==t?void 0:t.headers,Authorization:"Bearer "+r.access_token}})},[r]),O=Object(n.useCallback)(e=>{const t=new Date(1e3*JSON.parse(window.atob(e.access_token.split(".")[1])).exp);i({...e,expires_at:t})},[]),v=Object(n.useCallback)(async()=>{O(await fetch(b+"/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"grant_type=refresh_token&refresh_token="+r.refresh_token}).then(e=>e.json()))},[O,b,r]),j=Object(n.useCallback)(async()=>{console.log("Logging Out"),localStorage.removeItem("ni.goTrueToken"),localStorage.removeItem("ni.user"),i(),o(),m&&(clearTimeout(m),g())},[m]);Object(n.useEffect)(()=>{if(r){localStorage.setItem("ni.goTrueToken",JSON.stringify(r));const e=Math.max(new Date(r.expires_at).getTime()-(new Date).getTime()-24e4,0);console.log(`Refresh goTrueToken in ${(e/1e3).toFixed(0)} seconds`),g(setTimeout(v,e))}},[r,v]),Object(n.useEffect)(()=>{t&&localStorage.setItem("ni.user",JSON.stringify(t))},[t]),Object(n.useEffect)(()=>{const e=localStorage.getItem("ni.goTrueToken"),t=localStorage.getItem("ni.user");e&&t&&(i(JSON.parse(e)),o(JSON.parse(t)),p())},[]),Object(n.useEffect)(()=>{l(function(){var e,t;if(null===(e=document)||void 0===e||null===(t=e.location)||void 0===t||!t.hash)return null;const o=document.location.hash.replace(a,"");try{window&&window.history.pushState("",document.title,window.location.pathname+window.location.search)}catch(e){window.location.href.substr(0,window.location.href.indexOf("#"))}const n=o.match(s);if(n){const e={};return o.split("&").forEach(t=>{const[o,n]=t.split("=");e[o]=n}),e.type=n[1],e.token=n[2],e}return null}())},[]),Object(n.useEffect)(()=>{if("confirmation"!==(null==c?void 0:c.type)&&"recovery"!==(null==c?void 0:c.type)&&"invite"!==(null==c?void 0:c.type)||!r)if("access"===(null==c?void 0:c.type)){const e=c;l(),O(e)}else"confirmation"===(null==c?void 0:c.type)?(console.log("Confirming User"),fetch(b+"/verify",{method:"POST",body:JSON.stringify({token:c.token,type:"signup"})}).then(e=>e.json()).then(e=>{404===e.code?(console.log("Confirmation token attempted that's already been consumed; logging out"),l()):(l(),O(e))})):"recovery"===(null==c?void 0:c.type)&&(console.log("Recovering User"),fetch(b+"/verify",{method:"POST",body:JSON.stringify({token:c.token,type:"recovery"})}).then(e=>e.json()).then(e=>{404===e.code?(console.log("Recovery token attempted that's already been consumed; logging out"),l()):(l({type:"passwordRecovery"}),O(e))}));else j()},[b,O,l,r,j,c]);const S=async({email:e,password:t})=>{const o=await fetch(b+"/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=password&username=${encodeURIComponent(e)}&password=${encodeURIComponent(t)}`}).then(e=>e.json());if(null!=o&&o.error_description)throw new Error(o.error_description);O(o)},k=Object(n.useCallback)(async e=>{delete Object.assign(e,{data:e.user_metadata}).user_metadata;const t=await w(b+"/user",{method:"PUT",body:JSON.stringify(e)}).then(e=>e.json());if(null!=t&&t.msg)throw new Error(t.msg);o(t),h(!0)},[b,w,o,h]);Object(n.useEffect)(()=>{r&&t&&u&&(d(),k(u))},[r,t,u,k]),Object(n.useEffect)(()=>{c&&"email_change"===c.type&&t&&(console.log("Confirming Email Change"),d({email_change_token:c.token}),l())},[c,t,k]),Object(n.useEffect)(()=>{r&&!t&&w(b+"/user").then(e=>e.json()).then(e=>o(e))},[b,o,w,r,t]);Object(n.useEffect)(()=>{r&&y&&(clearTimeout(m),v(),h())},[r,y,v,m]);const T=Object(n.useMemo)(()=>(null==t?void 0:t.email)!==(null==t?void 0:t.new_email)&&(null==t?void 0:t.new_email),[t]);return{user:t,login:S,logout:j,update:k,signup:async e=>{delete Object.assign(e,{data:e.user_metadata}).user_metadata;const t=await fetch(b+"/signup",{method:"POST",body:JSON.stringify(e)}).then(e=>e.json());if(null!=t&&t.msg)throw new Error(t.msg);null!=t&&t.confirmed_at?await S(e):p(t)},urlToken:c,refreshUser:k,authorizedFetch:w,provisionalUser:f,pendingEmailUpdate:T,sendPasswordRecovery:async({email:e})=>fetch(b+"/recover",{method:"POST",body:JSON.stringify({email:e})}),completeUrlTokenTwoStep:async({password:e,...t})=>{if("passwordRecovery"===(null==c?void 0:c.type))console.log("Updating Password & Clearing URL Token"),d({password:e}),l();else if("invite"===(null==c?void 0:c.type)){console.log("Setting Up Invited User");const o=await fetch(b+"/verify",{method:"POST",body:JSON.stringify({token:c.token,type:"signup",password:e})}).then(e=>e.json());l(),O(o),d(t)}}}},c=Object(n.createContext)(),l=()=>Object(n.useContext)(c),u=({url:e,children:t})=>{if(!e)throw new Error("No Identity URL defined! Use format https://example.com - no trailing slash");const o=i({url:e});return r.a.createElement(c.Provider,{value:o},t)}}]);