UNPKG

authrix

Version:

Lightweight, flexible authentication library for Node.js and TypeScript.

1 lines 2.68 kB
import {a as a$1}from'./chunk-ML66D24Y.mjs';import {b as b$1}from'./chunk-2W6WDMNG.mjs';import {a}from'./chunk-ZNCUQ2DE.mjs';import g from'bcryptjs';import a$2 from'jsonwebtoken';async function m(e,r){let t=a.db;if(!t)throw new Error("Database not configured. Make sure initAuth() is called before using authentication functions.");if(!e||!e.trim())throw new Error("Email is required");if(!r||!r.trim())throw new Error("Password is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))throw new Error("Invalid email format");if(r.length<6)throw new Error("Password must be at least 6 characters long");if(await t.findUserByEmail(e))throw new Error("Email already registered");let s=await b$1(r,{skipValidation:true}),c=await t.createUser({email:e,password:s}),l=a$1({id:c.id,email:e});return {user:{id:c.id,email:e},token:l,cookieOptions:{httpOnly:true,secure:process.env.NODE_ENV==="production",maxAge:1e3*60*60*24*7,sameSite:"lax",path:"/"}}}async function b(e,r,t){let o=await m(e,r);return t.cookie(a.cookieName,o.token,o.cookieOptions),o.user}async function w(e,r){let t=a.db;if(!t)throw new Error("Database not configured. Make sure initAuth() is called before using authentication functions.");let o=await t.findUserByEmail(e);if(!o)throw new Error("Invalid email or password");if(!await g.compare(r,o.password))throw new Error("Invalid email or password");let s=a$1({id:o.id,email:e});return {user:{id:o.id,email:e},token:s,cookieOptions:{httpOnly:true,secure:process.env.NODE_ENV==="production",maxAge:1e3*60*60*24*7,sameSite:"lax",path:"/"}}}async function C(e,r,t){let o=await w(e,r);return t.cookie(a.cookieName,o.token,o.cookieOptions),o.user}function h(){return {cookieName:a.cookieName,cookieOptions:{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/",expires:new Date(0)},message:"Logged out successfully"}}function V(e){let r=h();return e.clearCookie&&e.clearCookie(r.cookieName,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/"}),{message:r.message}}function p(e){try{return a$2.verify(e,a.jwtSecret)}catch(r){throw r instanceof a$2.TokenExpiredError?new Error("Token expired"):r instanceof a$2.JsonWebTokenError?new Error("Invalid token"):new Error("Token verification failed")}}async function f(e){try{if(!e)return null;let r=p(e),t=a.db;if(!t)return null;let o=await t.findUserById(r.id);return o?{id:o.id,email:o.email,createdAt:o.createdAt}:null}catch{return null}}async function k(e){let r=e.cookies[a.cookieName];return f(r)}async function _(e){return await f(e)!==null}async function B(e){return await k(e)!==null}export{m as a,b,w as c,C as d,h as e,V as f,p as g,f as h,k as i,_ as j,B as k};