import{ensureMongoDocumentToObject as e}from"./utils/ensureMongoDocumentToObject.mjs";import{GenericError as t}from"./utils/errors/ErrorsClass.mjs";import{getOrganizationById as n}from"./services/organization.service.mjs";import{ProjectModel as r}from"./models/project.model.mjs";import{OAuth2AccessTokenModel as i}from"./models/oAuth2.model.mjs";import{getUserById as a}from"./services/user.service.mjs";import{mapUserToAPI as o}from"./utils/mapper/user.mjs";import{mapOrganizationToAPI as s}from"./utils/mapper/organization.mjs";import{mapProjectToAPI as c}from"./utils/mapper/project.mjs";import{randomBytes as l}from"node:crypto";const u=3600*2,d=()=>new Date(Date.now()+u*1e3),f={scope:void 0,addAcceptedScopesHeader:void 0,addAuthorizedScopesHeader:void 0,allowBearerTokensInQueryString:void 0},p=()=>({getClient:g,saveToken:y,getUserFromClient:x,verifyScope:S,getAccessToken:b}),m=()=>({clientId:l(16).toString(`hex`),clientSecret:l(32).toString(`hex`)}),h=async e=>{let t=await r.findOne({"oAuth2Access.clientId":e});if(!t)return!1;let n=t.oAuth2Access.find(t=>t.clientId===e);return n?{client:{id:n.clientId,clientId:e,clientSecret:n.clientSecret,grants:[`client_credentials`]},oAuth2Access:n,grants:n.grants,project:t}:!1},g=async(e,t)=>{let n=await h(e);if(!n)return!1;let{client:r}=n;return!r||r.clientSecret!==t?!1:r},_=(e,n,r,i,a,l)=>{let{clientId:u,userId:d,...f}=e;if(String(d)!==String(r.id))throw new t(`USER_ID_MISMATCH`);return{...f,client:n,user:o(r),organization:s(a),project:c(i),accessToken:e.accessToken,accessTokenExpiresAt:e.accessTokenExpiresAt??new Date(`999-99-99`),grants:l}},v=(e,t,n)=>({id:e.id,clientId:t,userId:n,accessToken:e.accessToken,expiresIn:e.accessTokenExpiresAt??d()}),y=async(e,t,r)=>{let a=v(e,t.id,r.id),o=await i.create(a);if(!o)return!1;let s=await h(o.clientId);if(!s)return!1;let{project:c}=s,l=await n(c.organizationId);return l?_(a,t,r,c,l,e.rights):!1},b=async e=>{let t=await i.findOne({accessToken:e});if(!t)return!1;let{userId:r,clientId:o}=t,s=await a(r);if(!s)return!1;let c=await h(o);if(!c)return!1;let{client:l,project:u,grants:d}=c,f=await n(u.organizationId);return f?_(t,l,s,u,f,d):!1},x=async e=>{let t=await h(e.id);if(!t)return!1;let{userId:n}=t.oAuth2Access;return n?await a(n)??!1:!1},S=async(e,t,n)=>!0,C=async n=>{try{let r=await i.findOne({accessToken:n});if(!r)throw new t(`INVALID_ACCESS_TOKEN`);if(new Date>new Date(r.expiresIn))throw new t(`EXPIRED_ACCESS_TOKEN`);return e(r)}catch{throw new t(`INVALID_ACCESS_TOKEN`)}},w=async e=>{let{userId:r,clientId:i}=e,l=await a(String(r)),u=await h(i);if(!u)throw new t(`INVALID_ACCESS_TOKEN`);let{project:d,grants:f}=u,p=await n(d.organizationId);return{accessToken:e.accessToken,user:l?o(l):void 0,project:d?c(d):void 0,organization:p?s(p):void 0,grants:f}};export{g as a,x as c,S as d,u as f,d as h,b as i,y as l,p as m,_ as n,h as o,f as p,m as r,w as s,v as t,C as u};
//# sourceMappingURL=oAuth2.service-4snhZ7Ht.mjs.map