import{ensureMongoDocumentToObject as e}from"../utils/ensureMongoDocumentToObject.mjs";import{GenericError as t}from"../utils/errors/ErrorsClass.mjs";import{getOrganizationById as n}from"./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"./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{getTokenExpireAt as l}from"../utils/oAuth2.mjs";import{randomBytes as u}from"node:crypto";const d=()=>({clientId:u(16).toString(`hex`),clientSecret:u(32).toString(`hex`)}),f=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},p=async(e,t)=>{let n=await f(e);if(!n)return!1;let{client:r}=n;return!r||r.clientSecret!==t?!1:r},m=(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}},h=(e,t,n)=>({id:e.id,clientId:t,userId:n,accessToken:e.accessToken,expiresIn:e.accessTokenExpiresAt??l()}),g=async(e,t,r)=>{let a=h(e,t.id,r.id),o=await i.create(a);if(!o)return!1;let s=await f(o.clientId);if(!s)return!1;let{project:c}=s,l=await n(c.organizationId);return l?m(a,t,r,c,l,e.rights):!1},_=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 f(o);if(!c)return!1;let{client:l,project:u,grants:d}=c,p=await n(u.organizationId);return p?m(t,l,s,u,p,d):!1},v=async e=>{let t=await f(e.id);if(!t)return!1;let{userId:n}=t.oAuth2Access;return n?await a(n)??!1:!1},y=async(e,t,n)=>!0,b=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`)}},x=async e=>{let{userId:r,clientId:i}=e,l=await a(String(r)),u=await f(i);if(!u)throw new t(`INVALID_ACCESS_TOKEN`);let{project:d,grants:p}=u,m=await n(d.organizationId);return{accessToken:e.accessToken,user:l?o(l):void 0,project:d?c(d):void 0,organization:m?s(m):void 0,grants:p}};export{h as formatDBToken,m as formatOAuth2Token,d as generateClientCredentials,_ as getAccessToken,p as getClient,f as getClientAndProjectByClientId,x as getOAuth2AccessTokenContext,v as getUserFromClient,g as saveToken,b as validateOAuth2AccessToken,y as verifyScope};
//# sourceMappingURL=oAuth2.service.mjs.map