UNPKG

better-auth-harmony

Version:

Validation and normalization for better-auth

1 lines 2.78 kB
import {APIError}from'better-auth/api';import {createAuthMiddleware}from'better-auth/plugins';import x from'mailchecker';import E from'validator/es/lib/isEmail.js';import w from'validator/es/lib/normalizeEmail.js';import {parsePhoneNumberWithError,ParseError}from'libphonenumber-js/max';var p=["/sign-up/email","/email-otp/verify-email","/sign-in/email-otp","/sign-in/magic-link","/sign-in/email","/forget-password/email-otp","/email-otp/reset-password","/email-otp/create-verification-otp","/email-otp/get-verification-otp","/email-otp/send-verification-otp","/forget-password","/send-verification-email","/change-email"],y=new Set(p),g=new Set(p.slice(1,12)),c=({path:t})=>y.has(t),h=({path:t})=>g.has(t);var M=t=>E(t)&&x.isValid(t),u=t=>({email:t.body?.email??t.query?.email,container:t.body?"body":"query"}),P=({allowNormalizedSignin:t=false,validator:m=M,matchers:a={},normalizer:s=w}={})=>({id:"harmony-email",init(){let e=async o=>{let{email:r,phoneNumber:n}=o;if(!r||n)return {data:o};let i=s(r);return i?{data:{...o,normalizedEmail:i}}:false};return {options:{databaseHooks:{user:{create:{before:e},update:{before:e}}}}}},schema:{user:{fields:{normalizedEmail:{type:"string",required:false,unique:true,input:false,returned:false}}}},hooks:{before:[{matcher:e=>a.validation?a.validation.some(o=>o(e)):c(e),handler:createAuthMiddleware(async e=>{let o=e.path==="/change-email"?e.body?.newEmail:u(e).email;if(typeof o!="string")return;if(!await m(o))throw new APIError("BAD_REQUEST",{message:"Invalid email"})})},{matcher:e=>t&&(a.signIn?a.signIn.some(o=>o(e)):h(e)),handler:createAuthMiddleware(async e=>{let{email:o,container:r}=u(e);if(typeof o!="string")return;let n=s(o);if(n!==o){let i=await e.context.adapter.findOne({model:"user",where:[{field:"normalizedEmail",value:n}]});return i?r==="query"?{context:{...e,query:{...e.query,email:i.email,normalizedEmail:n}}}:{context:{...e,body:{...e.body,email:i.email,normalizedEmail:n}}}:void 0}})}]}}),C=P;var v=new Set(["/sign-in/phone-number","/phone-number/forget-password","/phone-number/reset-password","/phone-number/send-otp","/phone-number/verify"]),f=({path:t})=>v.has(t);var H=({defaultCountry:t,defaultCallingCode:m,extract:a=true,acceptRawInputOnError:s=false,matchers:e=[f],normalizer:o=r=>parsePhoneNumberWithError(r,{defaultCountry:t,defaultCallingCode:m,extract:a}).number}={})=>({id:"harmony-phone-number",hooks:{before:[{matcher:r=>e.some(n=>n(r)),handler:createAuthMiddleware(async r=>{let{phoneNumber:n}=r.body;if(typeof n!="string")return;let i=n;try{i=await o(n,r.request);}catch(l){if(!s&&l instanceof ParseError)throw new APIError("BAD_REQUEST",{message:l.message});if(s)i=n;else throw l}return {context:{...r,body:{...r.body,phoneNumber:i}}}})}]}}),O=H;export{C as emailHarmony,O as phoneHarmony};