@andrewcaires/api 4.0.3 → 4.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +69 -68
- package/dist/index.esm.js +2 -2
- package/package.json +13 -11
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.0.
|
|
2
|
+
* @andrewcaires/api v4.0.4
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/node"),r=require("@andrewcaires/utils.js"),o=require("ws"),s=require("@andrewcaires/sequelize"),i=require("dotenv"),n=require("fs"),d=require("express-session"),a=require("sequelize"),p=require("jsonwebtoken"),u=require("path");function l(e,t,r,o){var s,i=arguments.length,n=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(s=e[d])&&(n=(i<3?s(n):i>3?s(t,r,n):s(t,r))||n);return i>3&&n&&Object.defineProperty(t,r,n),n}function c(e,t){return function(r,o){t(r,o,e)}}function g(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))((function(s,i){function n(e){try{a(o.next(e))}catch(e){i(e)}}function d(e){try{a(o.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,i.config();class x{static getBool(e,t){return r.toBool(x.getString(e,t.toString()))}static getInt(e,t){return parseInt(x.getString(e,t.toString()))}static getMs(e,t){return r.parseMs(x.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}x.API_CONSOLE_ERROR=x.getBool("API_CONSOLE_ERROR",!1),x.API_DEFAULT_PATH=x.getString("API_DEFAULT_PATH","/api"),x.API_DB_DATABASE=x.getString("API_DB_DATABASE",""),x.API_DB_HOST=x.getString("API_DB_HOST","127.0.0.1"),x.API_DB_PASSWORD=x.getString("API_DB_PASSWORD",""),x.API_DB_PORT=x.getInt("API_DB_PORT",3306),x.API_DB_TYPE=x.getString("API_DB_TYPE",""),x.API_DB_USERNAME=x.getString("API_DB_USERNAME","root"),x.API_DB_LOG=x.getBool("API_DB_LOG",!1),x.API_DB_AUDIT=x.getBool("API_DB_AUDIT",!0),x.API_DB_PREFIX=x.getString("API_DB_PREFIX",""),x.API_DB_TIMEZONE=x.getString("API_DB_TIMEZONE","+00:00"),x.API_HTTP_CRT=x.getString("API_HTTP_CRT",""),x.API_HTTP_KEY=x.getString("API_HTTP_KEY",""),x.API_HTTP_PORT=x.getInt("API_HTTP_PORT",3e3),x.API_HTTP_PUBLIC=x.getString("API_HTTP_PUBLIC",""),x.API_HTTP_CROSS=x.getBool("API_HTTP_CROSS",!1),x.API_HTTP_HYBRID=x.getBool("API_HTTP_HYBRID",!1),x.API_HTTP_REDIRECT=x.getString("API_HTTP_REDIRECT",""),x.API_KEY_HASH=x.getString("API_KEY_HASH",""),x.API_KEY_HEADER=x.getString("API_KEY_HEADER","api_key"),x.API_MODEL_LIMIT=x.getInt("API_MODEL_LIMIT",10),x.API_MODEL_LIMIT_MAX=x.getInt("API_MODEL_LIMIT_MAX",500),x.API_NOTFOUND_REDIRECT=x.getString("API_NOTFOUND_REDIRECT",""),x.API_SLEEP_AUTH=x.getMs("API_SLEEP_AUTH","2s"),x.API_SLEEP_FORGOT=x.getMs("API_SLEEP_FORGOT","5s"),x.API_SLEEP_REGISTRY=x.getMs("API_SLEEP_REGISTRY","5s"),x.API_SESSION_NAME=x.getString("API_SESSION_NAME","session.id"),x.API_SESSION_LIFETIME=x.getMs("API_SESSION_LIFETIME","1d"),x.API_SESSION_SECRET=x.getString("API_SESSION_SECRET","yoursecret"),x.API_TOKEN_CRT=x.getString("API_TOKEN_CRT",""),x.API_TOKEN_KEY=x.getString("API_TOKEN_KEY",""),x.API_TOKEN_FORGOT=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_HEADER=x.getString("API_TOKEN_HEADER","authorization"),x.API_TOKEN_LIFETIME=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_RENEW=x.getMs("API_TOKEN_RENEW","1d"),x.API_UPLOAD_COUNT=x.getInt("API_UPLOAD_COUNT",1),x.API_UPLOAD_FIELD=x.getString("API_UPLOAD_FIELD","upload"),x.API_UPLOAD_SIZE=x.getInt("API_UPLOAD_SIZE",2),x.API_UPLOAD_TEMP=x.getString("API_UPLOAD_TEMP","./temp"),x.API_WEBSOCKET_START=x.getBool("API_WEBSOCKET_START",!1);const h=new s.Connection({type:x.API_DB_TYPE,database:x.API_DB_DATABASE,username:x.API_DB_USERNAME,password:x.API_DB_PASSWORD,hostname:x.API_DB_HOST,hostport:x.API_DB_PORT,logging:x.API_DB_LOG,prefix:x.API_DB_PREFIX});class v extends s.Model{}const _={afterCreate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;if(!x.API_DB_AUDIT)return;const n=r.isObject(e)?e.constructor:null,d=null!==(o=null==n?void 0:n.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create({type:"CREATE",model:null!==(s=null==n?void 0:n.getTableName())&&void 0!==s?s:null,record:d?e.getDataValue(d):null,data:JSON.stringify(e.toJSON()),state:!0,user_id:null!==(i=null==t?void 0:t.user_id)&&void 0!==i?i:null}).catch(r.noop)})),afterUpdate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;if(!x.API_DB_AUDIT)return;const n=r.isObject(e)?e.constructor:null,d=null!==(o=null==n?void 0:n.primaryKeyAttribute)&&void 0!==o?o:null,a={},p=e.changed();p&&p.forEach((t=>a[t]=e.getDataValue(t))),yield exports.Audit.create({type:"UPDATE",model:null!==(s=null==n?void 0:n.getTableName())&&void 0!==s?s:null,record:d?e.getDataValue(d):null,data:JSON.stringify({before:e.previous(),after:a}),state:!0,user_id:null!==(i=null==t?void 0:t.user_id)&&void 0!==i?i:null}).catch(r.noop)})),afterDestroy:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;if(!x.API_DB_AUDIT)return;const n=r.isObject(e)?e.constructor:null,d=null!==(o=null==n?void 0:n.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create({type:"DELETE",model:null!==(s=null==n?void 0:n.getTableName())&&void 0!==s?s:null,record:d?e.getDataValue(d):null,data:JSON.stringify(e.toJSON()),state:!0,user_id:null!==(i=null==t?void 0:t.user_id)&&void 0!==i?i:null}).catch(r.noop)}))};exports.Auth=class extends v{},l([s.Id(),g("design:type",Number)],exports.Auth.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Auth.prototype,"secret",void 0),l([s.FullDate(),g("design:type",Date)],exports.Auth.prototype,"logout",void 0),l([s.String(),g("design:type",s.String)],exports.Auth.prototype,"useragent",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Auth.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Auth.prototype,"deleted_at",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=l([s.Database(h),s.ModelName("auth")],exports.Auth),exports.Register=class extends v{},l([s.Id(),g("design:type",Number)],exports.Register.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Register.prototype,"token",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.Register.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Register.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Register.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Register.prototype,"deleted_at",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=l([s.Database(h),s.ModelName("register")],exports.Register),exports.Group=class extends v{},l([s.Id(),g("design:type",Number)],exports.Group.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Group.prototype,"name",void 0),l([s.Text(),g("design:type",s.String)],exports.Group.prototype,"description",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.Group.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Group.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Group.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Group.prototype,"deleted_at",void 0),l([s.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),l([s.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=l([s.Database(h),s.ModelName("group"),s.Hooks(_)],exports.Group),exports.UserGroup=class extends v{},l([s.CreatedAt,g("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),l([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=l([s.Database(h),s.ModelName("users_groups"),s.Hooks(_)],exports.UserGroup),exports.User=class extends v{},l([s.Id(),g("design:type",Number)],exports.User.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"name",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"email",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"username",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"password",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"salt",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"token",void 0),l([s.String(),g("design:type",s.String)],exports.User.prototype,"avatar",void 0),l([s.DateOnly(),g("design:type",s.String)],exports.User.prototype,"date",void 0),l([s.Text(),g("design:type",s.String)],exports.User.prototype,"description",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.User.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.User.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.User.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.User.prototype,"deleted_at",void 0),l([s.HasMany((()=>exports.Audit),"user_id"),g("design:type",Array)],exports.User.prototype,"audits",void 0),l([s.HasMany((()=>exports.Auth),"user_id"),g("design:type",Array)],exports.User.prototype,"auths",void 0),l([s.HasMany((()=>exports.Register),"user_id"),g("design:type",Array)],exports.User.prototype,"registers",void 0),l([s.HasMany((()=>exports.UserGroup),"user_id"),g("design:type",Array)],exports.User.prototype,"users_groups",void 0),exports.User=l([s.Database(h),s.ModelName("user"),s.DefaultScope({attributes:{exclude:["password","salt","token"]}}),s.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),s.Hooks(_)],exports.User),exports.Audit=class extends v{},l([s.Id(),g("design:type",Number)],exports.Audit.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Audit.prototype,"type",void 0),l([s.String(),g("design:type",s.String)],exports.Audit.prototype,"model",void 0),l([s.Integer(),g("design:type",s.String)],exports.Audit.prototype,"record",void 0),l([s.Text(),g("design:type",s.String)],exports.Audit.prototype,"data",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.Audit.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Audit.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Audit.prototype,"deleted_at",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=l([s.Database(h),s.ModelName("audit")],exports.Audit),exports.Configs=class extends v{},l([s.String(),g("design:type",s.String)],exports.Configs.prototype,"key",void 0),l([s.String(),g("design:type",s.String)],exports.Configs.prototype,"value",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Configs.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Configs.prototype,"updated_at",void 0),exports.Configs=l([s.Database(h),s.ModelName("configs"),s.Hooks(_)],exports.Configs),exports.Forgot=class extends v{},l([s.Id(),g("design:type",Number)],exports.Forgot.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Forgot.prototype,"token",void 0),l([s.BigInt(),g("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.Forgot.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Forgot.prototype,"deleted_at",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=l([s.Database(h),s.ModelName("forgot")],exports.Forgot),exports.Route=class extends v{},l([s.Id(),g("design:type",Number)],exports.Route.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Route.prototype,"name",void 0),l([s.Text(),g("design:type",s.String)],exports.Route.prototype,"description",void 0),l([s.Boolean(),g("design:type",s.Boolean)],exports.Route.prototype,"state",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Route.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Route.prototype,"updated_at",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Route.prototype,"deleted_at",void 0),l([s.HasMany((()=>exports.GroupRoute),"route_id"),g("design:type",Array)],exports.Route.prototype,"groups_routes",void 0),exports.Route=l([s.Database(h),s.ModelName("route"),s.Hooks(_)],exports.Route),exports.GroupRoute=class extends v{},l([s.CreatedAt,g("design:type",Date)],exports.GroupRoute.prototype,"created_at",void 0),l([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.GroupRoute.prototype,"group_id",void 0),l([s.BelongsTo((()=>exports.Route)),g("design:type",Number)],exports.GroupRoute.prototype,"route_id",void 0),exports.GroupRoute=l([s.Database(h),s.ModelName("groups_routes"),s.Hooks(_)],exports.GroupRoute),exports.Log=class extends v{},l([s.Id(),g("design:type",Number)],exports.Log.prototype,"id",void 0),l([s.String(),g("design:type",s.String)],exports.Log.prototype,"type",void 0),l([s.String(),g("design:type",s.String)],exports.Log.prototype,"source",void 0),l([s.Text(),g("design:type",s.String)],exports.Log.prototype,"message",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=l([s.Database(h),s.ModelName("log")],exports.Log),exports.Session=class extends v{},l([s.String(),g("design:type",s.String)],exports.Session.prototype,"session",void 0),l([s.Text(),g("design:type",s.String)],exports.Session.prototype,"json",void 0),l([s.BigInt(),g("design:type",Number)],exports.Session.prototype,"expired",void 0),l([s.CreatedAt,g("design:type",Date)],exports.Session.prototype,"created_at",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=l([s.Database(h),s.ModelName("session")],exports.Session);class m{static write(e,r,o){return y(this,void 0,void 0,(function*(){yield m.writeRaw(t.LogColor.White,"",e,r,o)}))}static error(e,r,o){return y(this,void 0,void 0,(function*(){yield m.writeRaw(t.LogColor.Red,"error",e,r,o)}))}static info(e,r,o){return y(this,void 0,void 0,(function*(){yield m.writeRaw(t.LogColor.Cyan,"info",e,r,o)}))}static success(e,r,o){return y(this,void 0,void 0,(function*(){yield m.writeRaw(t.LogColor.Green,"success",e,r,o)}))}static warning(e,r,o){return y(this,void 0,void 0,(function*(){yield m.writeRaw(t.LogColor.Yellow,"warning",e,r,o)}))}static writeRaw(e,r,o,s,i){return y(this,void 0,void 0,(function*(){i&&t.Log.console(e,r,o),h&&(yield exports.Log.create({type:r,source:s,message:o}).catch((()=>null)))}))}}const f=e=>n.existsSync(e)?n.readFileSync(e):void 0,A={http:f(x.API_HTTP_CRT),token:f(x.API_TOKEN_CRT)},C={http:f(x.API_HTTP_KEY),token:f(x.API_TOKEN_KEY)};class S extends d.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,(function*(){e=e||r.noop;const t=yield exports.Session.findAll({attributes:["session"],where:{expired:{[a.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy().catch(r.noop),e&&e()})),this.destroy=(e,t)=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{session:e}}).catch(r.noop),t&&t()})),this.expired=()=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{expired:{[a.Op.lt]:Date.now()}}}).catch(r.noop)})),this.get=(e,t)=>y(this,void 0,void 0,(function*(){t=t||r.noop;const o=yield exports.Session.findOne({where:{session:e,expired:{[a.Op.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(o){const e=JSON.parse(o.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(r.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>y(this,void 0,void 0,(function*(){e&&e(null,(yield exports.Session.count().catch(r.noop))||0)})),this.set=(e,t,o)=>y(this,void 0,void 0,(function*(){o=o||r.noop;const s=Date.now()+x.API_SESSION_LIFETIME,i=JSON.stringify(t),[n,d]=(yield exports.Session.findOrCreate({where:{session:e},defaults:{session:e,json:i,expired:s}}).catch(r.noop))||[];n&&(d||(n.json=i,n.expired=s,yield n.save().catch(r.noop))),o()})),this.loop=r.loop(this.expired,3e4),this.loop.start()}}class P{static create(e){return y(this,void 0,void 0,(function*(){if(!C.token)return{error:"Key not found"};const{id:t}=e,o=r.uuidv4(),s=yield exports.Auth.create({secret:o,user_id:t}).catch(P.error);if(!s)return{error:"Internal Server Error"};return{auth:s,token:p.sign({id:t,secret:o},C.token,P.options())}}))}static destroy(e){return y(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){m.error(e.message,"api.token",x.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:x.API_TOKEN_LIFETIME+"ms"}}static renew(e){return y(this,void 0,void 0,(function*(){if(!C.token)return{error:"Key not found"};const{error:t,decode:o}=P.verify(e,x.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(o){const{id:e,secret:t}=o;if(e&&t){const o=yield exports.User.findOne({where:{id:e,state:!0}}).catch(P.error);if(o){const s=yield exports.Auth.findOne({where:{secret:t,user_id:o.id}}).catch(P.error);if(s&&!s.logout){s.secret=r.uuidv4(),yield s.save().catch(P.error);return{auth:s,token:p.sign({id:e,secret:s.secret},C.token,P.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return y(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const o=yield exports.User.findOne({where:{token:t,state:!0}}).catch(P.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(P.error))||[];if(r)return{auth:r,user:o}}return{error:"Access denied"}}const{error:o,decode:s}=P.verify(t);if(o)return{error:o};if(s){const{id:e,secret:t}=s;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(P.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(P.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!A.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:p.verify(e,A.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class I extends e.Application{constructor(e){super(e,{cert:A.http,cross:x.API_HTTP_CROSS,hybrid:x.API_HTTP_HYBRID,key:C.http,notfound:x.API_NOTFOUND_REDIRECT,path:x.API_DEFAULT_PATH,port:x.API_HTTP_PORT,public:x.API_HTTP_PUBLIC,redirect:x.API_HTTP_REDIRECT,session:{store:new S,name:x.API_SESSION_NAME,secret:x.API_SESSION_SECRET,cookie:{maxAge:x.API_SESSION_LIFETIME},genid:r.uuidv4}}),this.hash=new t.Hash(x.API_KEY_HASH)}error(e,t){m.error(e.message,t,x.API_CONSOLE_ERROR)}log(e,t){m.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,(function*(){yield h.sync(),yield e.listen.call(this),x.API_WEBSOCKET_START&&this.server&&(this._webSocket=new o.Server({server:this.server,verifyClient:(e,t)=>t(x.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>y(this,void 0,void 0,(function*(){t.url||(t.url="");const o=t.url.length<=1?"":t.url.replace(/\//g,".");let s;e.on("message",(r=>y(this,void 0,void 0,(function*(){if(s)try{const i=JSON.parse(r);this.emit("ws.message"+o,{data:i,message:r,req:t,user:s,ws:e})}catch(i){this.emit("ws.message"+o,{message:r,req:t,user:s,ws:e})}else{const{user:i}=yield P.user("",r.toString(),this);i&&(s=i,this.emit("ws.connection"+o,{req:t,user:s,ws:e}))}s||e.close()})))),e.on("close",(()=>{s&&this.emit("ws.close"+o,{user:s,ws:e})})),yield r.sleep(2e3),s||e.close()})))))}))}websocket(){return this._webSocket}}class O{static all(){return y(this,void 0,void 0,(function*(){const e=yield exports.Configs.findAll().catch(O.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return y(this,void 0,void 0,(function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield exports.Configs.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(O.error))||0)>0}))}static error(e){m.error(e.message,"api.config",x.API_CONSOLE_ERROR)}static get(e){return y(this,arguments,void 0,(function*(e,t=""){const[r]=(yield exports.Configs.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(O.error))||[];return r?r.value:t}))}static set(e,t,r){return y(this,void 0,void 0,(function*(){var o;const s=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[i]=(yield exports.Configs.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(O.error))||[];i&&(i.value=t,yield i.save().catch(O.error))}))}}const w=e.parameterFactory((({ctx:e})=>{var t,r,o;return{user_id:null!==(o=null===(r=null===(t=e.req)||void 0===t?void 0:t.user)||void 0===r?void 0:r.id)&&void 0!==o?o:null}})),E=e.parameterFactory((({ctx:e})=>e.req.auth)),R=e.parameterFactory((({ctx:e})=>e.req.user));class T{static all(e,t){return y(this,void 0,void 0,(function*(){return yield exports.Route.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:exports.GroupRoute,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch((e=>{m.error(e.message,"api.permission",x.API_CONSOLE_ERROR)}))}))}static get(e){return y(this,void 0,void 0,(function*(){const t=yield T.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return y(this,void 0,void 0,(function*(){const r=yield T.all(e,{name:t});return!!r&&r.length>0}))}}class D extends r.EventEmitter{auth(e,t,r,o,s){return y(this,void 0,void 0,(function*(){const{auth:i,error:n,user:d}=yield P.user(t,r,s);return n?e.error(n):i&&d?i.useragent&&i.useragent!=o?e.error("Invalid token"):(e.req.auth=i,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,o){return y(this,void 0,void 0,(function*(){o.auth&&o.user&&(o.useragent?o.useragent!=t&&o.regenerate(r.noop):(o.useragent=t,o.save(r.noop))),e.next()}))}error(e){m.error(e.message,"api.controller",x.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,(function*(){return r?(yield T.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(t,r){r.path||(r.path=x.API_UPLOAD_TEMP),r.size||(r.size=x.API_UPLOAD_SIZE),r.field||(r.field=x.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}validation(e,t){return y(this,void 0,void 0,(function*(){const{error:o,value:s}=yield r.Validation.object(t).parse().validateAsync(e.req.body);if(o)return e.validation(o);e.req.body=s,e.next()}))}write(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}l([c(0,e.Ctx()),c(1,e.Headers(x.API_KEY_HEADER)),c(2,e.Headers(x.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,I]),g("design:returntype",Promise)],D.prototype,"auth",null),l([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],D.prototype,"session",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],D.prototype,"permission",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],D.prototype,"read",null),l([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",void 0)],D.prototype,"upload",null),l([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],D.prototype,"validation",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],D.prototype,"write",null),exports.ModelController=class extends D{constructor(){super(...arguments),this._columns=[]}_add(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,body:o,user:s}){var i;const n=null!==(i=null==s?void 0:s.id)&&void 0!==i?i:null,d=yield this.model().create(Object.assign(Object.assign({},t.req.body),o||{}),Object.assign(Object.assign({},r||{}),{user_id:n})).catch(this.error);if(d){const r=this.key();return t.prepare(e.Status.OK,{[r]:d.getDataValue(r)}),d}t.error("Internal Server Error")}))}_all(t){return y(this,arguments,void 0,(function*({ctx:t,options:o,callback:s,scope:i}){var n,d,p,u,l,c;const g=this.scope(i),y=Object.assign({},o||{});y.where=Object.assign({},y.where||{});const h=t.req.query.limit,v=r.isString(h)?parseInt(h):x.API_MODEL_LIMIT;y.limit=v>=0?Math.min(v,x.API_MODEL_LIMIT_MAX):void 0;const _=t.req.query.offset;if(r.isString(_)){const e=_?parseInt(_):0;y.offset=e>0?e:void 0}const m=[],f=this.columns(),A=e=>f.indexOf(e)>=0,C=null===(n=t.req.query.asc)||void 0===n?void 0:n.toString();C&&C.length&&m.push(...C.split(",").filter(A).map((e=>[e,"ASC"])));const S=null===(d=t.req.query.desc)||void 0===d?void 0:d.toString();S&&S.length&&m.push(...S.split(",").filter(A).map((e=>[e,"DESC"]))),m.length&&(y.order=m);const P=[],I=null===(p=t.req.query.search)||void 0===p?void 0:p.toString();(r.isArray(y.attributes)?y.attributes:f).filter(r.isString).forEach((e=>{var r;if(I&&I.length&&P.push({[e]:{[a.Op.like]:`%${I}%`}}),"search_"+e in t.req.query){const o=null===(r=t.req.query["search_"+e])||void 0===r?void 0:r.toString();o&&o.length&&P.push({[e]:{[a.Op.like]:`%${o}%`}})}})),P.length&&(y.where=Object.assign(Object.assign({},y.where),{[a.Op.or]:[...P]}));const O=null!==(u=yield g.count(Object.assign(Object.assign({},y),{col:f[0]})).catch(this.error))&&void 0!==u?u:0,w=yield g.findAll(y).catch(this.error),E={count:O,limit:null!==(l=y.limit)&&void 0!==l?l:-1,offset:null!==(c=y.offset)&&void 0!==c?c:0};return w?(t.prepare(e.Status.OK,Object.assign(Object.assign({},E),{records:s?yield s(w):w})),Object.assign(Object.assign({},E),{records:w})):(t.error("Internal Server Error"),Object.assign(Object.assign({},E),{records:[]}))}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return y(this,arguments,void 0,(function*({ctx:e,options:t,user:r}){var o;const s=this.key(),{[s]:i}=e.req.params;if(!i)return e.error("Internal Server Error"),0;const n=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,d=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:i}),individualHooks:!0}),{user_id:n})).catch(this.error);return d?(e.success("OK"),d):(e.notFound("Record not found"),0)}))}error(e){e.sql?m.error(e.message+"\n"+e.sql,"api.controller.sql",x.API_CONSOLE_ERROR):super.error(e)}_get(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,callback:o,scope:s}){const i=this.key(),{[i]:n}=t.req.params,d=yield this.scope(s).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[i]:n})})).catch(this.error);return d?(t.prepare(e.Status.OK,o?yield o(d):d.toJSON()),d):null===d?t.notFound("Record not found"):void t.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return y(this,arguments,void 0,(function*({ctx:e,options:t,body:r,user:o}){var s,i;const n=this.key(),{[n]:d}=e.req.params,a=null!==(s=null==o?void 0:o.id)&&void 0!==s?s:null,[p]=null!==(i=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:d}),individualHooks:!0}),{user_id:a})).catch(this.error))&&void 0!==i?i:[];return p?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=l([e.Extends(D)],exports.ModelController),exports.AuditsController=class extends exports.ModelController{model(){return exports.Audit}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data"]},where:o,order:[["created_at","DESC"]]}})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}},l([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("table")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),l([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=l([e.Controller("/audits"),e.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class extends D{login(e,o,s,i,n){return y(this,void 0,void 0,(function*(){var d;yield r.sleep(x.API_SLEEP_AUTH);const p=yield exports.User.scope("password").findOne({where:{[a.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(i+=null!==(d=null==p?void 0:p.salt)&&void 0!==d?d:"",!p||p.password!=t.sha256(i))return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield exports.Register.findOne({where:{state:!0,user_id:p.id}}).catch(this.error);if(u)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:u,user:p}),void this.emit("auth.activation",{ctx:e,register:u,user:p});if(!p.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:l,error:c,token:g}=yield P.create(p);return c?(e.error(c),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):l&&g?(l.useragent=o,yield l.save().catch(this.error),e.json({token:g}),n.emit("auth.login",{auth:l,ctx:e,user:p}),void this.emit("auth.login",{auth:l,ctx:e,user:p})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,o){return y(this,void 0,void 0,(function*(){if(yield P.destroy(t))return e.success("Disconcerted"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const{auth:s,error:i,token:n}=yield P.renew(r);return i?e.error(i):s?(s.useragent=t,yield s.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:s,ctx:e}),void this.emit("auth.renew",{auth:s,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return y(this,void 0,void 0,(function*(){const r=yield T.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},l([e.Post("/login"),e.Middleware("validation",{username:r.Validation.string().min(3).required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),l([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,E()),c(2,R()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),l([e.Post("/renew"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),l([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,R()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=l([e.Controller("/auth"),e.Extends(D)],exports.AuthController),exports.FilesController=class extends D{directory(){return x.API_HTTP_PUBLIC||"./"}files(e){return y(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=u.join(this.directory(),t);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return e.notFound("Path not Found");let s=[];return s=n.readdirSync(o),s=s.map((e=>this.info(u.join(o,e)))),s=s.filter(r.isDef),Object.assign(Object.assign({},this.info(o)),{files:s})}))}access(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}},l([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.FilesController.prototype,"files",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=l([e.Controller("/files"),e.Extends(D)],exports.FilesController),exports.ForgotController=class extends D{check(e,t){return y(this,void 0,void 0,(function*(){const o=yield this.find(t);if(!o||!o.user)return e.notFound("User not found");o.token=r.uniqueID(),yield o.save(),e.json({token:o.token})}))}forgot(e,t,o){return y(this,void 0,void 0,(function*(){yield r.sleep(x.API_SLEEP_FORGOT);const s=t,i=yield exports.User.findOne({where:{[a.Op.or]:[{email:s},{username:t}]}}).catch(this.error);if(!i)return e.notFound("User not found");const n=r.uniqueID(),d=Date.now()+6e4*x.API_TOKEN_FORGOT,p=yield exports.Forgot.create({token:n,timestamp:d,state:!0,user_id:i.id});e.success("OK"),o.emit("forgot.send",{ctx:e,forgot:p,user:i}),this.emit("forgot.send",{ctx:e,forgot:p,user:i})}))}reset(e,r,o,s){return y(this,void 0,void 0,(function*(){const i=yield this.find(r);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.password=t.sha256(o),yield i.user.save().catch(this.error),e.success("OK"),s.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})}))}find(e){return y(this,void 0,void 0,(function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)}))}},l([e.Get("/check"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),l([e.Post(),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),l([e.Post("/reset"),e.Middleware("validation",{token:r.Validation.string().required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,I]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=l([e.Controller("/forgot"),e.Extends(D)],exports.ForgotController),exports.CrudController=class extends exports.ModelController{constructor(){super(...arguments),this._crud={}}add(e,t){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e,user:t})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}create(){return this._crud}del(e,t){return y(this,void 0,void 0,(function*(){yield this._del({ctx:e,user:t})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return y(this,void 0,void 0,(function*(){yield this._set({ctx:e,user:t})}))}update(){return this._crud}validationAdd(e){return y(this,void 0,void 0,(function*(){const t=this.create();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}validationSet(e){return y(this,void 0,void 0,(function*(){const t=this.update();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}},l([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationAdd"),c(0,e.Ctx()),c(1,R()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.CrudController.prototype,"add",null),l([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"all",null),l([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,R()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.CrudController.prototype,"del",null),l([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"get",null),l([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationSet"),c(0,e.Ctx()),c(1,R()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.CrudController.prototype,"set",null),l([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),l([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=l([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return exports.Group}create(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}update(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.GroupsController=l([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return exports.GroupRoute}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:exports.Route,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,o,s){return y(this,void 0,void 0,(function*(){const i=yield exports.Group.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield exports.GroupRoute.destroy(Object.assign({where:{group_id:t},individualHooks:!0},s)),o){let e=0;yield r.sleep(1e3);for(let r=0;r<o.length;r++)e=yield exports.Route.count({where:{id:o[r]}}),e&&(yield exports.GroupRoute.create({group_id:t,route_id:o[r]},Object.assign({},s)))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},l([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),l([e.Put("/:id/routes"),e.Middleware("auth"),e.Middleware("write","groups"),e.Middleware("validation",{routes:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("routes")),c(3,w()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=l([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return exports.Log}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this._all({ctx:e,options:{where:o,order:[["created_at","DESC"]]}})}))}},l([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=l([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends D{register(e,o,s){return y(this,void 0,void 0,(function*(){yield r.sleep(x.API_SLEEP_REGISTRY);const{name:i,date:n,email:d,username:p,password:u,confirm:l}=o,c=p||d,g=t.sha256(u);if(yield exports.User.count({where:{[a.Op.or]:[{email:d},{username:c}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=t.sha256(l))return e.error("Invalid password");const y=yield exports.User.create({name:i,email:d,username:c,password:g,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const h=yield exports.Register.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),e.error("Internal Server Error");e.success("OK"),s.emit("register.user",{ctx:e,register:h,user:y}),this.emit("register.user",{ctx:e,register:h,user:y})}))}confirm(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("User not found");o.state=!1,yield o.save().catch(this.error),o.user.state=!0,yield o.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:o,user:o.user}),this.emit("register.confirm",{ctx:e,register:o,user:o.user})}))}send(e,t,r){return y(this,void 0,void 0,(function*(){const o=t,s=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[a.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})}))}getId(){return y(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield exports.Register.count({where:{token:e}}))?this.getId():e}))}},l([e.Post(),e.Middleware("validation",{name:r.Validation.string().required(),date:r.Validation.date().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).required(),confirm:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,Object,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),l([e.Post("/confirm"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),l([e.Post("/send"),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=l([e.Controller("/register"),e.Extends(D)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return exports.Route}create(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}update(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.RoutesController=l([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends D{setup(e){return y(this,void 0,void 0,(function*(){if(0==(yield exports.User.count())){const e=r.uniqueID(),o=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:t.sha256("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),s={description:"API CORE",state:!0},i=yield exports.Group.create(Object.assign({name:"admin"},s));yield exports.UserGroup.create({user_id:o.id,group_id:i.id});const n=["read","write"],d=["audits","users","groups","routes"];yield r.forEachSeries(d,(e=>y(this,void 0,void 0,(function*(){yield r.forEachSeries(n,(t=>y(this,void 0,void 0,(function*(){const r=yield exports.Route.create(Object.assign({name:`${e}.${t}`},s));yield exports.GroupRoute.create({group_id:i.id,route_id:r.id})}))))}))));const a=["delete","list","read","rename","upload","write"];yield r.forEachSeries(a,(e=>y(this,void 0,void 0,(function*(){const t=yield exports.Route.create(Object.assign({name:`files.${e}`},s));yield exports.GroupRoute.create({group_id:i.id,route_id:t.id})}))));const p=["logs"];yield r.forEachSeries(p,(e=>y(this,void 0,void 0,(function*(){const t=yield exports.Route.create(Object.assign({name:`${e}.read`},s));yield exports.GroupRoute.create({group_id:i.id,route_id:t.id})}))))}e.success("OK")}))}},l([e.Get(),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=l([e.Controller("/setup"),e.Extends(D)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return exports.User}constructor(){super(),this.dir=x.API_HTTP_PUBLIC+"/avatar",x.API_HTTP_PUBLIC&&n.existsSync(x.API_HTTP_PUBLIC)&&!n.existsSync(this.dir)&&n.mkdirSync(this.dir)}avatar(e,t,r,o){return y(this,void 0,void 0,(function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.dir+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=s,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t,r){return y(this,void 0,void 0,(function*(){const o=this.dir+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&n.existsSync(o)&&n.rmSync(o),e.success("OK")}))}password(e,o,s,i,n){return y(this,void 0,void 0,(function*(){var d;const a=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);return o+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==t.sha256(o)?(a.salt=r.uniqueID(),a.password=t.sha256(s+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_get(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_remove(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(s){const t=yield this.token_new();return s.token=o.hash.encrypt(t),yield s.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return y(this,void 0,void 0,(function*(){var e;const t=r.uuidv4();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,o,s){return y(this,void 0,void 0,(function*(){const i=r.uniqueID();yield this._add({ctx:e,body:{password:t.sha256(o+i),salt:i},user:s})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return y(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("Record not found");yield this._del({ctx:e,user:r})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,o,s){return y(this,void 0,void 0,(function*(){const i=r.uniqueID();yield this._set({ctx:e,body:o?{password:t.sha256(o+i),salt:i}:{},user:s})}))}},l([e.Post("/avatar"),e.Middleware("auth"),e.Middleware("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),c(0,e.Ctx()),c(1,e.Files()),c(2,R()),c(3,w()),g("design:type",Function),g("design:paramtypes",[e.Context,Array,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),l([e.Get("/avatar/remove"),e.Middleware("auth"),c(0,e.Ctx()),c(1,R()),c(2,w()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar_remove",null),l([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:r.Validation.string().min(5).required(),newPassword:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,R()),c(4,w()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),l([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,R()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token",null),l([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),l([e.Get("/token/remove/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,w()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_remove",null),l([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,w()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),l([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:r.Validation.string().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).required(),password:r.Validation.string().min(5).required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}),c(0,e.Ctx()),c(1,e.Body("password")),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"add",null),l([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"all",null),l([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"del",null),l([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"get",null),l([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:r.Validation.string().empty(),email:r.Validation.string().email().empty(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).empty().filter(""),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}),c(0,e.Ctx()),c(1,e.Body("password")),c(2,R()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=l([e.Controller("/users"),e.Extends(exports.ModelController),g("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return exports.UserGroup}groups(e,t){return y(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,o,s){return y(this,void 0,void 0,(function*(){const i=yield exports.User.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:i.id},individualHooks:!0},s)),o){let e=0;yield r.sleep(1e3);for(let t=0;t<o.length;t++)e=yield exports.Group.count({where:{id:o[t]}}),e&&(yield exports.UserGroup.create({user_id:i.id,group_id:o[t]},Object.assign({},s)))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},l([e.Get("/groups"),e.Middleware("auth"),c(0,e.Ctx()),c(1,R()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"groups",null),l([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),l([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("write","users"),e.Middleware("validation",{groups:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),c(3,w()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=l([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=I,exports.Config=O,exports.ControllerBase=D,exports.Env=x,exports.Logs=m,exports.Model=v,exports.Permission=T,exports.ReqAudit=w,exports.ReqAuth=E,exports.ReqUser=R,exports.Token=P,exports.audit=_,exports.conn=h,exports.crt=A,exports.key=C;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/node"),r=require("@andrewcaires/utils.js"),o=require("ws"),s=require("@andrewcaires/sequelize"),i=require("dotenv"),n=require("fs"),d=require("express-session"),a=require("sequelize"),p=require("jsonwebtoken"),l=require("path");function u(e,t,r,o){var s,i=arguments.length,n=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(s=e[d])&&(n=(i<3?s(n):i>3?s(t,r,n):s(t,r))||n);return i>3&&n&&Object.defineProperty(t,r,n),n}function c(e,t){return function(r,o){t(r,o,e)}}function g(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function y(e,t,r,o){return new(r||(r=Promise))((function(s,i){function n(e){try{a(o.next(e))}catch(e){i(e)}}function d(e){try{a(o.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,i.config();class x{static getBool(e,t){return r.toBool(x.getString(e,t.toString()))}static getInt(e,t){return parseInt(x.getString(e,t.toString()))}static getMs(e,t){return r.parseMs(x.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}x.API_CONSOLE_ERROR=x.getBool("API_CONSOLE_ERROR",!1),x.API_DEFAULT_PATH=x.getString("API_DEFAULT_PATH","/api"),x.API_DB_DATABASE=x.getString("API_DB_DATABASE",""),x.API_DB_HOST=x.getString("API_DB_HOST","127.0.0.1"),x.API_DB_PASSWORD=x.getString("API_DB_PASSWORD",""),x.API_DB_PORT=x.getInt("API_DB_PORT",3306),x.API_DB_TYPE=x.getString("API_DB_TYPE",""),x.API_DB_USERNAME=x.getString("API_DB_USERNAME","root"),x.API_DB_LOG=x.getBool("API_DB_LOG",!1),x.API_DB_AUDIT=x.getBool("API_DB_AUDIT",!0),x.API_DB_PREFIX=x.getString("API_DB_PREFIX",""),x.API_DB_TIMEZONE=x.getString("API_DB_TIMEZONE","+00:00"),x.API_HTTP_CRT=x.getString("API_HTTP_CRT",""),x.API_HTTP_KEY=x.getString("API_HTTP_KEY",""),x.API_HTTP_PORT=x.getInt("API_HTTP_PORT",3e3),x.API_HTTP_PUBLIC=x.getString("API_HTTP_PUBLIC",""),x.API_HTTP_CROSS=x.getBool("API_HTTP_CROSS",!1),x.API_HTTP_HYBRID=x.getBool("API_HTTP_HYBRID",!1),x.API_HTTP_NOTFOUND=x.getString("API_HTTP_NOTFOUND",""),x.API_HTTP_REDIRECT=x.getString("API_HTTP_REDIRECT",""),x.API_KEY_HASH=x.getString("API_KEY_HASH",""),x.API_KEY_HEADER=x.getString("API_KEY_HEADER","api_key"),x.API_MODEL_LIMIT=x.getInt("API_MODEL_LIMIT",10),x.API_MODEL_LIMIT_MAX=x.getInt("API_MODEL_LIMIT_MAX",500),x.API_SLEEP_AUTH=x.getMs("API_SLEEP_AUTH","2s"),x.API_SLEEP_FORGOT=x.getMs("API_SLEEP_FORGOT","5s"),x.API_SLEEP_REGISTRY=x.getMs("API_SLEEP_REGISTRY","5s"),x.API_SESSION_NAME=x.getString("API_SESSION_NAME","session.id"),x.API_SESSION_LIFETIME=x.getMs("API_SESSION_LIFETIME","1d"),x.API_SESSION_SECRET=x.getString("API_SESSION_SECRET","yoursecret"),x.API_TOKEN_CRT=x.getString("API_TOKEN_CRT",""),x.API_TOKEN_KEY=x.getString("API_TOKEN_KEY",""),x.API_TOKEN_FORGOT=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_HEADER=x.getString("API_TOKEN_HEADER","authorization"),x.API_TOKEN_LIFETIME=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_RENEW=x.getMs("API_TOKEN_RENEW","1d"),x.API_UPLOAD_COUNT=x.getInt("API_UPLOAD_COUNT",1),x.API_UPLOAD_FIELD=x.getString("API_UPLOAD_FIELD","upload"),x.API_UPLOAD_SIZE=x.getInt("API_UPLOAD_SIZE",2),x.API_UPLOAD_TEMP=x.getString("API_UPLOAD_TEMP","./temp"),x.API_WEBSOCKET_START=x.getBool("API_WEBSOCKET_START",!1);const h=new s.Connection({type:x.API_DB_TYPE,database:x.API_DB_DATABASE,username:x.API_DB_USERNAME,password:x.API_DB_PASSWORD,hostname:x.API_DB_HOST,hostport:x.API_DB_PORT,logging:x.API_DB_LOG,prefix:x.API_DB_PREFIX});class v extends s.Model{}const m=(e,t,r)=>{var o,s,i,n;return{type:e,model:null!==(o=null==t?void 0:t.getTableName())&&void 0!==o?o:null,user_ip:null!==(s=null==r?void 0:r.audit_user_ip)&&void 0!==s?s:null,user_agent:null!==(i=null==r?void 0:r.audit_user_agent)&&void 0!==i?i:null,user_id:null!==(n=null==r?void 0:r.audit_user_id)&&void 0!==n?n:null,state:!0}},_={afterCreate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o;if(!x.API_DB_AUDIT)return;const s=r.isObject(e)?e.constructor:null,i=null!==(o=null==s?void 0:s.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},m("CREATE",s,t)),{record:i?e.getDataValue(i):null,data:e.toJSON()})).catch(r.noop)})),afterUpdate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o;if(!x.API_DB_AUDIT)return;const s=r.isObject(e)?e.constructor:null,i=null!==(o=null==s?void 0:s.primaryKeyAttribute)&&void 0!==o?o:null,n=e.changed();n&&n.forEach((t=>e.getDataValue(t))),yield exports.Audit.create(Object.assign(Object.assign({},m("UPDATE",s,t)),{record:i?e.getDataValue(i):null,data:e.toJSON(),previously:e.previous()})).catch(r.noop)})),afterDestroy:(e,t)=>y(void 0,void 0,void 0,(function*(){var o;if(!x.API_DB_AUDIT)return;const s=r.isObject(e)?e.constructor:null,i=null!==(o=null==s?void 0:s.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},m("DELETE",s,t)),{record:i?e.getDataValue(i):null,data:JSON.stringify(e.toJSON())})).catch(r.noop)}))};exports.Auth=class extends v{},u([s.Id(),g("design:type",Number)],exports.Auth.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Auth.prototype,"secret",void 0),u([s.FullDate(),g("design:type",Date)],exports.Auth.prototype,"logout",void 0),u([s.String(),g("design:type",s.String)],exports.Auth.prototype,"user_agent",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Auth.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Auth.prototype,"deleted_at",void 0),u([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=u([s.Database(h),s.ModelName("auth")],exports.Auth),exports.Register=class extends v{},u([s.Id(),g("design:type",Number)],exports.Register.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Register.prototype,"token",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.Register.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Register.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Register.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Register.prototype,"deleted_at",void 0),u([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=u([s.Database(h),s.ModelName("register")],exports.Register),exports.Group=class extends v{},u([s.Id(),g("design:type",Number)],exports.Group.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Group.prototype,"name",void 0),u([s.Text(),g("design:type",s.String)],exports.Group.prototype,"description",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.Group.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Group.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Group.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Group.prototype,"deleted_at",void 0),u([s.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),u([s.HasMany((()=>exports.UserGroup),"group_id"),g("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=u([s.Database(h),s.ModelName("group"),s.Hooks(_)],exports.Group),exports.UserGroup=class extends v{},u([s.CreatedAt,g("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),u([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),u([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=u([s.Database(h),s.ModelName("users_groups"),s.Hooks(_)],exports.UserGroup),exports.User=class extends v{},u([s.Id(),g("design:type",Number)],exports.User.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"name",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"email",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"username",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"password",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"salt",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"token",void 0),u([s.String(),g("design:type",s.String)],exports.User.prototype,"avatar",void 0),u([s.DateOnly(),g("design:type",s.String)],exports.User.prototype,"date",void 0),u([s.Text(),g("design:type",s.String)],exports.User.prototype,"description",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.User.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.User.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.User.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.User.prototype,"deleted_at",void 0),u([s.HasMany((()=>exports.Audit),"user_id"),g("design:type",Array)],exports.User.prototype,"audits",void 0),u([s.HasMany((()=>exports.Auth),"user_id"),g("design:type",Array)],exports.User.prototype,"auths",void 0),u([s.HasMany((()=>exports.Register),"user_id"),g("design:type",Array)],exports.User.prototype,"registers",void 0),u([s.HasMany((()=>exports.UserGroup),"user_id"),g("design:type",Array)],exports.User.prototype,"users_groups",void 0),exports.User=u([s.Database(h),s.ModelName("user"),s.DefaultScope({attributes:{exclude:["password","salt","token"]}}),s.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),s.Hooks(_)],exports.User),exports.Audit=class extends v{},u([s.Id(),g("design:type",Number)],exports.Audit.prototype,"id",void 0),u([s.Enum("CREATE","DELETE","UPDATE"),g("design:type",s.String)],exports.Audit.prototype,"type",void 0),u([s.String(),g("design:type",s.String)],exports.Audit.prototype,"model",void 0),u([s.String(),g("design:type",s.String)],exports.Audit.prototype,"record",void 0),u([s.String(),g("design:type",s.String)],exports.Audit.prototype,"user_ip",void 0),u([s.String(),g("design:type",s.String)],exports.Audit.prototype,"user_agent",void 0),u([s.Json(),g("design:type",Object)],exports.Audit.prototype,"data",void 0),u([s.Json(),g("design:type",Object)],exports.Audit.prototype,"previously",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.Audit.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Audit.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Audit.prototype,"deleted_at",void 0),u([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=u([s.Database(h),s.ModelName("audit")],exports.Audit),exports.Configs=class extends v{},u([s.String(),g("design:type",s.String)],exports.Configs.prototype,"key",void 0),u([s.String(),g("design:type",s.String)],exports.Configs.prototype,"value",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Configs.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Configs.prototype,"updated_at",void 0),exports.Configs=u([s.Database(h),s.ModelName("configs"),s.Hooks(_)],exports.Configs),exports.Forgot=class extends v{},u([s.Id(),g("design:type",Number)],exports.Forgot.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Forgot.prototype,"token",void 0),u([s.BigInt(),g("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.Forgot.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Forgot.prototype,"deleted_at",void 0),u([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=u([s.Database(h),s.ModelName("forgot")],exports.Forgot),exports.Permission=class extends v{},u([s.Id(),g("design:type",Number)],exports.Permission.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Permission.prototype,"name",void 0),u([s.String(),s.Unique(!0),g("design:type",s.String)],exports.Permission.prototype,"route",void 0),u([s.Text(),g("design:type",s.String)],exports.Permission.prototype,"description",void 0),u([s.Boolean(),g("design:type",s.Boolean)],exports.Permission.prototype,"state",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Permission.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),u([s.DeletedAt,g("design:type",Date)],exports.Permission.prototype,"deleted_at",void 0),u([s.HasMany((()=>exports.GroupPermission),"permission_id"),g("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=u([s.Database(h),s.ModelName("permission"),s.Hooks(_)],exports.Permission),exports.GroupPermission=class extends v{},u([s.CreatedAt,g("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),u([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),u([s.BelongsTo((()=>exports.Permission)),g("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=u([s.Database(h),s.ModelName("groups_permissions"),s.Hooks(_)],exports.GroupPermission),exports.Log=class extends v{},u([s.Id(),g("design:type",Number)],exports.Log.prototype,"id",void 0),u([s.String(),g("design:type",s.String)],exports.Log.prototype,"type",void 0),u([s.String(),g("design:type",s.String)],exports.Log.prototype,"source",void 0),u([s.Text(),g("design:type",s.String)],exports.Log.prototype,"message",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=u([s.Database(h),s.ModelName("log")],exports.Log),exports.Session=class extends v{},u([s.String(),g("design:type",s.String)],exports.Session.prototype,"session",void 0),u([s.Text(),g("design:type",s.String)],exports.Session.prototype,"json",void 0),u([s.BigInt(),g("design:type",Number)],exports.Session.prototype,"expired",void 0),u([s.CreatedAt,g("design:type",Date)],exports.Session.prototype,"created_at",void 0),u([s.UpdatedAt,g("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=u([s.Database(h),s.ModelName("session")],exports.Session);class P{static write(e,r,o){return y(this,void 0,void 0,(function*(){yield P.writeRaw(t.LogColor.White,"",e,r,o)}))}static error(e,r,o){return y(this,void 0,void 0,(function*(){yield P.writeRaw(t.LogColor.Red,"error",e,r,o)}))}static info(e,r,o){return y(this,void 0,void 0,(function*(){yield P.writeRaw(t.LogColor.Cyan,"info",e,r,o)}))}static success(e,r,o){return y(this,void 0,void 0,(function*(){yield P.writeRaw(t.LogColor.Green,"success",e,r,o)}))}static warning(e,r,o){return y(this,void 0,void 0,(function*(){yield P.writeRaw(t.LogColor.Yellow,"warning",e,r,o)}))}static writeRaw(e,r,o,s,i){return y(this,void 0,void 0,(function*(){i&&t.Log.console(e,r,o),h&&(yield exports.Log.create({type:r,source:s,message:o}).catch((()=>null)))}))}}const A=e=>n.existsSync(e)?n.readFileSync(e):void 0,f={http:A(x.API_HTTP_CRT),token:A(x.API_TOKEN_CRT)},C={http:A(x.API_HTTP_KEY),token:A(x.API_TOKEN_KEY)};class S extends d.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,(function*(){e=e||r.noop;const t=yield exports.Session.findAll({attributes:["session"],where:{expired:{[a.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy().catch(r.noop),e&&e()})),this.destroy=(e,t)=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{session:e}}).catch(r.noop),t&&t()})),this.expired=()=>y(this,void 0,void 0,(function*(){yield exports.Session.destroy({where:{expired:{[a.Op.lt]:Date.now()}}}).catch(r.noop)})),this.get=(e,t)=>y(this,void 0,void 0,(function*(){t=t||r.noop;const o=yield exports.Session.findOne({where:{session:e,expired:{[a.Op.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(o){const e=JSON.parse(o.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(r.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>y(this,void 0,void 0,(function*(){e&&e(null,(yield exports.Session.count().catch(r.noop))||0)})),this.set=(e,t,o)=>y(this,void 0,void 0,(function*(){o=o||r.noop;const s=Date.now()+x.API_SESSION_LIFETIME,i=JSON.stringify(t),[n,d]=(yield exports.Session.findOrCreate({where:{session:e},defaults:{session:e,json:i,expired:s}}).catch(r.noop))||[];n&&(d||(n.json=i,n.expired=s,yield n.save().catch(r.noop))),o()})),this.loop=r.loop(this.expired,3e4),this.loop.start()}}class O{static create(e){return y(this,void 0,void 0,(function*(){if(!C.token)return{error:"Key not found"};const{id:t}=e,o=r.uuidv4(),s=yield exports.Auth.create({secret:o,user_id:t}).catch(O.error);if(!s)return{error:"Internal Server Error"};return{auth:s,token:p.sign({id:t,secret:o},C.token,O.options())}}))}static destroy(e){return y(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){P.error(e.message,"api.token",x.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:x.API_TOKEN_LIFETIME+"ms"}}static renew(e){return y(this,void 0,void 0,(function*(){if(!C.token)return{error:"Key not found"};const{error:t,decode:o}=O.verify(e,x.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(o){const{id:e,secret:t}=o;if(e&&t){const o=yield exports.User.findOne({where:{id:e,state:!0}}).catch(O.error);if(o){const s=yield exports.Auth.findOne({where:{secret:t,user_id:o.id}}).catch(O.error);if(s&&!s.logout){s.secret=r.uuidv4(),yield s.save().catch(O.error);return{auth:s,token:p.sign({id:e,secret:s.secret},C.token,O.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return y(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const o=yield exports.User.findOne({where:{token:t,state:!0}}).catch(O.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(O.error))||[];if(r)return{auth:r,user:o}}return{error:"Access denied"}}const{error:o,decode:s}=O.verify(t);if(o)return{error:o};if(s){const{id:e,secret:t}=s;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(O.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(O.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!f.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:p.verify(e,f.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class I extends e.Application{constructor(e){super(e,{cert:f.http,cross:x.API_HTTP_CROSS,hybrid:x.API_HTTP_HYBRID,key:C.http,notfound:x.API_HTTP_NOTFOUND,path:x.API_DEFAULT_PATH,port:x.API_HTTP_PORT,public:x.API_HTTP_PUBLIC,redirect:x.API_HTTP_REDIRECT,session:{store:new S,name:x.API_SESSION_NAME,secret:x.API_SESSION_SECRET,cookie:{maxAge:x.API_SESSION_LIFETIME},genid:r.uuidv4}}),this.hash=new t.Hash(x.API_KEY_HASH)}error(e,t){P.error(e.message,t,x.API_CONSOLE_ERROR)}log(e,t){P.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,(function*(){yield h.sync(),yield e.listen.call(this),x.API_WEBSOCKET_START&&this.server&&(this._webSocket=new o.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(x.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>y(this,void 0,void 0,(function*(){t.url||(t.url="");const o=t.url.length<=1?"":t.url.replace(/\//g,".");let s;e.on("message",(r=>y(this,void 0,void 0,(function*(){if(s)try{const i=JSON.parse(r);this.emit("ws.message"+o,{data:i,message:r,req:t,user:s,ws:e})}catch(i){this.emit("ws.message"+o,{message:r,req:t,user:s,ws:e})}else{const{user:i}=yield O.user("",r.toString(),this);i&&(s=i,this.emit("ws.connection"+o,{req:t,user:s,ws:e}))}s||e.close()})))),e.on("close",(()=>{s&&this.emit("ws.close"+o,{user:s,ws:e})})),yield r.sleep(2e3),s||e.close()})))))}))}websocket(){return this._webSocket}}class E{static all(){return y(this,void 0,void 0,(function*(){const e=yield exports.Configs.findAll().catch(E.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return y(this,void 0,void 0,(function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield exports.Configs.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(E.error))||0)>0}))}static error(e){P.error(e.message,"api.config",x.API_CONSOLE_ERROR)}static get(e){return y(this,arguments,void 0,(function*(e,t=""){const[r]=(yield exports.Configs.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(E.error))||[];return r?r.value:t}))}static set(e,t,r){return y(this,void 0,void 0,(function*(){var o;const s=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[i]=(yield exports.Configs.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(E.error))||[];i&&(i.value=t,yield i.save().catch(E.error))}))}}const w=e=>{var t,r,o,s,i,n;return{audit_user_ip:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_user_id:null!==(s=null===(o=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.user)||void 0===o?void 0:o.id)&&void 0!==s?s:null,audit_user_agent:null!==(n=null===(i=e.req)||void 0===i?void 0:i.headers["user-agent"])&&void 0!==n?n:""}},T=e.parameterFactory((({ctx:e})=>w(e))),b=e.parameterFactory((({ctx:e})=>e.req.auth)),D=e.parameterFactory((({ctx:e})=>e.req.user));class U extends r.EventEmitter{auth(e,t,r,o,s){return y(this,void 0,void 0,(function*(){const{auth:i,error:n,user:d}=yield O.user(t,r,s);return n?e.error(n):i&&d?i.user_agent&&i.user_agent!=o?e.error("Invalid token"):(e.req.auth=i,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}create(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",r)}))}delete(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",r)}))}error(e){P.error(e.message,"api.controller",x.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,(function*(){if(r){const o=yield this.permissions(r,{route:t});if(o&&o.length>0)return e.next()}e.unauthorized("Access denied")}))}permissions(e,t){return y(this,void 0,void 0,(function*(){return yield exports.Permission.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:exports.GroupPermission,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}session(e,t,o){return y(this,void 0,void 0,(function*(){o.auth&&o.user&&(o.user_agent?o.user_agent!=t&&o.regenerate(r.noop):(o.user_agent=t,o.save(r.noop))),e.next()}))}upload(t,r){r.path||(r.path=x.API_UPLOAD_TEMP),r.size||(r.size=x.API_UPLOAD_SIZE),r.field||(r.field=x.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}update(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",r)}))}validation(e,t){return y(this,void 0,void 0,(function*(){const{error:o,value:s}=yield r.Validation.object(t).parse().validateAsync(e.req.body);if(o)return e.validation(o);e.req.body=s,e.next()}))}}u([c(0,e.Ctx()),c(1,e.Headers(x.API_KEY_HEADER)),c(2,e.Headers(x.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,I]),g("design:returntype",Promise)],U.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"create",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"delete",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],U.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",void 0)],U.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],U.prototype,"update",null),u([c(0,e.Ctx()),c(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],U.prototype,"validation",null),exports.ModelController=class extends U{constructor(){super(...arguments),this._columns=[]}_add(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,body:o}){const s=yield this.model().create(Object.assign(Object.assign({},t.req.body),o||{}),Object.assign(Object.assign({},r||{}),w(t))).catch(this.error);if(s){const r=this.key();return t.prepare(e.Status.OK,{[r]:s.getDataValue(r)}),s}t.error("Internal Server Error")}))}_all(t){return y(this,arguments,void 0,(function*({ctx:t,options:o,callback:s,scope:i}){var n,d,p,l;const u=this.scope(i),c=Object.assign({},o||{});c.where=Object.assign({},c.where||{});const g=t.req.query.limit,y=r.isString(g)?parseInt(g):x.API_MODEL_LIMIT;c.limit=y>=0?Math.min(y,x.API_MODEL_LIMIT_MAX):void 0;const h=t.req.query.offset;if(r.isString(h)){const e=h?parseInt(h):0;c.offset=e>0?e:void 0}const v=[],m=this.columns(),_=e=>m.indexOf(e)>=0,P=null===(n=t.req.query.asc)||void 0===n?void 0:n.toString();P&&P.length&&v.push(...P.split(",").filter(_).map((e=>[e,"ASC"])));const A=null===(d=t.req.query.desc)||void 0===d?void 0:d.toString();A&&A.length&&v.push(...A.split(",").filter(_).map((e=>[e,"DESC"]))),v.length&&(c.order=v);const f=[],C=null===(p=t.req.query.search)||void 0===p?void 0:p.toString();(r.isArray(c.attributes)?c.attributes:m).filter(r.isString).forEach((e=>{var r;if(C&&C.length&&f.push({[e]:{[a.Op.like]:`%${C}%`}}),"search_"+e in t.req.query){const o=null===(r=t.req.query["search_"+e])||void 0===r?void 0:r.toString();o&&o.length&&f.push({[e]:{[a.Op.like]:`%${o}%`}})}})),f.length&&(c.where=Object.assign(Object.assign({},c.where),{[a.Op.or]:[...f]}));const S=null!==(l=yield u.count(Object.assign(Object.assign({},c),{col:m[0]})).catch(this.error))&&void 0!==l?l:0,O=yield u.findAll(c).catch(this.error),I={count:S};return O?(t.prepare(e.Status.OK,Object.assign(Object.assign({},I),{records:s?yield s(O):O})),Object.assign(Object.assign({},I),{records:O})):(t.error("Internal Server Error"),Object.assign(Object.assign({},I),{records:[]}))}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return y(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("Internal Server Error"),0;const s=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o}),individualHooks:!0}),w(e))).catch(this.error);return s?(e.success("OK"),s):(e.notFound("Record not found"),0)}))}error(e){e.sql?P.error(e.message+"\n"+e.sql,"api.controller.sql",x.API_CONSOLE_ERROR):super.error(e)}_get(t){return y(this,arguments,void 0,(function*({ctx:t,options:r,callback:o,scope:s}){const i=this.key(),{[i]:n}=t.req.params,d=yield this.scope(s).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[i]:n})})).catch(this.error);return d?(t.prepare(e.Status.OK,o?yield o(d):d.toJSON()),d):null===d?t.notFound("Record not found"):void t.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return y(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){var o;const s=this.key(),{[s]:i}=e.req.params,[n]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:i}),individualHooks:!0}),w(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=u([e.Extends(U)],exports.ModelController),exports.AuditsController=class extends exports.ModelController{model(){return exports.Audit}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]}})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("table")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=u([e.Controller("/audits"),e.Extends(exports.ModelController)],exports.AuditsController),exports.AuthController=class extends U{login(e,o,s,i,n){return y(this,void 0,void 0,(function*(){var d;yield r.sleep(x.API_SLEEP_AUTH);const p=yield exports.User.scope("password").findOne({where:{[a.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(i+=null!==(d=null==p?void 0:p.salt)&&void 0!==d?d:"",!p||p.password!=t.sha256(i))return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield exports.Register.findOne({where:{state:!0,user_id:p.id}}).catch(this.error);if(l)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:l,user:p}),void this.emit("auth.activation",{ctx:e,register:l,user:p});if(!p.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:p}),void this.emit("auth.failure",{ctx:e,user:p});const{auth:u,error:c,token:g}=yield O.create(p);return c?(e.error(c),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&g?(u.user_agent=o,yield u.save().catch(this.error),e.json({token:g}),n.emit("auth.login",{auth:u,ctx:e,user:p}),void this.emit("auth.login",{auth:u,ctx:e,user:p})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,o){return y(this,void 0,void 0,(function*(){if(yield O.destroy(t))return e.success("Disconcerted"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const{auth:s,error:i,token:n}=yield O.renew(r);return i?e.error(i):s?(s.user_agent=t,yield s.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:s,ctx:e}),void this.emit("auth.renew",{auth:s,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return y(this,void 0,void 0,(function*(){const r=yield this.permissions(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.route))}))}))}},u([e.Post("/login"),e.Middleware("validation",{username:r.Validation.string().min(3).required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,b()),c(2,D()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),u([e.Post("/renew"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,I]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,D()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(U)],exports.AuthController),exports.FilesController=class extends U{directory(){return x.API_HTTP_PUBLIC||"./"}files(e){return y(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=l.join(this.directory(),t);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return e.notFound("Path not Found");let s=[];return s=n.readdirSync(o),s=s.map((e=>this.info(l.join(o,e)))),s=s.filter(r.isDef),Object.assign(Object.assign({},this.info(o)),{files:s})}))}access(e,t,r){return y(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}},u([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.FilesController.prototype,"files",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(U)],exports.FilesController),exports.ForgotController=class extends U{check(e,t){return y(this,void 0,void 0,(function*(){const o=yield this.find(t);if(!o||!o.user)return e.notFound("User not found");o.token=r.uniqueID(),yield o.save(),e.json({token:o.token})}))}forgot(e,t,o){return y(this,void 0,void 0,(function*(){yield r.sleep(x.API_SLEEP_FORGOT);const s=t,i=yield exports.User.findOne({where:{[a.Op.or]:[{email:s},{username:t}]}}).catch(this.error);if(!i)return e.notFound("User not found");const n=r.uniqueID(),d=Date.now()+6e4*x.API_TOKEN_FORGOT,p=yield exports.Forgot.create({token:n,timestamp:d,state:!0,user_id:i.id});e.success("OK"),o.emit("forgot.send",{ctx:e,forgot:p,user:i}),this.emit("forgot.send",{ctx:e,forgot:p,user:i})}))}reset(e,r,o,s){return y(this,void 0,void 0,(function*(){const i=yield this.find(r);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.password=t.sha256(o),yield i.user.save().catch(this.error),e.success("OK"),s.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})}))}find(e){return y(this,void 0,void 0,(function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)}))}},u([e.Get("/check"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),u([e.Post(),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),u([e.Post("/reset"),e.Middleware("validation",{token:r.Validation.string().required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,I]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(U)],exports.ForgotController),exports.CrudController=class extends exports.ModelController{constructor(){super(...arguments),this._crud={}}add(e){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return y(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return y(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return y(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}validationSet(e){return y(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}},u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validationAdd"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validationSet"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"set",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),u([c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=u([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return exports.Group}CrudCreate(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}CrudUpdate(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.GroupsController=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsPermissionsController=class extends exports.ModelController{model(){return exports.GroupPermission}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,o,s){return y(this,void 0,void 0,(function*(){const i=yield exports.Group.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:t},individualHooks:!0},s)),o){let e=0;yield r.sleep(1e3);for(let r=0;r<o.length;r++)e=yield exports.Permission.count({where:{id:o[r]}}),e&&(yield exports.GroupPermission.create({group_id:t,permission_id:o[r]},Object.assign({},s)))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),u([e.Put("/:id/permissions"),e.Middleware("auth"),e.Middleware("update","groups"),e.Middleware("validation",{permissions:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("permissions")),c(3,T()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsPermissionsController),exports.LogsController=class extends exports.ModelController{model(){return exports.Log}all(e,t,r){return y(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this._all({ctx:e,options:{where:o,order:[["created_at","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.PermissionsController=class extends exports.CrudController{model(){return exports.Permission}CrudCreate(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}CrudUpdate(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.PermissionsController=u([e.Controller("/permissions"),e.Extends(exports.CrudController)],exports.PermissionsController),exports.RegisterController=class extends U{register(e,o,s){return y(this,void 0,void 0,(function*(){yield r.sleep(x.API_SLEEP_REGISTRY);const{name:i,date:n,email:d,username:p,password:l,confirm:u}=o,c=p||d,g=t.sha256(l);if(yield exports.User.count({where:{[a.Op.or]:[{email:d},{username:c}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=t.sha256(u))return e.error("Invalid password");const y=yield exports.User.create({name:i,email:d,username:c,password:g,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const h=yield exports.Register.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),e.error("Internal Server Error");e.success("OK"),s.emit("register.user",{ctx:e,register:h,user:y}),this.emit("register.user",{ctx:e,register:h,user:y})}))}confirm(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("User not found");o.state=!1,yield o.save().catch(this.error),o.user.state=!0,yield o.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:o,user:o.user}),this.emit("register.confirm",{ctx:e,register:o,user:o.user})}))}send(e,t,r){return y(this,void 0,void 0,(function*(){const o=t,s=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[a.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})}))}getId(){return y(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield exports.Register.count({where:{token:e}}))?this.getId():e}))}},u([e.Post(),e.Middleware("validation",{name:r.Validation.string().required(),date:r.Validation.date().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).required(),confirm:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,Object,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),u([e.Post("/confirm"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),u([e.Post("/send"),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(U)],exports.RegisterController),exports.SetupController=class extends U{setup(e,o){return y(this,void 0,void 0,(function*(){if(0==(yield exports.User.count())){const e=r.uniqueID(),s=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:t.sha256("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},o)),i={description:"API CORE",state:!0},n=yield exports.Group.create(Object.assign({name:"admin"},i),Object.assign({},o));yield exports.UserGroup.create({user_id:s.id,group_id:n.id},Object.assign({},o));const d=["audits","users","groups","routes"],a=["create","read","update","delete"];yield r.forEachSeries(d,(e=>y(this,void 0,void 0,(function*(){yield r.forEachSeries(a,(t=>y(this,void 0,void 0,(function*(){const r=yield exports.Permission.create(Object.assign({name:`${e} ${t}`,route:`${e}.${t}`},i),Object.assign({},o));yield exports.GroupPermission.create({group_id:n.id,permission_id:r.id},Object.assign({},o))}))))}))));const p=["delete","list","read","rename","upload","write"];yield r.forEachSeries(p,(e=>y(this,void 0,void 0,(function*(){const t=yield exports.Permission.create(Object.assign({name:`files ${e}`,route:`files.${e}`},i),Object.assign({},o));yield exports.GroupPermission.create({group_id:n.id,permission_id:t.id},Object.assign({},o))}))));const l=["logs"];yield r.forEachSeries(l,(e=>y(this,void 0,void 0,(function*(){const t=yield exports.Permission.create(Object.assign({name:`${e} files`,route:`${e}.read`},i),Object.assign({},o));yield exports.GroupPermission.create({group_id:n.id,permission_id:t.id},Object.assign({},o))}))))}e.success("OK")}))}},u([e.Get(),c(0,e.Ctx()),c(1,T()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=u([e.Controller("/setup"),e.Extends(U)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return exports.User}constructor(){super(),this.path=x.API_HTTP_PUBLIC+"/avatar",x.API_HTTP_PUBLIC&&n.existsSync(x.API_HTTP_PUBLIC)&&!n.existsSync(this.path)&&n.mkdirSync(this.path)}avatar(e,t,r,o){return y(this,void 0,void 0,(function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.path+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=s,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&n.existsSync(o)&&n.rmSync(o),e.success("OK")}))}password(e,o,s,i,n){return y(this,void 0,void 0,(function*(){var d;const a=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);return o+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==t.sha256(o)?(a.salt=r.uniqueID(),a.password=t.sha256(s+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_get(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_delete(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r,o){return y(this,void 0,void 0,(function*(){const s=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(s){const t=yield this.token_new();return s.token=o.hash.encrypt(t),yield s.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return y(this,void 0,void 0,(function*(){var e;const t=r.uuidv4();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,o){return y(this,void 0,void 0,(function*(){const s=r.uniqueID();yield this._add({ctx:e,body:{password:t.sha256(o+s),salt:s}})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return y(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("Record not found");yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,o){return y(this,void 0,void 0,(function*(){const s=r.uniqueID();yield this._set({ctx:e,body:o?{password:t.sha256(o+s),salt:s}:{}})}))}},u([e.Post("/avatar"),e.Middleware("auth"),e.Middleware("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),c(0,e.Ctx()),c(1,e.Files()),c(2,D()),c(3,T()),g("design:type",Function),g("design:paramtypes",[e.Context,Array,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Delete("/avatar"),e.Middleware("auth"),c(0,e.Ctx()),c(1,D()),c(2,T()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar_delete",null),u([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:r.Validation.string().min(5).required(),newPassword:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,D()),c(4,T()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,exports.User,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,D()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("create"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Delete("/token/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,T()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_delete",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("update"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,T()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object,I]),g("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([e.Post(),e.Middleware("auth"),e.Middleware("create"),e.Middleware("validation",{name:r.Validation.string().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).required(),password:r.Validation.string().min(5).required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}),c(0,e.Ctx()),c(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("delete"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,D()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("update"),e.Middleware("validation",{name:r.Validation.string().empty(),email:r.Validation.string().email().empty(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).empty().filter(""),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}),c(0,e.Ctx()),c(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),g("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return exports.UserGroup}groups(e,t){return y(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,o,s){return y(this,void 0,void 0,(function*(){const i=yield exports.User.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:i.id},individualHooks:!0},s)),o){let e=0;yield r.sleep(1e3);for(let t=0;t<o.length;t++)e=yield exports.Group.count({where:{id:o[t]}}),e&&(yield exports.UserGroup.create({user_id:i.id,group_id:o[t]},Object.assign({},s)))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,D()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"groups",null),u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("update","users"),e.Middleware("validation",{groups:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),c(3,T()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,Object]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=I,exports.Config=E,exports.ControllerBase=U,exports.Env=x,exports.Logs=P,exports.Model=v,exports.ReqAudit=T,exports.ReqAuth=b,exports.ReqUser=D,exports.Token=O,exports.audit=w,exports.conn=h,exports.crt=f,exports.hooks=_,exports.key=C;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.0.
|
|
2
|
+
* @andrewcaires/api v4.0.4
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
7
|
import { Context, IStore, IUpload, Application as Application$1, IFile } from '@andrewcaires/express';
|
|
8
8
|
import { Hash } from '@andrewcaires/node';
|
|
9
|
-
import
|
|
10
|
-
import { EventEmitter, TypeObject, ValidationBase,
|
|
9
|
+
import { WebSocketServer } from 'ws';
|
|
10
|
+
import { TypeObjectAny, EventEmitter, TypeObject, ValidationBase, TypeObjectString } from '@andrewcaires/utils.js';
|
|
11
|
+
import { WhereOptions, Model as Model$2, CreateOptions, Attributes, FindOptions, UpdateOptions, ModelStatic } from 'sequelize';
|
|
11
12
|
import { Model as Model$1, Connection } from '@andrewcaires/sequelize';
|
|
12
|
-
import { Model as Model$2, CreateOptions, Attributes, FindOptions, UpdateOptions, ModelStatic, WhereOptions } from 'sequelize';
|
|
13
13
|
|
|
14
14
|
declare class Model extends Model$1 {
|
|
15
15
|
}
|
|
@@ -18,7 +18,7 @@ declare class Auth extends Model {
|
|
|
18
18
|
id: number;
|
|
19
19
|
secret: string;
|
|
20
20
|
logout: Date;
|
|
21
|
-
|
|
21
|
+
user_agent: string;
|
|
22
22
|
created_at: Date;
|
|
23
23
|
updated_at: Date;
|
|
24
24
|
deleted_at: Date;
|
|
@@ -37,23 +37,24 @@ declare class Register extends Model {
|
|
|
37
37
|
user: User;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
declare class
|
|
40
|
+
declare class Permission extends Model {
|
|
41
41
|
id: number;
|
|
42
42
|
name: string;
|
|
43
|
+
route: string;
|
|
43
44
|
description: string;
|
|
44
45
|
state: boolean;
|
|
45
46
|
created_at: Date;
|
|
46
47
|
updated_at: Date;
|
|
47
48
|
deleted_at: Date;
|
|
48
|
-
|
|
49
|
+
groups_permissions: Array<GroupPermission>;
|
|
49
50
|
}
|
|
50
51
|
|
|
51
|
-
declare class
|
|
52
|
+
declare class GroupPermission extends Model {
|
|
52
53
|
created_at: Date;
|
|
53
54
|
group_id: number;
|
|
54
55
|
group: Group;
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
permission_id: number;
|
|
57
|
+
permission: Permission;
|
|
57
58
|
}
|
|
58
59
|
|
|
59
60
|
declare class Group extends Model {
|
|
@@ -64,7 +65,7 @@ declare class Group extends Model {
|
|
|
64
65
|
created_at: Date;
|
|
65
66
|
updated_at: Date;
|
|
66
67
|
deleted_at: Date;
|
|
67
|
-
groups_routes: Array<
|
|
68
|
+
groups_routes: Array<GroupPermission>;
|
|
68
69
|
users_groups: Array<UserGroup>;
|
|
69
70
|
}
|
|
70
71
|
|
|
@@ -102,7 +103,10 @@ declare class Audit extends Model {
|
|
|
102
103
|
type: string;
|
|
103
104
|
model: string;
|
|
104
105
|
record: string;
|
|
105
|
-
|
|
106
|
+
user_ip: string;
|
|
107
|
+
user_agent: string;
|
|
108
|
+
data: TypeObjectAny;
|
|
109
|
+
previously: TypeObjectAny;
|
|
106
110
|
state: boolean;
|
|
107
111
|
created_at: Date;
|
|
108
112
|
updated_at: Date;
|
|
@@ -147,15 +151,18 @@ declare class Session extends Model {
|
|
|
147
151
|
}
|
|
148
152
|
|
|
149
153
|
declare abstract class ControllerBase extends EventEmitter {
|
|
150
|
-
auth(ctx: Context, key: string, token: string,
|
|
151
|
-
|
|
154
|
+
auth(ctx: Context, key: string, token: string, user_agent: string, app: Application): Promise<void>;
|
|
155
|
+
create(ctx: Context, name: string, user: User): Promise<void>;
|
|
156
|
+
delete(ctx: Context, name: string, user: User): Promise<void>;
|
|
152
157
|
error(error: any): void;
|
|
153
158
|
name(): string;
|
|
154
|
-
permission(ctx: Context,
|
|
159
|
+
permission(ctx: Context, route: string, user: User): Promise<void>;
|
|
160
|
+
permissions(user: User, where?: WhereOptions): Promise<void | Array<Permission>>;
|
|
155
161
|
read(ctx: Context, name: string, user: User): Promise<void>;
|
|
162
|
+
session(ctx: Context, user_agent: string, store: IStore): Promise<void>;
|
|
156
163
|
upload(ctx: Context, options: IUpload): void;
|
|
164
|
+
update(ctx: Context, name: string, user: User): Promise<void>;
|
|
157
165
|
validation(ctx: Context, options: TypeObject<ValidationBase>): Promise<void>;
|
|
158
|
-
write(ctx: Context, name: string, user: User): Promise<void>;
|
|
159
166
|
}
|
|
160
167
|
|
|
161
168
|
declare class Application extends Application$1 {
|
|
@@ -165,15 +172,9 @@ declare class Application extends Application$1 {
|
|
|
165
172
|
error(error: any, source?: string): void;
|
|
166
173
|
log(message: string, source?: string): void;
|
|
167
174
|
listen(): Promise<void>;
|
|
168
|
-
websocket():
|
|
175
|
+
websocket(): WebSocketServer | undefined;
|
|
169
176
|
}
|
|
170
177
|
|
|
171
|
-
declare const audit: {
|
|
172
|
-
afterCreate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
173
|
-
afterUpdate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
174
|
-
afterDestroy: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
175
|
-
};
|
|
176
|
-
|
|
177
178
|
declare class Config {
|
|
178
179
|
static all(): Promise<TypeObjectString>;
|
|
179
180
|
static del(key: string, user?: User): Promise<boolean>;
|
|
@@ -188,7 +189,6 @@ interface ArgumentsModelAdd<M extends Model$2<M>> {
|
|
|
188
189
|
ctx: Context;
|
|
189
190
|
options?: CreateOptions<Attributes<M>>;
|
|
190
191
|
body?: TypeObjectAny;
|
|
191
|
-
user?: User;
|
|
192
192
|
}
|
|
193
193
|
|
|
194
194
|
type CallbackModelAll<M> = (records: Array<M>) => Array<any> | Promise<Array<any>>;
|
|
@@ -203,7 +203,6 @@ interface ArgumentsModelAll<M extends Model$2<M>> {
|
|
|
203
203
|
interface ArgumentsModelDel<M extends Model$2<M>> {
|
|
204
204
|
ctx: Context;
|
|
205
205
|
options?: FindOptions<Attributes<M>>;
|
|
206
|
-
user?: User;
|
|
207
206
|
}
|
|
208
207
|
|
|
209
208
|
type CallbackModelGet<M> = (records: M) => any | Promise<any>;
|
|
@@ -219,7 +218,6 @@ interface ArgumentsModelSet<M extends Model$2<M>> {
|
|
|
219
218
|
ctx: Context;
|
|
220
219
|
options?: UpdateOptions<Attributes<M>>;
|
|
221
220
|
body?: TypeObjectAny;
|
|
222
|
-
user?: User;
|
|
223
221
|
}
|
|
224
222
|
|
|
225
223
|
interface IDatabaseOptions {
|
|
@@ -241,24 +239,22 @@ interface ITokenParameters {
|
|
|
241
239
|
|
|
242
240
|
interface ResultModelAll<M extends Model$2<M>> {
|
|
243
241
|
count: number;
|
|
244
|
-
limit: number;
|
|
245
|
-
offset: number;
|
|
246
242
|
records: Array<M>;
|
|
247
243
|
}
|
|
248
244
|
|
|
249
245
|
declare abstract class ModelController<M extends Model$2<M>> extends ControllerBase {
|
|
250
246
|
private _columns;
|
|
251
|
-
protected _add({ ctx, options, body
|
|
247
|
+
protected _add({ ctx, options, body }: ArgumentsModelAdd<M>): Promise<M | void>;
|
|
252
248
|
protected _all({ ctx, options, callback, scope }: ArgumentsModelAll<M>): Promise<ResultModelAll<M>>;
|
|
253
249
|
protected columns(): Array<string>;
|
|
254
|
-
protected _del({ ctx, options
|
|
250
|
+
protected _del({ ctx, options }: ArgumentsModelDel<M>): Promise<number>;
|
|
255
251
|
error(error: any): void;
|
|
256
252
|
protected _get({ ctx, options, callback, scope }: ArgumentsModelGet<M>): Promise<M | void>;
|
|
257
253
|
key(): string;
|
|
258
254
|
abstract model(): ModelStatic<M>;
|
|
259
255
|
name(): string;
|
|
260
256
|
scope(name?: string): ModelStatic<M>;
|
|
261
|
-
protected _set({ ctx, options, body
|
|
257
|
+
protected _set({ ctx, options, body }: ArgumentsModelSet<M>): Promise<boolean>;
|
|
262
258
|
}
|
|
263
259
|
|
|
264
260
|
declare class AuditsController extends ModelController<Audit> {
|
|
@@ -268,9 +264,9 @@ declare class AuditsController extends ModelController<Audit> {
|
|
|
268
264
|
}
|
|
269
265
|
|
|
270
266
|
declare class AuthController extends ControllerBase {
|
|
271
|
-
protected login(ctx: Context,
|
|
267
|
+
protected login(ctx: Context, user_agent: string, username: string, password: string, app: Application): Promise<void>;
|
|
272
268
|
protected logout(ctx: Context, auth: Auth, user: User, app: Application): Promise<void>;
|
|
273
|
-
protected renew(ctx: Context,
|
|
269
|
+
protected renew(ctx: Context, user_agent: string, old: string, app: Application): Promise<void>;
|
|
274
270
|
protected user(ctx: Context, user: User): Promise<void>;
|
|
275
271
|
}
|
|
276
272
|
|
|
@@ -291,27 +287,27 @@ declare class ForgotController extends ControllerBase {
|
|
|
291
287
|
|
|
292
288
|
declare abstract class CrudController<M extends Model$2<M>> extends ModelController<M> {
|
|
293
289
|
private _crud;
|
|
294
|
-
protected add(ctx: Context
|
|
290
|
+
protected add(ctx: Context): Promise<void>;
|
|
295
291
|
protected all(ctx: Context): Promise<void>;
|
|
296
|
-
|
|
297
|
-
protected del(ctx: Context
|
|
292
|
+
CrudCreate(): TypeObject<ValidationBase>;
|
|
293
|
+
protected del(ctx: Context): Promise<void>;
|
|
298
294
|
protected get(ctx: Context): Promise<void>;
|
|
299
|
-
protected set(ctx: Context
|
|
300
|
-
|
|
295
|
+
protected set(ctx: Context): Promise<void>;
|
|
296
|
+
CrudUpdate(): TypeObject<ValidationBase>;
|
|
301
297
|
protected validationAdd(ctx: Context): Promise<void>;
|
|
302
298
|
protected validationSet(ctx: Context): Promise<void>;
|
|
303
299
|
}
|
|
304
300
|
|
|
305
301
|
declare class GroupsController extends CrudController<Group> {
|
|
306
302
|
model(): typeof Group;
|
|
307
|
-
|
|
308
|
-
|
|
303
|
+
CrudCreate(): TypeObject<ValidationBase>;
|
|
304
|
+
CrudUpdate(): TypeObject<ValidationBase>;
|
|
309
305
|
}
|
|
310
306
|
|
|
311
|
-
declare class
|
|
312
|
-
model(): typeof
|
|
307
|
+
declare class GroupsPermissionsController extends ModelController<GroupPermission> {
|
|
308
|
+
model(): typeof GroupPermission;
|
|
313
309
|
protected all(ctx: Context, group_id: string): Promise<void>;
|
|
314
|
-
protected set(ctx: Context, id: string,
|
|
310
|
+
protected set(ctx: Context, id: string, permissions: Array<number>, audit: TypeObjectAny): Promise<void>;
|
|
315
311
|
}
|
|
316
312
|
|
|
317
313
|
declare class LogsController extends ModelController<Log> {
|
|
@@ -319,6 +315,12 @@ declare class LogsController extends ModelController<Log> {
|
|
|
319
315
|
protected all(ctx: Context, type: string, source: string): Promise<void>;
|
|
320
316
|
}
|
|
321
317
|
|
|
318
|
+
declare class PermissionsController extends CrudController<Permission> {
|
|
319
|
+
model(): typeof Permission;
|
|
320
|
+
CrudCreate(): TypeObject<ValidationBase>;
|
|
321
|
+
CrudUpdate(): TypeObject<ValidationBase>;
|
|
322
|
+
}
|
|
323
|
+
|
|
322
324
|
declare class RegisterController extends ControllerBase {
|
|
323
325
|
protected register(ctx: Context, body: TypeObjectAny, app: Application): Promise<void>;
|
|
324
326
|
protected confirm(ctx: Context, token: string, app: Application): Promise<void>;
|
|
@@ -326,33 +328,27 @@ declare class RegisterController extends ControllerBase {
|
|
|
326
328
|
private getId;
|
|
327
329
|
}
|
|
328
330
|
|
|
329
|
-
declare class RoutesController extends CrudController<Route> {
|
|
330
|
-
model(): typeof Route;
|
|
331
|
-
create(): TypeObject<ValidationBase>;
|
|
332
|
-
update(): TypeObject<ValidationBase>;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
331
|
declare class SetupController extends ControllerBase {
|
|
336
|
-
protected setup(ctx: Context): Promise<void>;
|
|
332
|
+
protected setup(ctx: Context, audit: TypeObjectAny): Promise<void>;
|
|
337
333
|
}
|
|
338
334
|
|
|
339
335
|
declare class UsersController extends ModelController<User> {
|
|
340
|
-
|
|
336
|
+
path: string;
|
|
341
337
|
model(): typeof User;
|
|
342
338
|
constructor();
|
|
343
339
|
protected avatar(ctx: Context, files: Array<IFile>, user: User, audit: TypeObjectAny): Promise<void>;
|
|
344
|
-
protected
|
|
340
|
+
protected avatar_delete(ctx: Context, user: User, audit: TypeObjectAny): Promise<void>;
|
|
345
341
|
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User, audit: TypeObjectAny): Promise<void>;
|
|
346
342
|
protected token(ctx: Context, user: User, app: Application): Promise<void>;
|
|
347
343
|
protected token_get(ctx: Context, id: string, app: Application): Promise<void>;
|
|
348
|
-
protected
|
|
344
|
+
protected token_delete(ctx: Context, id: string, audit: TypeObjectAny): Promise<void>;
|
|
349
345
|
protected token_renew(ctx: Context, id: string, audit: TypeObjectAny, app: Application): Promise<void>;
|
|
350
346
|
private token_new;
|
|
351
|
-
protected add(ctx: Context, password: string
|
|
347
|
+
protected add(ctx: Context, password: string): Promise<void>;
|
|
352
348
|
protected all(ctx: Context): Promise<void>;
|
|
353
349
|
protected del(ctx: Context, id: string, user: User): Promise<void>;
|
|
354
350
|
protected get(ctx: Context): Promise<void>;
|
|
355
|
-
protected set(ctx: Context, password: string
|
|
351
|
+
protected set(ctx: Context, password: string): Promise<void>;
|
|
356
352
|
}
|
|
357
353
|
|
|
358
354
|
declare class UsersGroupsController extends ModelController<UserGroup> {
|
|
@@ -381,12 +377,12 @@ declare class Env {
|
|
|
381
377
|
static readonly API_HTTP_PUBLIC: string;
|
|
382
378
|
static readonly API_HTTP_CROSS: boolean;
|
|
383
379
|
static readonly API_HTTP_HYBRID: boolean;
|
|
380
|
+
static readonly API_HTTP_NOTFOUND: string;
|
|
384
381
|
static readonly API_HTTP_REDIRECT: string;
|
|
385
382
|
static readonly API_KEY_HASH: string;
|
|
386
383
|
static readonly API_KEY_HEADER: string;
|
|
387
384
|
static readonly API_MODEL_LIMIT: number;
|
|
388
385
|
static readonly API_MODEL_LIMIT_MAX: number;
|
|
389
|
-
static readonly API_NOTFOUND_REDIRECT: string;
|
|
390
386
|
static readonly API_SLEEP_AUTH: number;
|
|
391
387
|
static readonly API_SLEEP_FORGOT: number;
|
|
392
388
|
static readonly API_SLEEP_REGISTRY: number;
|
|
@@ -410,6 +406,11 @@ declare class Env {
|
|
|
410
406
|
protected static getString(key: string, value: string): string;
|
|
411
407
|
}
|
|
412
408
|
|
|
409
|
+
declare const audit: (ctx: Context) => {
|
|
410
|
+
audit_user_ip: string;
|
|
411
|
+
audit_user_id: number | null;
|
|
412
|
+
audit_user_agent: string;
|
|
413
|
+
};
|
|
413
414
|
declare const ReqAudit: (key?: string) => ParameterDecorator;
|
|
414
415
|
|
|
415
416
|
declare const ReqAuth: (key?: string) => ParameterDecorator;
|
|
@@ -425,21 +426,21 @@ declare global {
|
|
|
425
426
|
}
|
|
426
427
|
}
|
|
427
428
|
|
|
429
|
+
declare const hooks: {
|
|
430
|
+
afterCreate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
431
|
+
afterUpdate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
432
|
+
afterDestroy: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
433
|
+
};
|
|
434
|
+
|
|
428
435
|
declare class Logs {
|
|
429
|
-
static write(message: string, source?: string,
|
|
430
|
-
static error(message: string, source?: string,
|
|
431
|
-
static info(message: string, source?: string,
|
|
432
|
-
static success(message: string, source?: string,
|
|
433
|
-
static warning(message: string, source?: string,
|
|
436
|
+
static write(message: string, source?: string, show?: boolean): Promise<void>;
|
|
437
|
+
static error(message: string, source?: string, show?: boolean): Promise<void>;
|
|
438
|
+
static info(message: string, source?: string, show?: boolean): Promise<void>;
|
|
439
|
+
static success(message: string, source?: string, show?: boolean): Promise<void>;
|
|
440
|
+
static warning(message: string, source?: string, show?: boolean): Promise<void>;
|
|
434
441
|
private static writeRaw;
|
|
435
442
|
}
|
|
436
443
|
|
|
437
|
-
declare class Permission {
|
|
438
|
-
static all(user: User, where?: WhereOptions): Promise<void | Array<Route>>;
|
|
439
|
-
static get(user: User): Promise<Array<string>>;
|
|
440
|
-
static is(user: User, name: string): Promise<boolean>;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
444
|
declare const crt: {
|
|
444
445
|
http: Buffer | undefined;
|
|
445
446
|
token: Buffer | undefined;
|
|
@@ -459,4 +460,4 @@ declare class Token {
|
|
|
459
460
|
private static verify;
|
|
460
461
|
}
|
|
461
462
|
|
|
462
|
-
export { Application, type ArgumentsModelAdd, type ArgumentsModelAll, type ArgumentsModelDel, type ArgumentsModelGet, type ArgumentsModelSet, Audit, AuditsController, Auth, AuthController, type CallbackModelAll, type CallbackModelGet, Config, Configs, ControllerBase, CrudController, Env, FilesController, Forgot, ForgotController, Group,
|
|
463
|
+
export { Application, type ArgumentsModelAdd, type ArgumentsModelAll, type ArgumentsModelDel, type ArgumentsModelGet, type ArgumentsModelSet, Audit, AuditsController, Auth, AuthController, type CallbackModelAll, type CallbackModelGet, Config, Configs, ControllerBase, CrudController, Env, FilesController, Forgot, ForgotController, Group, GroupPermission, GroupsController, GroupsPermissionsController, type IDatabaseOptions, type ITokenParameters, Log, Logs, LogsController, Model, ModelController, Permission, PermissionsController, Register, RegisterController, ReqAudit, ReqAuth, ReqUser, type ResultModelAll, Session, SetupController, Token, User, UserGroup, UsersController, UsersGroupsController, audit, conn, crt, hooks, key };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.0.
|
|
2
|
+
* @andrewcaires/api v4.0.4
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,App as n,Session as o,Argument as s,Upload as d,Context as a,Extends as u,Status as c,Get as l,Middleware as p,Query as y,Controller as g,Post as h,Body as v,Delete as _,Put as m,Params as f,Files as P}from"@andrewcaires/express";import{LogColor as I,Log as A,Hash as O,sha256 as E}from"@andrewcaires/node";import{toBool as S,parseMs as w,isObject as T,noop as b,loop as D,uuidv4 as R,sleep as k,EventEmitter as x,Validation as F,isString as N,isArray as j,isDef as q,uniqueID as L,isNull as B,forEachSeries as K}from"@andrewcaires/utils.js";import H from"ws";import{Connection as C,Model as U,Id as M,String as Y,FullDate as G,CreatedAt as z,UpdatedAt as W,DeletedAt as J,BelongsTo as X,Database as $,ModelName as V,Boolean as Z,Text as Q,HasMany as ee,Hooks as te,DateOnly as re,DefaultScope as ie,Scopes as ne,Integer as oe,BigInt as se}from"@andrewcaires/sequelize";import{config as de}from"dotenv";import{existsSync as ae,readFileSync as ue,statSync as ce,readdirSync as le,mkdirSync as pe,lstatSync as ye,rmSync as ge}from"fs";import{Store as he}from"express-session";import{Op as ve}from"sequelize";import{verify as _e,sign as me}from"jsonwebtoken";import{join as fe}from"path";function Pe(e,t,r,i){var n,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(s=(o<3?n(s):o>3?n(t,r,s):n(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}function Ie(e,t){return function(r,i){t(r,i,e)}}function Ae(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Oe(e,t,r,i){return new(r||(r=Promise))((function(n,o){function s(e){try{a(i.next(e))}catch(e){o(e)}}function d(e){try{a(i.throw(e))}catch(e){o(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,d)}a((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,de();class Ee{static getBool(e,t){return S(Ee.getString(e,t.toString()))}static getInt(e,t){return parseInt(Ee.getString(e,t.toString()))}static getMs(e,t){return w(Ee.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}Ee.API_CONSOLE_ERROR=Ee.getBool("API_CONSOLE_ERROR",!1),Ee.API_DEFAULT_PATH=Ee.getString("API_DEFAULT_PATH","/api"),Ee.API_DB_DATABASE=Ee.getString("API_DB_DATABASE",""),Ee.API_DB_HOST=Ee.getString("API_DB_HOST","127.0.0.1"),Ee.API_DB_PASSWORD=Ee.getString("API_DB_PASSWORD",""),Ee.API_DB_PORT=Ee.getInt("API_DB_PORT",3306),Ee.API_DB_TYPE=Ee.getString("API_DB_TYPE",""),Ee.API_DB_USERNAME=Ee.getString("API_DB_USERNAME","root"),Ee.API_DB_LOG=Ee.getBool("API_DB_LOG",!1),Ee.API_DB_AUDIT=Ee.getBool("API_DB_AUDIT",!0),Ee.API_DB_PREFIX=Ee.getString("API_DB_PREFIX",""),Ee.API_DB_TIMEZONE=Ee.getString("API_DB_TIMEZONE","+00:00"),Ee.API_HTTP_CRT=Ee.getString("API_HTTP_CRT",""),Ee.API_HTTP_KEY=Ee.getString("API_HTTP_KEY",""),Ee.API_HTTP_PORT=Ee.getInt("API_HTTP_PORT",3e3),Ee.API_HTTP_PUBLIC=Ee.getString("API_HTTP_PUBLIC",""),Ee.API_HTTP_CROSS=Ee.getBool("API_HTTP_CROSS",!1),Ee.API_HTTP_HYBRID=Ee.getBool("API_HTTP_HYBRID",!1),Ee.API_HTTP_REDIRECT=Ee.getString("API_HTTP_REDIRECT",""),Ee.API_KEY_HASH=Ee.getString("API_KEY_HASH",""),Ee.API_KEY_HEADER=Ee.getString("API_KEY_HEADER","api_key"),Ee.API_MODEL_LIMIT=Ee.getInt("API_MODEL_LIMIT",10),Ee.API_MODEL_LIMIT_MAX=Ee.getInt("API_MODEL_LIMIT_MAX",500),Ee.API_NOTFOUND_REDIRECT=Ee.getString("API_NOTFOUND_REDIRECT",""),Ee.API_SLEEP_AUTH=Ee.getMs("API_SLEEP_AUTH","2s"),Ee.API_SLEEP_FORGOT=Ee.getMs("API_SLEEP_FORGOT","5s"),Ee.API_SLEEP_REGISTRY=Ee.getMs("API_SLEEP_REGISTRY","5s"),Ee.API_SESSION_NAME=Ee.getString("API_SESSION_NAME","session.id"),Ee.API_SESSION_LIFETIME=Ee.getMs("API_SESSION_LIFETIME","1d"),Ee.API_SESSION_SECRET=Ee.getString("API_SESSION_SECRET","yoursecret"),Ee.API_TOKEN_CRT=Ee.getString("API_TOKEN_CRT",""),Ee.API_TOKEN_KEY=Ee.getString("API_TOKEN_KEY",""),Ee.API_TOKEN_FORGOT=Ee.getMs("API_TOKEN_LIFETIME","1d"),Ee.API_TOKEN_HEADER=Ee.getString("API_TOKEN_HEADER","authorization"),Ee.API_TOKEN_LIFETIME=Ee.getMs("API_TOKEN_LIFETIME","1d"),Ee.API_TOKEN_RENEW=Ee.getMs("API_TOKEN_RENEW","1d"),Ee.API_UPLOAD_COUNT=Ee.getInt("API_UPLOAD_COUNT",1),Ee.API_UPLOAD_FIELD=Ee.getString("API_UPLOAD_FIELD","upload"),Ee.API_UPLOAD_SIZE=Ee.getInt("API_UPLOAD_SIZE",2),Ee.API_UPLOAD_TEMP=Ee.getString("API_UPLOAD_TEMP","./temp"),Ee.API_WEBSOCKET_START=Ee.getBool("API_WEBSOCKET_START",!1);const Se=new C({type:Ee.API_DB_TYPE,database:Ee.API_DB_DATABASE,username:Ee.API_DB_USERNAME,password:Ee.API_DB_PASSWORD,hostname:Ee.API_DB_HOST,hostport:Ee.API_DB_PORT,logging:Ee.API_DB_LOG,prefix:Ee.API_DB_PREFIX});class we extends U{}const Te={afterCreate:(e,t)=>Oe(void 0,void 0,void 0,(function*(){var r,i,n;if(!Ee.API_DB_AUDIT)return;const o=T(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield Fe.create({type:"CREATE",model:null!==(i=null==o?void 0:o.getTableName())&&void 0!==i?i:null,record:s?e.getDataValue(s):null,data:JSON.stringify(e.toJSON()),state:!0,user_id:null!==(n=null==t?void 0:t.user_id)&&void 0!==n?n:null}).catch(b)})),afterUpdate:(e,t)=>Oe(void 0,void 0,void 0,(function*(){var r,i,n;if(!Ee.API_DB_AUDIT)return;const o=T(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null,d={},a=e.changed();a&&a.forEach((t=>d[t]=e.getDataValue(t))),yield Fe.create({type:"UPDATE",model:null!==(i=null==o?void 0:o.getTableName())&&void 0!==i?i:null,record:s?e.getDataValue(s):null,data:JSON.stringify({before:e.previous(),after:d}),state:!0,user_id:null!==(n=null==t?void 0:t.user_id)&&void 0!==n?n:null}).catch(b)})),afterDestroy:(e,t)=>Oe(void 0,void 0,void 0,(function*(){var r,i,n;if(!Ee.API_DB_AUDIT)return;const o=T(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield Fe.create({type:"DELETE",model:null!==(i=null==o?void 0:o.getTableName())&&void 0!==i?i:null,record:s?e.getDataValue(s):null,data:JSON.stringify(e.toJSON()),state:!0,user_id:null!==(n=null==t?void 0:t.user_id)&&void 0!==n?n:null}).catch(b)}))};let be=class extends we{};Pe([M(),Ae("design:type",Number)],be.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],be.prototype,"secret",void 0),Pe([G(),Ae("design:type",Date)],be.prototype,"logout",void 0),Pe([Y(),Ae("design:type",Y)],be.prototype,"useragent",void 0),Pe([z,Ae("design:type",Date)],be.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],be.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],be.prototype,"deleted_at",void 0),Pe([X((()=>xe)),Ae("design:type",Number)],be.prototype,"user_id",void 0),be=Pe([$(Se),V("auth")],be);let De=class extends we{};Pe([M(),Ae("design:type",Number)],De.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],De.prototype,"token",void 0),Pe([Z(),Ae("design:type",Z)],De.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],De.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],De.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],De.prototype,"deleted_at",void 0),Pe([X((()=>xe)),Ae("design:type",Number)],De.prototype,"user_id",void 0),De=Pe([$(Se),V("register")],De);let Re=class extends we{};Pe([M(),Ae("design:type",Number)],Re.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],Re.prototype,"name",void 0),Pe([Q(),Ae("design:type",Y)],Re.prototype,"description",void 0),Pe([Z(),Ae("design:type",Z)],Re.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],Re.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],Re.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],Re.prototype,"deleted_at",void 0),Pe([ee((()=>ke),"group_id"),Ae("design:type",Array)],Re.prototype,"groups_routes",void 0),Pe([ee((()=>ke),"group_id"),Ae("design:type",Array)],Re.prototype,"users_groups",void 0),Re=Pe([$(Se),V("group"),te(Te)],Re);let ke=class extends we{};Pe([z,Ae("design:type",Date)],ke.prototype,"created_at",void 0),Pe([X((()=>Re)),Ae("design:type",Number)],ke.prototype,"group_id",void 0),Pe([X((()=>xe)),Ae("design:type",Number)],ke.prototype,"user_id",void 0),ke=Pe([$(Se),V("users_groups"),te(Te)],ke);let xe=class extends we{};Pe([M(),Ae("design:type",Number)],xe.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"name",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"email",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"username",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"password",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"salt",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"token",void 0),Pe([Y(),Ae("design:type",Y)],xe.prototype,"avatar",void 0),Pe([re(),Ae("design:type",Y)],xe.prototype,"date",void 0),Pe([Q(),Ae("design:type",Y)],xe.prototype,"description",void 0),Pe([Z(),Ae("design:type",Z)],xe.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],xe.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],xe.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],xe.prototype,"deleted_at",void 0),Pe([ee((()=>Fe),"user_id"),Ae("design:type",Array)],xe.prototype,"audits",void 0),Pe([ee((()=>be),"user_id"),Ae("design:type",Array)],xe.prototype,"auths",void 0),Pe([ee((()=>De),"user_id"),Ae("design:type",Array)],xe.prototype,"registers",void 0),Pe([ee((()=>ke),"user_id"),Ae("design:type",Array)],xe.prototype,"users_groups",void 0),xe=Pe([$(Se),V("user"),ie({attributes:{exclude:["password","salt","token"]}}),ne({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),te(Te)],xe);let Fe=class extends we{};Pe([M(),Ae("design:type",Number)],Fe.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],Fe.prototype,"type",void 0),Pe([Y(),Ae("design:type",Y)],Fe.prototype,"model",void 0),Pe([oe(),Ae("design:type",Y)],Fe.prototype,"record",void 0),Pe([Q(),Ae("design:type",Y)],Fe.prototype,"data",void 0),Pe([Z(),Ae("design:type",Z)],Fe.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],Fe.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],Fe.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],Fe.prototype,"deleted_at",void 0),Pe([X((()=>xe)),Ae("design:type",Number)],Fe.prototype,"user_id",void 0),Fe=Pe([$(Se),V("audit")],Fe);let Ne=class extends we{};Pe([Y(),Ae("design:type",Y)],Ne.prototype,"key",void 0),Pe([Y(),Ae("design:type",Y)],Ne.prototype,"value",void 0),Pe([z,Ae("design:type",Date)],Ne.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],Ne.prototype,"updated_at",void 0),Ne=Pe([$(Se),V("configs"),te(Te)],Ne);let je=class extends we{};Pe([M(),Ae("design:type",Number)],je.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],je.prototype,"token",void 0),Pe([se(),Ae("design:type",Number)],je.prototype,"timestamp",void 0),Pe([Z(),Ae("design:type",Z)],je.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],je.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],je.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],je.prototype,"deleted_at",void 0),Pe([X((()=>xe)),Ae("design:type",Number)],je.prototype,"user_id",void 0),je=Pe([$(Se),V("forgot")],je);let qe=class extends we{};Pe([M(),Ae("design:type",Number)],qe.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],qe.prototype,"name",void 0),Pe([Q(),Ae("design:type",Y)],qe.prototype,"description",void 0),Pe([Z(),Ae("design:type",Z)],qe.prototype,"state",void 0),Pe([z,Ae("design:type",Date)],qe.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],qe.prototype,"updated_at",void 0),Pe([J,Ae("design:type",Date)],qe.prototype,"deleted_at",void 0),Pe([ee((()=>Le),"route_id"),Ae("design:type",Array)],qe.prototype,"groups_routes",void 0),qe=Pe([$(Se),V("route"),te(Te)],qe);let Le=class extends we{};Pe([z,Ae("design:type",Date)],Le.prototype,"created_at",void 0),Pe([X((()=>Re)),Ae("design:type",Number)],Le.prototype,"group_id",void 0),Pe([X((()=>qe)),Ae("design:type",Number)],Le.prototype,"route_id",void 0),Le=Pe([$(Se),V("groups_routes"),te(Te)],Le);let Be=class extends we{};Pe([M(),Ae("design:type",Number)],Be.prototype,"id",void 0),Pe([Y(),Ae("design:type",Y)],Be.prototype,"type",void 0),Pe([Y(),Ae("design:type",Y)],Be.prototype,"source",void 0),Pe([Q(),Ae("design:type",Y)],Be.prototype,"message",void 0),Pe([z,Ae("design:type",Date)],Be.prototype,"created_at",void 0),Be=Pe([$(Se),V("log")],Be);let Ke=class extends we{};Pe([Y(),Ae("design:type",Y)],Ke.prototype,"session",void 0),Pe([Q(),Ae("design:type",Y)],Ke.prototype,"json",void 0),Pe([se(),Ae("design:type",Number)],Ke.prototype,"expired",void 0),Pe([z,Ae("design:type",Date)],Ke.prototype,"created_at",void 0),Pe([W,Ae("design:type",Date)],Ke.prototype,"updated_at",void 0),Ke=Pe([$(Se),V("session")],Ke);class He{static write(e,t,r){return Oe(this,void 0,void 0,(function*(){yield He.writeRaw(I.White,"",e,t,r)}))}static error(e,t,r){return Oe(this,void 0,void 0,(function*(){yield He.writeRaw(I.Red,"error",e,t,r)}))}static info(e,t,r){return Oe(this,void 0,void 0,(function*(){yield He.writeRaw(I.Cyan,"info",e,t,r)}))}static success(e,t,r){return Oe(this,void 0,void 0,(function*(){yield He.writeRaw(I.Green,"success",e,t,r)}))}static warning(e,t,r){return Oe(this,void 0,void 0,(function*(){yield He.writeRaw(I.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return Oe(this,void 0,void 0,(function*(){n&&A.console(e,t,r),Se&&(yield Be.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Ce=e=>ae(e)?ue(e):void 0,Ue={http:Ce(Ee.API_HTTP_CRT),token:Ce(Ee.API_TOKEN_CRT)},Me={http:Ce(Ee.API_HTTP_KEY),token:Ce(Ee.API_TOKEN_KEY)};class Ye extends he{constructor(){super(),this.all=e=>Oe(this,void 0,void 0,(function*(){e=e||b;const t=yield Ke.findAll({attributes:["session"],where:{expired:{[ve.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>Oe(this,void 0,void 0,(function*(){yield Ke.destroy().catch(b),e&&e()})),this.destroy=(e,t)=>Oe(this,void 0,void 0,(function*(){yield Ke.destroy({where:{session:e}}).catch(b),t&&t()})),this.expired=()=>Oe(this,void 0,void 0,(function*(){yield Ke.destroy({where:{expired:{[ve.lt]:Date.now()}}}).catch(b)})),this.get=(e,t)=>Oe(this,void 0,void 0,(function*(){t=t||b;const r=yield Ke.findOne({where:{session:e,expired:{[ve.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(r){const e=JSON.parse(r.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield r.destroy().catch(b),void t(null)}t(null,e)}else t(null)})),this.length=e=>Oe(this,void 0,void 0,(function*(){e&&e(null,(yield Ke.count().catch(b))||0)})),this.set=(e,t,r)=>Oe(this,void 0,void 0,(function*(){r=r||b;const i=Date.now()+Ee.API_SESSION_LIFETIME,n=JSON.stringify(t),[o,s]=(yield Ke.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(b))||[];o&&(s||(o.json=n,o.expired=i,yield o.save().catch(b))),r()})),this.loop=D(this.expired,3e4),this.loop.start()}}class Ge{static create(e){return Oe(this,void 0,void 0,(function*(){if(!Me.token)return{error:"Key not found"};const{id:t}=e,r=R(),i=yield be.create({secret:r,user_id:t}).catch(Ge.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:me({id:t,secret:r},Me.token,Ge.options())}}))}static destroy(e){return Oe(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){He.error(e.message,"api.token",Ee.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:Ee.API_TOKEN_LIFETIME+"ms"}}static renew(e){return Oe(this,void 0,void 0,(function*(){if(!Me.token)return{error:"Key not found"};const{error:t,decode:r}=Ge.verify(e,Ee.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield xe.findOne({where:{id:e,state:!0}}).catch(Ge.error);if(r){const i=yield be.findOne({where:{secret:t,user_id:r.id}}).catch(Ge.error);if(i&&!i.logout){i.secret=R(),yield i.save().catch(Ge.error);return{auth:i,token:me({id:e,secret:i.secret},Me.token,Ge.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return Oe(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield xe.findOne({where:{token:t,state:!0}}).catch(Ge.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield be.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(Ge.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:n}=Ge.verify(t);if(i)return{error:i};if(n){const{id:e,secret:t}=n;if(e&&t){const r=yield xe.findOne({where:{id:e,state:!0}}).catch(Ge.error);if(r){const e=yield be.findOne({where:{secret:t,user_id:r.id}}).catch(Ge.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ue.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:_e(e,Ue.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class ze extends e{constructor(e){super(e,{cert:Ue.http,cross:Ee.API_HTTP_CROSS,hybrid:Ee.API_HTTP_HYBRID,key:Me.http,notfound:Ee.API_NOTFOUND_REDIRECT,path:Ee.API_DEFAULT_PATH,port:Ee.API_HTTP_PORT,public:Ee.API_HTTP_PUBLIC,redirect:Ee.API_HTTP_REDIRECT,session:{store:new Ye,name:Ee.API_SESSION_NAME,secret:Ee.API_SESSION_SECRET,cookie:{maxAge:Ee.API_SESSION_LIFETIME},genid:R}}),this.hash=new O(Ee.API_KEY_HASH)}error(e,t){He.error(e.message,t,Ee.API_CONSOLE_ERROR)}log(e,t){He.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Oe(this,void 0,void 0,(function*(){yield Se.sync(),yield e.listen.call(this),Ee.API_WEBSOCKET_START&&this.server&&(this._webSocket=new H.Server({server:this.server,verifyClient:(e,t)=>t(Ee.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>Oe(this,void 0,void 0,(function*(){t.url||(t.url="");const r=t.url.length<=1?"":t.url.replace(/\//g,".");let i;e.on("message",(n=>Oe(this,void 0,void 0,(function*(){if(i)try{const o=JSON.parse(n);this.emit("ws.message"+r,{data:o,message:n,req:t,user:i,ws:e})}catch(o){this.emit("ws.message"+r,{message:n,req:t,user:i,ws:e})}else{const{user:o}=yield Ge.user("",n.toString(),this);o&&(i=o,this.emit("ws.connection"+r,{req:t,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+r,{user:i,ws:e})})),yield k(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class We{static all(){return Oe(this,void 0,void 0,(function*(){const e=yield Ne.findAll().catch(We.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return Oe(this,void 0,void 0,(function*(){var r;const i=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield Ne.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:i})).catch(We.error))||0)>0}))}static error(e){He.error(e.message,"api.config",Ee.API_CONSOLE_ERROR)}static get(e){return Oe(this,arguments,void 0,(function*(e,t=""){const[r]=(yield Ne.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(We.error))||[];return r?r.value:t}))}static set(e,t,r){return Oe(this,void 0,void 0,(function*(){var i;const n=null!==(i=null==r?void 0:r.id)&&void 0!==i?i:null,[o]=(yield Ne.findOrCreate(Object.assign({where:{key:e}},{user_id:n})).catch(We.error))||[];o&&(o.value=t,yield o.save().catch(We.error))}))}}const Je=t((({ctx:e})=>{var t,r,i;return{user_id:null!==(i=null===(r=null===(t=e.req)||void 0===t?void 0:t.user)||void 0===r?void 0:r.id)&&void 0!==i?i:null}})),Xe=t((({ctx:e})=>e.req.auth)),$e=t((({ctx:e})=>e.req.user));class Ve{static all(e,t){return Oe(this,void 0,void 0,(function*(){return yield qe.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:Le,required:!0,include:[{model:Re,required:!0,where:{state:!0},include:[{model:ke,required:!0,where:{user_id:e.id}}]}]}]}).catch((e=>{He.error(e.message,"api.permission",Ee.API_CONSOLE_ERROR)}))}))}static get(e){return Oe(this,void 0,void 0,(function*(){const t=yield Ve.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return Oe(this,void 0,void 0,(function*(){const r=yield Ve.all(e,{name:t});return!!r&&r.length>0}))}}class Ze extends x{auth(e,t,r,i,n){return Oe(this,void 0,void 0,(function*(){const{auth:o,error:s,user:d}=yield Ge.user(t,r,n);return s?e.error(s):o&&d?o.useragent&&o.useragent!=i?e.error("Invalid token"):(e.req.auth=o,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,r){return Oe(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(b):(r.useragent=t,r.save(b))),e.next()}))}error(e){He.error(e.message,"api.controller",Ee.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return Oe(this,void 0,void 0,(function*(){return r?(yield Ve.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return Oe(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){t.path||(t.path=Ee.API_UPLOAD_TEMP),t.size||(t.size=Ee.API_UPLOAD_SIZE),t.field||(t.field=Ee.API_UPLOAD_FIELD),d.middleware(e,t)}validation(e,t){return Oe(this,void 0,void 0,(function*(){const{error:r,value:i}=yield F.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=i,e.next()}))}write(e,t,r){return Oe(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}Pe([Ie(0,r()),Ie(1,i(Ee.API_KEY_HEADER)),Ie(2,i(Ee.API_TOKEN_HEADER)),Ie(3,i("user-agent")),Ie(4,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,String,ze]),Ae("design:returntype",Promise)],Ze.prototype,"auth",null),Pe([Ie(0,r()),Ie(1,i("user-agent")),Ie(2,o()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object]),Ae("design:returntype",Promise)],Ze.prototype,"session",null),Pe([Ie(0,r()),Ie(1,s()),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],Ze.prototype,"permission",null),Pe([Ie(0,r()),Ie(1,s()),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],Ze.prototype,"read",null),Pe([Ie(0,r()),Ie(1,s()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object]),Ae("design:returntype",void 0)],Ze.prototype,"upload",null),Pe([Ie(0,r()),Ie(1,s()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object]),Ae("design:returntype",Promise)],Ze.prototype,"validation",null),Pe([Ie(0,r()),Ie(1,s()),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],Ze.prototype,"write",null);let Qe=class extends Ze{constructor(){super(...arguments),this._columns=[]}_add(e){return Oe(this,arguments,void 0,(function*({ctx:e,options:t,body:r,user:i}){var n;const o=null!==(n=null==i?void 0:i.id)&&void 0!==n?n:null,s=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{user_id:o})).catch(this.error);if(s){const t=this.key();return e.prepare(c.OK,{[t]:s.getDataValue(t)}),s}e.error("Internal Server Error")}))}_all(e){return Oe(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){var n,o,s,d,a,u;const l=this.scope(i),p=Object.assign({},t||{});p.where=Object.assign({},p.where||{});const y=e.req.query.limit,g=N(y)?parseInt(y):Ee.API_MODEL_LIMIT;p.limit=g>=0?Math.min(g,Ee.API_MODEL_LIMIT_MAX):void 0;const h=e.req.query.offset;if(N(h)){const e=h?parseInt(h):0;p.offset=e>0?e:void 0}const v=[],_=this.columns(),m=e=>_.indexOf(e)>=0,f=null===(n=e.req.query.asc)||void 0===n?void 0:n.toString();f&&f.length&&v.push(...f.split(",").filter(m).map((e=>[e,"ASC"])));const P=null===(o=e.req.query.desc)||void 0===o?void 0:o.toString();P&&P.length&&v.push(...P.split(",").filter(m).map((e=>[e,"DESC"]))),v.length&&(p.order=v);const I=[],A=null===(s=e.req.query.search)||void 0===s?void 0:s.toString();(j(p.attributes)?p.attributes:_).filter(N).forEach((t=>{var r;if(A&&A.length&&I.push({[t]:{[ve.like]:`%${A}%`}}),"search_"+t in e.req.query){const i=null===(r=e.req.query["search_"+t])||void 0===r?void 0:r.toString();i&&i.length&&I.push({[t]:{[ve.like]:`%${i}%`}})}})),I.length&&(p.where=Object.assign(Object.assign({},p.where),{[ve.or]:[...I]}));const O=null!==(d=yield l.count(Object.assign(Object.assign({},p),{col:_[0]})).catch(this.error))&&void 0!==d?d:0,E=yield l.findAll(p).catch(this.error),S={count:O,limit:null!==(a=p.limit)&&void 0!==a?a:-1,offset:null!==(u=p.offset)&&void 0!==u?u:0};return E?(e.prepare(c.OK,Object.assign(Object.assign({},S),{records:r?yield r(E):E})),Object.assign(Object.assign({},S),{records:E})):(e.error("Internal Server Error"),Object.assign(Object.assign({},S),{records:[]}))}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return Oe(this,arguments,void 0,(function*({ctx:e,options:t,user:r}){var i;const n=this.key(),{[n]:o}=e.req.params;if(!o)return e.error("Internal Server Error"),0;const s=null!==(i=null==r?void 0:r.id)&&void 0!==i?i:null,d=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:o}),individualHooks:!0}),{user_id:s})).catch(this.error);return d?(e.success("OK"),d):(e.notFound("Record not found"),0)}))}error(e){e.sql?He.error(e.message+"\n"+e.sql,"api.controller.sql",Ee.API_CONSOLE_ERROR):super.error(e)}_get(e){return Oe(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){const n=this.key(),{[n]:o}=e.req.params,s=yield this.scope(i).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:o})})).catch(this.error);return s?(e.prepare(c.OK,r?yield r(s):s.toJSON()),s):null===s?e.notFound("Record not found"):void e.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return Oe(this,arguments,void 0,(function*({ctx:e,options:t,body:r,user:i}){var n,o;const s=this.key(),{[s]:d}=e.req.params,a=null!==(n=null==i?void 0:i.id)&&void 0!==n?n:null,[u]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:d}),individualHooks:!0}),{user_id:a})).catch(this.error))&&void 0!==o?o:[];return u?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};Qe=Pe([u(Ze)],Qe);let et=class extends Qe{model(){return Fe}all(e,t,r){return Oe(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data"]},where:i,order:[["created_at","DESC"]]}})}))}get(e){return Oe(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}};Pe([l(),p("auth"),p("read"),Ie(0,r()),Ie(1,y("type")),Ie(2,y("table")),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String]),Ae("design:returntype",Promise)],et.prototype,"all",null),Pe([l("/:id"),p("auth"),p("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],et.prototype,"get",null),et=Pe([g("/audits"),u(Qe)],et);let tt=class extends Ze{login(e,t,r,i,n){return Oe(this,void 0,void 0,(function*(){var o;yield k(Ee.API_SLEEP_AUTH);const s=yield xe.scope("password").findOne({where:{[ve.or]:[{email:r},{username:r}]}}).catch(this.error);if(i+=null!==(o=null==s?void 0:s.salt)&&void 0!==o?o:"",!s||s.password!=E(i))return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield De.findOne({where:{state:!0,user_id:s.id}}).catch(this.error);if(d)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:d,user:s}),void this.emit("auth.activation",{ctx:e,register:d,user:s});if(!s.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:s}),void this.emit("auth.failure",{ctx:e,user:s});const{auth:a,error:u,token:c}=yield Ge.create(s);return u?(e.error(u),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&c?(a.useragent=t,yield a.save().catch(this.error),e.json({token:c}),n.emit("auth.login",{auth:a,ctx:e,user:s}),void this.emit("auth.login",{auth:a,ctx:e,user:s})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return Oe(this,void 0,void 0,(function*(){if(yield Ge.destroy(t))return e.success("Disconcerted"),i.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,i){return Oe(this,void 0,void 0,(function*(){const{auth:n,error:o,token:s}=yield Ge.renew(r);return o?e.error(o):n?(n.useragent=t,yield n.save().catch(this.error),e.json({token:s}),i.emit("auth.renew",{auth:n,ctx:e}),void this.emit("auth.renew",{auth:n,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return Oe(this,void 0,void 0,(function*(){const r=yield Ve.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};Pe([h("/login"),p("validation",{username:F.string().min(3).required(),password:F.string().min(5).required()}),Ie(0,r()),Ie(1,i("user-agent")),Ie(2,v("username")),Ie(3,v("password")),Ie(4,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,String,ze]),Ae("design:returntype",Promise)],tt.prototype,"login",null),Pe([l("/logout"),p("auth"),Ie(0,r()),Ie(1,Xe()),Ie(2,$e()),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,be,xe,ze]),Ae("design:returntype",Promise)],tt.prototype,"logout",null),Pe([h("/renew"),p("validation",{token:F.string().required()}),Ie(0,r()),Ie(1,i("user-agent")),Ie(2,v("token")),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,ze]),Ae("design:returntype",Promise)],tt.prototype,"renew",null),Pe([l(),p("auth"),Ie(0,r()),Ie(1,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe]),Ae("design:returntype",Promise)],tt.prototype,"user",null),tt=Pe([g("/auth"),u(Ze)],tt);let rt=class extends Ze{directory(){return Ee.API_HTTP_PUBLIC||"./"}files(e){return Oe(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=fe(this.directory(),t);if(!ae(r)||!ce(r).isDirectory())return e.notFound("Path not Found");let i=[];return i=le(r),i=i.map((e=>this.info(fe(r,e)))),i=i.filter(q),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r){return Oe(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!ae(e))return null;const t=ce(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const i=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:i?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:i,symlink:t.isSymbolicLink()}}name(){return"files"}};Pe([l("/path/?*"),p("auth"),p("access","list"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],rt.prototype,"files",null),Pe([Ie(0,r()),Ie(1,s()),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],rt.prototype,"access",null),rt=Pe([g("/files"),u(Ze)],rt);let it=class extends Ze{check(e,t){return Oe(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("User not found");r.token=L(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return Oe(this,void 0,void 0,(function*(){yield k(Ee.API_SLEEP_FORGOT);const i=t,n=yield xe.findOne({where:{[ve.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const o=L(),s=Date.now()+6e4*Ee.API_TOKEN_FORGOT,d=yield je.create({token:o,timestamp:s,state:!0,user_id:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})}))}reset(e,t,r,i){return Oe(this,void 0,void 0,(function*(){const n=yield this.find(t);if(!n)return e.notFound("User not found");n.state=!1,yield n.save().catch(this.error),n.user.password=E(r),yield n.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})}))}find(e){return Oe(this,void 0,void 0,(function*(){return yield je.findOne({where:{token:e,state:!0},include:[{model:xe,required:!0}]}).catch(this.error)}))}};Pe([l("/check"),p("validation",{token:F.string().required()}),Ie(0,r()),Ie(1,v("token")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],it.prototype,"check",null),Pe([h(),p("validation",{username:F.string().min(4).required()}),Ie(0,r()),Ie(1,v("username")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,ze]),Ae("design:returntype",Promise)],it.prototype,"forgot",null),Pe([h("/reset"),p("validation",{token:F.string().required(),password:F.string().min(5).required()}),Ie(0,r()),Ie(1,v("token")),Ie(2,v("password")),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,ze]),Ae("design:returntype",Promise)],it.prototype,"reset",null),it=Pe([g("/forgot"),u(Ze)],it);let nt=class extends Qe{constructor(){super(...arguments),this._crud={}}add(e,t){return Oe(this,void 0,void 0,(function*(){yield this._add({ctx:e,user:t})}))}all(e){return Oe(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}create(){return this._crud}del(e,t){return Oe(this,void 0,void 0,(function*(){yield this._del({ctx:e,user:t})}))}get(e){return Oe(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return Oe(this,void 0,void 0,(function*(){yield this._set({ctx:e,user:t})}))}update(){return this._crud}validationAdd(e){return Oe(this,void 0,void 0,(function*(){const t=this.create();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}validationSet(e){return Oe(this,void 0,void 0,(function*(){const t=this.update();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}};Pe([h(),p("auth"),p("write"),p("validationAdd"),Ie(0,r()),Ie(1,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe]),Ae("design:returntype",Promise)],nt.prototype,"add",null),Pe([l(),p("auth"),p("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],nt.prototype,"all",null),Pe([_("/:id"),p("auth"),p("write"),Ie(0,r()),Ie(1,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe]),Ae("design:returntype",Promise)],nt.prototype,"del",null),Pe([l("/:id"),p("auth"),p("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],nt.prototype,"get",null),Pe([m("/:id"),p("auth"),p("write"),p("validationSet"),Ie(0,r()),Ie(1,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe]),Ae("design:returntype",Promise)],nt.prototype,"set",null),Pe([Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],nt.prototype,"validationAdd",null),Pe([Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],nt.prototype,"validationSet",null),nt=Pe([u(Qe)],nt);let ot=class extends nt{model(){return Re}create(){return{name:F.string().required(),description:F.string().empty(""),state:F.boolean().parse().required()}}update(){return{name:F.string().empty(),description:F.string().empty(),state:F.boolean().parse().empty()}}};ot=Pe([g("/groups"),u(nt)],ot);let st=class extends Qe{model(){return Le}all(e,t){return Oe(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:qe,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r,i){return Oe(this,void 0,void 0,(function*(){const n=yield Re.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){const t=n.id;if(yield Le.destroy(Object.assign({where:{group_id:t},individualHooks:!0},i)),r){let e=0;yield k(1e3);for(let n=0;n<r.length;n++)e=yield qe.count({where:{id:r[n]}}),e&&(yield Le.create({group_id:t,route_id:r[n]},Object.assign({},i)))}return e.success("OK")}if(B(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Pe([l("/:id/routes"),p("auth"),p("read","groups"),Ie(0,r()),Ie(1,f("id")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],st.prototype,"all",null),Pe([m("/:id/routes"),p("auth"),p("write","groups"),p("validation",{routes:F.array(F.number().parse())}),Ie(0,r()),Ie(1,f("id")),Ie(2,v("routes")),Ie(3,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Array,Object]),Ae("design:returntype",Promise)],st.prototype,"set",null),st=Pe([g("/groups"),u(Qe)],st);let dt=class extends Qe{model(){return Be}all(e,t,r){return Oe(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.source=r),yield this._all({ctx:e,options:{where:i,order:[["created_at","DESC"]]}})}))}};Pe([l(),p("auth"),p("read"),Ie(0,r()),Ie(1,y("type")),Ie(2,y("source")),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String]),Ae("design:returntype",Promise)],dt.prototype,"all",null),dt=Pe([g("/logs"),u(Qe)],dt);let at=class extends Ze{register(e,t,r){return Oe(this,void 0,void 0,(function*(){yield k(Ee.API_SLEEP_REGISTRY);const{name:i,date:n,email:o,username:s,password:d,confirm:a}=t,u=s||o,c=E(d);if(yield xe.count({where:{[ve.or]:[{email:o},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=E(a))return e.error("Invalid password");const l=yield xe.create({name:i,email:o,username:u,password:c,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!l)return e.error("Internal Server Error");const p=yield De.create({token:yield this.getId(),user_id:l.id,state:!0}).catch(this.error);if(!p)return yield l.destroy().catch(this.error),e.error("Internal Server Error");e.success("OK"),r.emit("register.user",{ctx:e,register:p,user:l}),this.emit("register.user",{ctx:e,register:p,user:l})}))}confirm(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=yield De.findOne({where:{token:t,state:!0},include:[{model:xe,required:!0}]}).catch(this.error);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})}))}send(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=t,n=yield De.findOne({where:{state:!0},include:[{model:xe,required:!0,where:{[ve.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})}))}getId(){return Oe(this,void 0,void 0,(function*(){const e=R();return(yield De.count({where:{token:e}}))?this.getId():e}))}};Pe([h(),p("validation",{name:F.string().required(),date:F.date().required(),email:F.string().email().required(),username:F.string().min(4).empty(),password:F.string().min(5).required(),confirm:F.string().min(5).required()}),Ie(0,r()),Ie(1,v()),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object,ze]),Ae("design:returntype",Promise)],at.prototype,"register",null),Pe([h("/confirm"),p("validation",{token:F.string().required()}),Ie(0,r()),Ie(1,v("token")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,ze]),Ae("design:returntype",Promise)],at.prototype,"confirm",null),Pe([h("/send"),p("validation",{username:F.string().min(4).required()}),Ie(0,r()),Ie(1,v("username")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,ze]),Ae("design:returntype",Promise)],at.prototype,"send",null),at=Pe([g("/register"),u(Ze)],at);let ut=class extends nt{model(){return qe}create(){return{name:F.string().required(),description:F.string().empty(""),state:F.boolean().parse().required()}}update(){return{name:F.string().empty(),description:F.string().empty(),state:F.boolean().parse().empty()}}};ut=Pe([g("/routes"),u(nt)],ut);let ct=class extends Ze{setup(e){return Oe(this,void 0,void 0,(function*(){if(0==(yield xe.count())){const e=L(),t=yield xe.create({name:"Admin",email:"admin@localhost",username:"admin",password:E("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),r={description:"API CORE",state:!0},i=yield Re.create(Object.assign({name:"admin"},r));yield ke.create({user_id:t.id,group_id:i.id});const n=["read","write"],o=["audits","users","groups","routes"];yield K(o,(e=>Oe(this,void 0,void 0,(function*(){yield K(n,(t=>Oe(this,void 0,void 0,(function*(){const n=yield qe.create(Object.assign({name:`${e}.${t}`},r));yield Le.create({group_id:i.id,route_id:n.id})}))))}))));const s=["delete","list","read","rename","upload","write"];yield K(s,(e=>Oe(this,void 0,void 0,(function*(){const t=yield qe.create(Object.assign({name:`files.${e}`},r));yield Le.create({group_id:i.id,route_id:t.id})}))));const d=["logs"];yield K(d,(e=>Oe(this,void 0,void 0,(function*(){const t=yield qe.create(Object.assign({name:`${e}.read`},r));yield Le.create({group_id:i.id,route_id:t.id})}))))}e.success("OK")}))}};Pe([l(),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ct.prototype,"setup",null),ct=Pe([g("/setup"),u(Ze)],ct);let lt=class extends Qe{model(){return xe}constructor(){super(),this.dir=Ee.API_HTTP_PUBLIC+"/avatar",Ee.API_HTTP_PUBLIC&&ae(Ee.API_HTTP_PUBLIC)&&!ae(this.dir)&&pe(this.dir)}avatar(e,t,r,i){return Oe(this,void 0,void 0,(function*(){if(t.length){const n=t[0].filename||"";if(n){const t=this.dir+"/"+r.avatar;if(ae(t)&&ye(t).isFile()&&ge(t),r.avatar=n,yield r.save(Object.assign({},i)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=this.dir+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&ae(i)&&ge(i),e.success("OK")}))}password(e,t,r,i,n){return Oe(this,void 0,void 0,(function*(){var o;const s=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);return t+=null!==(o=null==s?void 0:s.salt)&&void 0!==o?o:"",s&&s.password==E(t)?(s.salt=L(),s.password=E(r+s.salt),(yield s.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_get(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_remove(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i)return i.token="",yield i.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r,i){return Oe(this,void 0,void 0,(function*(){const n=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(n){const t=yield this.token_new();return n.token=i.hash.encrypt(t),yield n.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return Oe(this,void 0,void 0,(function*(){var e;const t=R();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=L();yield this._add({ctx:e,body:{password:E(t+i),salt:i},user:r})}))}all(e){return Oe(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return Oe(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("Record not found");yield this._del({ctx:e,user:r})}))}get(e){return Oe(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,r){return Oe(this,void 0,void 0,(function*(){const i=L();yield this._set({ctx:e,body:t?{password:E(t+i),salt:i}:{},user:r})}))}};Pe([h("/avatar"),p("auth"),p("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),Ie(0,r()),Ie(1,P()),Ie(2,$e()),Ie(3,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,Array,xe,Object]),Ae("design:returntype",Promise)],lt.prototype,"avatar",null),Pe([l("/avatar/remove"),p("auth"),Ie(0,r()),Ie(1,$e()),Ie(2,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe,Object]),Ae("design:returntype",Promise)],lt.prototype,"avatar_remove",null),Pe([h("/password"),p("auth"),p("validation",{oldPassword:F.string().min(5).required(),newPassword:F.string().min(5).required()}),Ie(0,r()),Ie(1,v("oldPassword")),Ie(2,v("newPassword")),Ie(3,$e()),Ie(4,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,xe,Object]),Ae("design:returntype",Promise)],lt.prototype,"password",null),Pe([l("/token"),p("auth"),Ie(0,r()),Ie(1,$e()),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe,ze]),Ae("design:returntype",Promise)],lt.prototype,"token",null),Pe([l("/token/:id"),p("auth"),p("write"),Ie(0,r()),Ie(1,f("id")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,ze]),Ae("design:returntype",Promise)],lt.prototype,"token_get",null),Pe([l("/token/remove/:id"),p("auth"),p("write"),Ie(0,r()),Ie(1,f("id")),Ie(2,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object]),Ae("design:returntype",Promise)],lt.prototype,"token_remove",null),Pe([l("/token/renew/:id"),p("auth"),p("write"),Ie(0,r()),Ie(1,f("id")),Ie(2,Je()),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object,ze]),Ae("design:returntype",Promise)],lt.prototype,"token_renew",null),Pe([h(),p("auth"),p("write"),p("validation",{name:F.string().required(),email:F.string().email().required(),username:F.string().min(4).required(),password:F.string().min(5).required(),description:F.string().empty(""),state:F.boolean().parse().required()}),Ie(0,r()),Ie(1,v("password")),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],lt.prototype,"add",null),Pe([l(),p("auth"),p("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],lt.prototype,"all",null),Pe([_("/:id"),p("auth"),p("write"),Ie(0,r()),Ie(1,f("id")),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],lt.prototype,"del",null),Pe([l("/:id"),p("auth"),p("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],lt.prototype,"get",null),Pe([m("/:id"),p("auth"),p("write"),p("validation",{name:F.string().empty(),email:F.string().email().empty(),username:F.string().min(4).empty(),password:F.string().min(5).empty().filter(""),description:F.string().empty(),state:F.boolean().parse().empty()}),Ie(0,r()),Ie(1,v("password")),Ie(2,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,xe]),Ae("design:returntype",Promise)],lt.prototype,"set",null),lt=Pe([g("/users"),u(Qe),Ae("design:paramtypes",[])],lt);let pt=class extends Qe{model(){return ke}groups(e,t){return Oe(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return Oe(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:Re,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r,i){return Oe(this,void 0,void 0,(function*(){const n=yield xe.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){if(yield ke.destroy(Object.assign({where:{user_id:n.id},individualHooks:!0},i)),r){let e=0;yield k(1e3);for(let t=0;t<r.length;t++)e=yield Re.count({where:{id:r[t]}}),e&&(yield ke.create({user_id:n.id,group_id:r[t]},Object.assign({},i)))}return e.success("OK")}if(B(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Pe([l("/groups"),p("auth"),Ie(0,r()),Ie(1,$e()),Ae("design:type",Function),Ae("design:paramtypes",[a,xe]),Ae("design:returntype",Promise)],pt.prototype,"groups",null),Pe([l("/:id/groups"),p("auth"),p("read","users"),Ie(0,r()),Ie(1,f("id")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],pt.prototype,"all",null),Pe([m("/:id/groups"),p("auth"),p("write","users"),p("validation",{groups:F.array(F.number().parse())}),Ie(0,r()),Ie(1,f("id")),Ie(2,v("groups")),Ie(3,Je()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Array,Object]),Ae("design:returntype",Promise)],pt.prototype,"set",null),pt=Pe([g("/users"),u(Qe)],pt);export{ze as Application,Fe as Audit,et as AuditsController,be as Auth,tt as AuthController,We as Config,Ne as Configs,Ze as ControllerBase,nt as CrudController,Ee as Env,rt as FilesController,je as Forgot,it as ForgotController,Re as Group,Le as GroupRoute,ot as GroupsController,st as GroupsRoutesController,Be as Log,He as Logs,dt as LogsController,we as Model,Qe as ModelController,Ve as Permission,De as Register,at as RegisterController,Je as ReqAudit,Xe as ReqAuth,$e as ReqUser,qe as Route,ut as RoutesController,Ke as Session,ct as SetupController,Ge as Token,xe as User,ke as UserGroup,lt as UsersController,pt as UsersGroupsController,Te as audit,Se as conn,Ue as crt,Me as key};
|
|
7
|
+
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,App as n,Argument as s,Session as o,Upload as d,Context as a,Extends as u,Status as p,Get as c,Middleware as l,Query as y,Controller as g,Post as h,Body as v,Delete as _,Put as m,Params as f,Files as P}from"@andrewcaires/express";import{LogColor as O,Log as I,Hash as A,sha256 as E}from"@andrewcaires/node";import{toBool as S,parseMs as T,isObject as b,noop as w,loop as D,uuidv4 as k,sleep as R,EventEmitter as x,Validation as j,isString as F,isArray as N,isDef as q,uniqueID as L,isNull as C,forEachSeries as B}from"@andrewcaires/utils.js";import{WebSocketServer as H}from"ws";import{Connection as K,Model as U,Id as M,String as Y,FullDate as G,CreatedAt as W,UpdatedAt as z,DeletedAt as $,BelongsTo as J,Database as X,ModelName as V,Boolean as Z,Text as Q,HasMany as ee,Hooks as te,DateOnly as re,DefaultScope as ie,Scopes as ne,Enum as se,Json as oe,BigInt as de,Unique as ae}from"@andrewcaires/sequelize";import{config as ue}from"dotenv";import{existsSync as pe,readFileSync as ce,statSync as le,readdirSync as ye,mkdirSync as ge,lstatSync as he,rmSync as ve}from"fs";import{Store as _e}from"express-session";import{Op as me}from"sequelize";import fe from"jsonwebtoken";import{join as Pe}from"path";function Oe(e,t,r,i){var n,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,i);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function Ie(e,t){return function(r,i){t(r,i,e)}}function Ae(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Ee(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{a(i.next(e))}catch(e){s(e)}}function d(e){try{a(i.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,d)}a((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,ue();class Se{static getBool(e,t){return S(Se.getString(e,t.toString()))}static getInt(e,t){return parseInt(Se.getString(e,t.toString()))}static getMs(e,t){return T(Se.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}Se.API_CONSOLE_ERROR=Se.getBool("API_CONSOLE_ERROR",!1),Se.API_DEFAULT_PATH=Se.getString("API_DEFAULT_PATH","/api"),Se.API_DB_DATABASE=Se.getString("API_DB_DATABASE",""),Se.API_DB_HOST=Se.getString("API_DB_HOST","127.0.0.1"),Se.API_DB_PASSWORD=Se.getString("API_DB_PASSWORD",""),Se.API_DB_PORT=Se.getInt("API_DB_PORT",3306),Se.API_DB_TYPE=Se.getString("API_DB_TYPE",""),Se.API_DB_USERNAME=Se.getString("API_DB_USERNAME","root"),Se.API_DB_LOG=Se.getBool("API_DB_LOG",!1),Se.API_DB_AUDIT=Se.getBool("API_DB_AUDIT",!0),Se.API_DB_PREFIX=Se.getString("API_DB_PREFIX",""),Se.API_DB_TIMEZONE=Se.getString("API_DB_TIMEZONE","+00:00"),Se.API_HTTP_CRT=Se.getString("API_HTTP_CRT",""),Se.API_HTTP_KEY=Se.getString("API_HTTP_KEY",""),Se.API_HTTP_PORT=Se.getInt("API_HTTP_PORT",3e3),Se.API_HTTP_PUBLIC=Se.getString("API_HTTP_PUBLIC",""),Se.API_HTTP_CROSS=Se.getBool("API_HTTP_CROSS",!1),Se.API_HTTP_HYBRID=Se.getBool("API_HTTP_HYBRID",!1),Se.API_HTTP_NOTFOUND=Se.getString("API_HTTP_NOTFOUND",""),Se.API_HTTP_REDIRECT=Se.getString("API_HTTP_REDIRECT",""),Se.API_KEY_HASH=Se.getString("API_KEY_HASH",""),Se.API_KEY_HEADER=Se.getString("API_KEY_HEADER","api_key"),Se.API_MODEL_LIMIT=Se.getInt("API_MODEL_LIMIT",10),Se.API_MODEL_LIMIT_MAX=Se.getInt("API_MODEL_LIMIT_MAX",500),Se.API_SLEEP_AUTH=Se.getMs("API_SLEEP_AUTH","2s"),Se.API_SLEEP_FORGOT=Se.getMs("API_SLEEP_FORGOT","5s"),Se.API_SLEEP_REGISTRY=Se.getMs("API_SLEEP_REGISTRY","5s"),Se.API_SESSION_NAME=Se.getString("API_SESSION_NAME","session.id"),Se.API_SESSION_LIFETIME=Se.getMs("API_SESSION_LIFETIME","1d"),Se.API_SESSION_SECRET=Se.getString("API_SESSION_SECRET","yoursecret"),Se.API_TOKEN_CRT=Se.getString("API_TOKEN_CRT",""),Se.API_TOKEN_KEY=Se.getString("API_TOKEN_KEY",""),Se.API_TOKEN_FORGOT=Se.getMs("API_TOKEN_LIFETIME","1d"),Se.API_TOKEN_HEADER=Se.getString("API_TOKEN_HEADER","authorization"),Se.API_TOKEN_LIFETIME=Se.getMs("API_TOKEN_LIFETIME","1d"),Se.API_TOKEN_RENEW=Se.getMs("API_TOKEN_RENEW","1d"),Se.API_UPLOAD_COUNT=Se.getInt("API_UPLOAD_COUNT",1),Se.API_UPLOAD_FIELD=Se.getString("API_UPLOAD_FIELD","upload"),Se.API_UPLOAD_SIZE=Se.getInt("API_UPLOAD_SIZE",2),Se.API_UPLOAD_TEMP=Se.getString("API_UPLOAD_TEMP","./temp"),Se.API_WEBSOCKET_START=Se.getBool("API_WEBSOCKET_START",!1);const Te=new K({type:Se.API_DB_TYPE,database:Se.API_DB_DATABASE,username:Se.API_DB_USERNAME,password:Se.API_DB_PASSWORD,hostname:Se.API_DB_HOST,hostport:Se.API_DB_PORT,logging:Se.API_DB_LOG,prefix:Se.API_DB_PREFIX});class be extends U{}const we=(e,t,r)=>{var i,n,s,o;return{type:e,model:null!==(i=null==t?void 0:t.getTableName())&&void 0!==i?i:null,user_ip:null!==(n=null==r?void 0:r.audit_user_ip)&&void 0!==n?n:null,user_agent:null!==(s=null==r?void 0:r.audit_user_agent)&&void 0!==s?s:null,user_id:null!==(o=null==r?void 0:r.audit_user_id)&&void 0!==o?o:null,state:!0}},De={afterCreate:(e,t)=>Ee(void 0,void 0,void 0,(function*(){var r;if(!Se.API_DB_AUDIT)return;const i=b(e)?e.constructor:null,n=null!==(r=null==i?void 0:i.primaryKeyAttribute)&&void 0!==r?r:null;yield Ne.create(Object.assign(Object.assign({},we("CREATE",i,t)),{record:n?e.getDataValue(n):null,data:e.toJSON()})).catch(w)})),afterUpdate:(e,t)=>Ee(void 0,void 0,void 0,(function*(){var r;if(!Se.API_DB_AUDIT)return;const i=b(e)?e.constructor:null,n=null!==(r=null==i?void 0:i.primaryKeyAttribute)&&void 0!==r?r:null,s=e.changed();s&&s.forEach((t=>e.getDataValue(t))),yield Ne.create(Object.assign(Object.assign({},we("UPDATE",i,t)),{record:n?e.getDataValue(n):null,data:e.toJSON(),previously:e.previous()})).catch(w)})),afterDestroy:(e,t)=>Ee(void 0,void 0,void 0,(function*(){var r;if(!Se.API_DB_AUDIT)return;const i=b(e)?e.constructor:null,n=null!==(r=null==i?void 0:i.primaryKeyAttribute)&&void 0!==r?r:null;yield Ne.create(Object.assign(Object.assign({},we("DELETE",i,t)),{record:n?e.getDataValue(n):null,data:JSON.stringify(e.toJSON())})).catch(w)}))};let ke=class extends be{};Oe([M(),Ae("design:type",Number)],ke.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],ke.prototype,"secret",void 0),Oe([G(),Ae("design:type",Date)],ke.prototype,"logout",void 0),Oe([Y(),Ae("design:type",Y)],ke.prototype,"user_agent",void 0),Oe([W,Ae("design:type",Date)],ke.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],ke.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],ke.prototype,"deleted_at",void 0),Oe([J((()=>Fe)),Ae("design:type",Number)],ke.prototype,"user_id",void 0),ke=Oe([X(Te),V("auth")],ke);let Re=class extends be{};Oe([M(),Ae("design:type",Number)],Re.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],Re.prototype,"token",void 0),Oe([Z(),Ae("design:type",Z)],Re.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],Re.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Re.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],Re.prototype,"deleted_at",void 0),Oe([J((()=>Fe)),Ae("design:type",Number)],Re.prototype,"user_id",void 0),Re=Oe([X(Te),V("register")],Re);let xe=class extends be{};Oe([M(),Ae("design:type",Number)],xe.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],xe.prototype,"name",void 0),Oe([Q(),Ae("design:type",Y)],xe.prototype,"description",void 0),Oe([Z(),Ae("design:type",Z)],xe.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],xe.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],xe.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],xe.prototype,"deleted_at",void 0),Oe([ee((()=>je),"group_id"),Ae("design:type",Array)],xe.prototype,"groups_routes",void 0),Oe([ee((()=>je),"group_id"),Ae("design:type",Array)],xe.prototype,"users_groups",void 0),xe=Oe([X(Te),V("group"),te(De)],xe);let je=class extends be{};Oe([W,Ae("design:type",Date)],je.prototype,"created_at",void 0),Oe([J((()=>xe)),Ae("design:type",Number)],je.prototype,"group_id",void 0),Oe([J((()=>Fe)),Ae("design:type",Number)],je.prototype,"user_id",void 0),je=Oe([X(Te),V("users_groups"),te(De)],je);let Fe=class extends be{};Oe([M(),Ae("design:type",Number)],Fe.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"name",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"email",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"username",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"password",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"salt",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"token",void 0),Oe([Y(),Ae("design:type",Y)],Fe.prototype,"avatar",void 0),Oe([re(),Ae("design:type",Y)],Fe.prototype,"date",void 0),Oe([Q(),Ae("design:type",Y)],Fe.prototype,"description",void 0),Oe([Z(),Ae("design:type",Z)],Fe.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],Fe.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Fe.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],Fe.prototype,"deleted_at",void 0),Oe([ee((()=>Ne),"user_id"),Ae("design:type",Array)],Fe.prototype,"audits",void 0),Oe([ee((()=>ke),"user_id"),Ae("design:type",Array)],Fe.prototype,"auths",void 0),Oe([ee((()=>Re),"user_id"),Ae("design:type",Array)],Fe.prototype,"registers",void 0),Oe([ee((()=>je),"user_id"),Ae("design:type",Array)],Fe.prototype,"users_groups",void 0),Fe=Oe([X(Te),V("user"),ie({attributes:{exclude:["password","salt","token"]}}),ne({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),te(De)],Fe);let Ne=class extends be{};Oe([M(),Ae("design:type",Number)],Ne.prototype,"id",void 0),Oe([se("CREATE","DELETE","UPDATE"),Ae("design:type",Y)],Ne.prototype,"type",void 0),Oe([Y(),Ae("design:type",Y)],Ne.prototype,"model",void 0),Oe([Y(),Ae("design:type",Y)],Ne.prototype,"record",void 0),Oe([Y(),Ae("design:type",Y)],Ne.prototype,"user_ip",void 0),Oe([Y(),Ae("design:type",Y)],Ne.prototype,"user_agent",void 0),Oe([oe(),Ae("design:type",Object)],Ne.prototype,"data",void 0),Oe([oe(),Ae("design:type",Object)],Ne.prototype,"previously",void 0),Oe([Z(),Ae("design:type",Z)],Ne.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],Ne.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Ne.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],Ne.prototype,"deleted_at",void 0),Oe([J((()=>Fe)),Ae("design:type",Number)],Ne.prototype,"user_id",void 0),Ne=Oe([X(Te),V("audit")],Ne);let qe=class extends be{};Oe([Y(),Ae("design:type",Y)],qe.prototype,"key",void 0),Oe([Y(),Ae("design:type",Y)],qe.prototype,"value",void 0),Oe([W,Ae("design:type",Date)],qe.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],qe.prototype,"updated_at",void 0),qe=Oe([X(Te),V("configs"),te(De)],qe);let Le=class extends be{};Oe([M(),Ae("design:type",Number)],Le.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],Le.prototype,"token",void 0),Oe([de(),Ae("design:type",Number)],Le.prototype,"timestamp",void 0),Oe([Z(),Ae("design:type",Z)],Le.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],Le.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Le.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],Le.prototype,"deleted_at",void 0),Oe([J((()=>Fe)),Ae("design:type",Number)],Le.prototype,"user_id",void 0),Le=Oe([X(Te),V("forgot")],Le);let Ce=class extends be{};Oe([M(),Ae("design:type",Number)],Ce.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],Ce.prototype,"name",void 0),Oe([Y(),ae(!0),Ae("design:type",Y)],Ce.prototype,"route",void 0),Oe([Q(),Ae("design:type",Y)],Ce.prototype,"description",void 0),Oe([Z(),Ae("design:type",Z)],Ce.prototype,"state",void 0),Oe([W,Ae("design:type",Date)],Ce.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Ce.prototype,"updated_at",void 0),Oe([$,Ae("design:type",Date)],Ce.prototype,"deleted_at",void 0),Oe([ee((()=>Be),"permission_id"),Ae("design:type",Array)],Ce.prototype,"groups_permissions",void 0),Ce=Oe([X(Te),V("permission"),te(De)],Ce);let Be=class extends be{};Oe([W,Ae("design:type",Date)],Be.prototype,"created_at",void 0),Oe([J((()=>xe)),Ae("design:type",Number)],Be.prototype,"group_id",void 0),Oe([J((()=>Ce)),Ae("design:type",Number)],Be.prototype,"permission_id",void 0),Be=Oe([X(Te),V("groups_permissions"),te(De)],Be);let He=class extends be{};Oe([M(),Ae("design:type",Number)],He.prototype,"id",void 0),Oe([Y(),Ae("design:type",Y)],He.prototype,"type",void 0),Oe([Y(),Ae("design:type",Y)],He.prototype,"source",void 0),Oe([Q(),Ae("design:type",Y)],He.prototype,"message",void 0),Oe([W,Ae("design:type",Date)],He.prototype,"created_at",void 0),He=Oe([X(Te),V("log")],He);let Ke=class extends be{};Oe([Y(),Ae("design:type",Y)],Ke.prototype,"session",void 0),Oe([Q(),Ae("design:type",Y)],Ke.prototype,"json",void 0),Oe([de(),Ae("design:type",Number)],Ke.prototype,"expired",void 0),Oe([W,Ae("design:type",Date)],Ke.prototype,"created_at",void 0),Oe([z,Ae("design:type",Date)],Ke.prototype,"updated_at",void 0),Ke=Oe([X(Te),V("session")],Ke);class Ue{static write(e,t,r){return Ee(this,void 0,void 0,(function*(){yield Ue.writeRaw(O.White,"",e,t,r)}))}static error(e,t,r){return Ee(this,void 0,void 0,(function*(){yield Ue.writeRaw(O.Red,"error",e,t,r)}))}static info(e,t,r){return Ee(this,void 0,void 0,(function*(){yield Ue.writeRaw(O.Cyan,"info",e,t,r)}))}static success(e,t,r){return Ee(this,void 0,void 0,(function*(){yield Ue.writeRaw(O.Green,"success",e,t,r)}))}static warning(e,t,r){return Ee(this,void 0,void 0,(function*(){yield Ue.writeRaw(O.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return Ee(this,void 0,void 0,(function*(){n&&I.console(e,t,r),Te&&(yield He.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Me=e=>pe(e)?ce(e):void 0,Ye={http:Me(Se.API_HTTP_CRT),token:Me(Se.API_TOKEN_CRT)},Ge={http:Me(Se.API_HTTP_KEY),token:Me(Se.API_TOKEN_KEY)};class We extends _e{constructor(){super(),this.all=e=>Ee(this,void 0,void 0,(function*(){e=e||w;const t=yield Ke.findAll({attributes:["session"],where:{expired:{[me.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>Ee(this,void 0,void 0,(function*(){yield Ke.destroy().catch(w),e&&e()})),this.destroy=(e,t)=>Ee(this,void 0,void 0,(function*(){yield Ke.destroy({where:{session:e}}).catch(w),t&&t()})),this.expired=()=>Ee(this,void 0,void 0,(function*(){yield Ke.destroy({where:{expired:{[me.lt]:Date.now()}}}).catch(w)})),this.get=(e,t)=>Ee(this,void 0,void 0,(function*(){t=t||w;const r=yield Ke.findOne({where:{session:e,expired:{[me.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(r){const e=JSON.parse(r.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield r.destroy().catch(w),void t(null)}t(null,e)}else t(null)})),this.length=e=>Ee(this,void 0,void 0,(function*(){e&&e(null,(yield Ke.count().catch(w))||0)})),this.set=(e,t,r)=>Ee(this,void 0,void 0,(function*(){r=r||w;const i=Date.now()+Se.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield Ke.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(w))||[];s&&(o||(s.json=n,s.expired=i,yield s.save().catch(w))),r()})),this.loop=D(this.expired,3e4),this.loop.start()}}class ze{static create(e){return Ee(this,void 0,void 0,(function*(){if(!Ge.token)return{error:"Key not found"};const{id:t}=e,r=k(),i=yield ke.create({secret:r,user_id:t}).catch(ze.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:fe.sign({id:t,secret:r},Ge.token,ze.options())}}))}static destroy(e){return Ee(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){Ue.error(e.message,"api.token",Se.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:Se.API_TOKEN_LIFETIME+"ms"}}static renew(e){return Ee(this,void 0,void 0,(function*(){if(!Ge.token)return{error:"Key not found"};const{error:t,decode:r}=ze.verify(e,Se.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield Fe.findOne({where:{id:e,state:!0}}).catch(ze.error);if(r){const i=yield ke.findOne({where:{secret:t,user_id:r.id}}).catch(ze.error);if(i&&!i.logout){i.secret=k(),yield i.save().catch(ze.error);return{auth:i,token:fe.sign({id:e,secret:i.secret},Ge.token,ze.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return Ee(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield Fe.findOne({where:{token:t,state:!0}}).catch(ze.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield ke.findOrCreate({where:{secret:t,user_id:i.id},defaults:{secret:t,user_id:i.id}}).catch(ze.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:n}=ze.verify(t);if(i)return{error:i};if(n){const{id:e,secret:t}=n;if(e&&t){const r=yield Fe.findOne({where:{id:e,state:!0}}).catch(ze.error);if(r){const e=yield ke.findOne({where:{secret:t,user_id:r.id}}).catch(ze.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ye.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:fe.verify(e,Ye.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class $e extends e{constructor(e){super(e,{cert:Ye.http,cross:Se.API_HTTP_CROSS,hybrid:Se.API_HTTP_HYBRID,key:Ge.http,notfound:Se.API_HTTP_NOTFOUND,path:Se.API_DEFAULT_PATH,port:Se.API_HTTP_PORT,public:Se.API_HTTP_PUBLIC,redirect:Se.API_HTTP_REDIRECT,session:{store:new We,name:Se.API_SESSION_NAME,secret:Se.API_SESSION_SECRET,cookie:{maxAge:Se.API_SESSION_LIFETIME},genid:k}}),this.hash=new A(Se.API_KEY_HASH)}error(e,t){Ue.error(e.message,t,Se.API_CONSOLE_ERROR)}log(e,t){Ue.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Ee(this,void 0,void 0,(function*(){yield Te.sync(),yield e.listen.call(this),Se.API_WEBSOCKET_START&&this.server&&(this._webSocket=new H({server:this.server,verifyClient:(e,t)=>t(Se.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>Ee(this,void 0,void 0,(function*(){t.url||(t.url="");const r=t.url.length<=1?"":t.url.replace(/\//g,".");let i;e.on("message",(n=>Ee(this,void 0,void 0,(function*(){if(i)try{const s=JSON.parse(n);this.emit("ws.message"+r,{data:s,message:n,req:t,user:i,ws:e})}catch(s){this.emit("ws.message"+r,{message:n,req:t,user:i,ws:e})}else{const{user:s}=yield ze.user("",n.toString(),this);s&&(i=s,this.emit("ws.connection"+r,{req:t,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+r,{user:i,ws:e})})),yield R(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class Je{static all(){return Ee(this,void 0,void 0,(function*(){const e=yield qe.findAll().catch(Je.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return Ee(this,void 0,void 0,(function*(){var r;const i=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield qe.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:i})).catch(Je.error))||0)>0}))}static error(e){Ue.error(e.message,"api.config",Se.API_CONSOLE_ERROR)}static get(e){return Ee(this,arguments,void 0,(function*(e,t=""){const[r]=(yield qe.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(Je.error))||[];return r?r.value:t}))}static set(e,t,r){return Ee(this,void 0,void 0,(function*(){var i;const n=null!==(i=null==r?void 0:r.id)&&void 0!==i?i:null,[s]=(yield qe.findOrCreate(Object.assign({where:{key:e}},{user_id:n})).catch(Je.error))||[];s&&(s.value=t,yield s.save().catch(Je.error))}))}}const Xe=e=>{var t,r,i,n,s,o;return{audit_user_ip:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_user_id:null!==(n=null===(i=null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.user)||void 0===i?void 0:i.id)&&void 0!==n?n:null,audit_user_agent:null!==(o=null===(s=e.req)||void 0===s?void 0:s.headers["user-agent"])&&void 0!==o?o:""}},Ve=t((({ctx:e})=>Xe(e))),Ze=t((({ctx:e})=>e.req.auth)),Qe=t((({ctx:e})=>e.req.user));class et extends x{auth(e,t,r,i,n){return Ee(this,void 0,void 0,(function*(){const{auth:s,error:o,user:d}=yield ze.user(t,r,n);return o?e.error(o):s&&d?s.user_agent&&s.user_agent!=i?e.error("Invalid token"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}create(e,t,r){return Ee(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".create",r)}))}delete(e,t,r){return Ee(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".delete",r)}))}error(e){Ue.error(e.message,"api.controller",Se.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return Ee(this,void 0,void 0,(function*(){if(r){const i=yield this.permissions(r,{route:t});if(i&&i.length>0)return e.next()}e.unauthorized("Access denied")}))}permissions(e,t){return Ee(this,void 0,void 0,(function*(){return yield Ce.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Be,required:!0,include:[{model:xe,required:!0,where:{state:!0},include:[{model:je,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error)}))}read(e,t,r){return Ee(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}session(e,t,r){return Ee(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(w):(r.user_agent=t,r.save(w))),e.next()}))}upload(e,t){t.path||(t.path=Se.API_UPLOAD_TEMP),t.size||(t.size=Se.API_UPLOAD_SIZE),t.field||(t.field=Se.API_UPLOAD_FIELD),d.middleware(e,t)}update(e,t,r){return Ee(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".update",r)}))}validation(e,t){return Ee(this,void 0,void 0,(function*(){const{error:r,value:i}=yield j.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=i,e.next()}))}}Oe([Ie(0,r()),Ie(1,i(Se.API_KEY_HEADER)),Ie(2,i(Se.API_TOKEN_HEADER)),Ie(3,i("user-agent")),Ie(4,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,String,$e]),Ae("design:returntype",Promise)],et.prototype,"auth",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],et.prototype,"create",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],et.prototype,"delete",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],et.prototype,"permission",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],et.prototype,"read",null),Oe([Ie(0,r()),Ie(1,i("user-agent")),Ie(2,o()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object]),Ae("design:returntype",Promise)],et.prototype,"session",null),Oe([Ie(0,r()),Ie(1,s()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object]),Ae("design:returntype",void 0)],et.prototype,"upload",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],et.prototype,"update",null),Oe([Ie(0,r()),Ie(1,s()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object]),Ae("design:returntype",Promise)],et.prototype,"validation",null);let tt=class extends et{constructor(){super(...arguments),this._columns=[]}_add(e){return Ee(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),Xe(e))).catch(this.error);if(i){const t=this.key();return e.prepare(p.OK,{[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all(e){return Ee(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){var n,s,o,d;const a=this.scope(i),u=Object.assign({},t||{});u.where=Object.assign({},u.where||{});const c=e.req.query.limit,l=F(c)?parseInt(c):Se.API_MODEL_LIMIT;u.limit=l>=0?Math.min(l,Se.API_MODEL_LIMIT_MAX):void 0;const y=e.req.query.offset;if(F(y)){const e=y?parseInt(y):0;u.offset=e>0?e:void 0}const g=[],h=this.columns(),v=e=>h.indexOf(e)>=0,_=null===(n=e.req.query.asc)||void 0===n?void 0:n.toString();_&&_.length&&g.push(..._.split(",").filter(v).map((e=>[e,"ASC"])));const m=null===(s=e.req.query.desc)||void 0===s?void 0:s.toString();m&&m.length&&g.push(...m.split(",").filter(v).map((e=>[e,"DESC"]))),g.length&&(u.order=g);const f=[],P=null===(o=e.req.query.search)||void 0===o?void 0:o.toString();(N(u.attributes)?u.attributes:h).filter(F).forEach((t=>{var r;if(P&&P.length&&f.push({[t]:{[me.like]:`%${P}%`}}),"search_"+t in e.req.query){const i=null===(r=e.req.query["search_"+t])||void 0===r?void 0:r.toString();i&&i.length&&f.push({[t]:{[me.like]:`%${i}%`}})}})),f.length&&(u.where=Object.assign(Object.assign({},u.where),{[me.or]:[...f]}));const O=null!==(d=yield a.count(Object.assign(Object.assign({},u),{col:h[0]})).catch(this.error))&&void 0!==d?d:0,I=yield a.findAll(u).catch(this.error),A={count:O};return I?(e.prepare(p.OK,Object.assign(Object.assign({},A),{records:r?yield r(I):I})),Object.assign(Object.assign({},A),{records:I})):(e.error("Internal Server Error"),Object.assign(Object.assign({},A),{records:[]}))}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return Ee(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:i}=e.req.params;if(!i)return e.error("Internal Server Error"),0;const n=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i}),individualHooks:!0}),Xe(e))).catch(this.error);return n?(e.success("OK"),n):(e.notFound("Record not found"),0)}))}error(e){e.sql?Ue.error(e.message+"\n"+e.sql,"api.controller.sql",Se.API_CONSOLE_ERROR):super.error(e)}_get(e){return Ee(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){const n=this.key(),{[n]:s}=e.req.params,o=yield this.scope(i).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:s})})).catch(this.error);return o?(e.prepare(p.OK,r?yield r(o):o.toJSON()),o):null===o?e.notFound("Record not found"):void e.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return Ee(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){var i;const n=this.key(),{[n]:s}=e.req.params,[o]=null!==(i=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:s}),individualHooks:!0}),Xe(e))).catch(this.error))&&void 0!==i?i:[];return o?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};tt=Oe([u(et)],tt);let rt=class extends tt{model(){return Ne}all(e,t,r){return Ee(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.table=r),yield this._all({ctx:e,options:{attributes:{exclude:["data","previously"]},where:i,order:[["created_at","DESC"]]}})}))}get(e){return Ee(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}};Oe([c(),l("auth"),l("read"),Ie(0,r()),Ie(1,y("type")),Ie(2,y("table")),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String]),Ae("design:returntype",Promise)],rt.prototype,"all",null),Oe([c("/:id"),l("auth"),l("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],rt.prototype,"get",null),rt=Oe([g("/audits"),u(tt)],rt);let it=class extends et{login(e,t,r,i,n){return Ee(this,void 0,void 0,(function*(){var s;yield R(Se.API_SLEEP_AUTH);const o=yield Fe.scope("password").findOne({where:{[me.or]:[{email:r},{username:r}]}}).catch(this.error);if(i+=null!==(s=null==o?void 0:o.salt)&&void 0!==s?s:"",!o||o.password!=E(i))return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield Re.findOne({where:{state:!0,user_id:o.id}}).catch(this.error);if(d)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:d,user:o}),void this.emit("auth.activation",{ctx:e,register:d,user:o});if(!o.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:p}=yield ze.create(o);return u?(e.error(u),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&p?(a.user_agent=t,yield a.save().catch(this.error),e.json({token:p}),n.emit("auth.login",{auth:a,ctx:e,user:o}),void this.emit("auth.login",{auth:a,ctx:e,user:o})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return Ee(this,void 0,void 0,(function*(){if(yield ze.destroy(t))return e.success("Disconcerted"),i.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,i){return Ee(this,void 0,void 0,(function*(){const{auth:n,error:s,token:o}=yield ze.renew(r);return s?e.error(s):n?(n.user_agent=t,yield n.save().catch(this.error),e.json({token:o}),i.emit("auth.renew",{auth:n,ctx:e}),void this.emit("auth.renew",{auth:n,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return Ee(this,void 0,void 0,(function*(){const r=yield this.permissions(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.route))}))}))}};Oe([h("/login"),l("validation",{username:j.string().min(3).required(),password:j.string().min(5).required()}),Ie(0,r()),Ie(1,i("user-agent")),Ie(2,v("username")),Ie(3,v("password")),Ie(4,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,String,$e]),Ae("design:returntype",Promise)],it.prototype,"login",null),Oe([c("/logout"),l("auth"),Ie(0,r()),Ie(1,Ze()),Ie(2,Qe()),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,ke,Fe,$e]),Ae("design:returntype",Promise)],it.prototype,"logout",null),Oe([h("/renew"),l("validation",{token:j.string().required()}),Ie(0,r()),Ie(1,i("user-agent")),Ie(2,v("token")),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,$e]),Ae("design:returntype",Promise)],it.prototype,"renew",null),Oe([c(),l("auth"),Ie(0,r()),Ie(1,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,Fe]),Ae("design:returntype",Promise)],it.prototype,"user",null),it=Oe([g("/auth"),u(et)],it);let nt=class extends et{directory(){return Se.API_HTTP_PUBLIC||"./"}files(e){return Ee(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=Pe(this.directory(),t);if(!pe(r)||!le(r).isDirectory())return e.notFound("Path not Found");let i=[];return i=ye(r),i=i.map((e=>this.info(Pe(r,e)))),i=i.filter(q),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r){return Ee(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!pe(e))return null;const t=le(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const i=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:i?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:i,symlink:t.isSymbolicLink()}}name(){return"files"}};Oe([c("/path/?*"),l("auth"),l("access","list"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],nt.prototype,"files",null),Oe([Ie(0,r()),Ie(1,s()),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],nt.prototype,"access",null),nt=Oe([g("/files"),u(et)],nt);let st=class extends et{check(e,t){return Ee(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("User not found");r.token=L(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return Ee(this,void 0,void 0,(function*(){yield R(Se.API_SLEEP_FORGOT);const i=t,n=yield Fe.findOne({where:{[me.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=L(),o=Date.now()+6e4*Se.API_TOKEN_FORGOT,d=yield Le.create({token:s,timestamp:o,state:!0,user_id:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})}))}reset(e,t,r,i){return Ee(this,void 0,void 0,(function*(){const n=yield this.find(t);if(!n)return e.notFound("User not found");n.state=!1,yield n.save().catch(this.error),n.user.password=E(r),yield n.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})}))}find(e){return Ee(this,void 0,void 0,(function*(){return yield Le.findOne({where:{token:e,state:!0},include:[{model:Fe,required:!0}]}).catch(this.error)}))}};Oe([c("/check"),l("validation",{token:j.string().required()}),Ie(0,r()),Ie(1,v("token")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],st.prototype,"check",null),Oe([h(),l("validation",{username:j.string().min(4).required()}),Ie(0,r()),Ie(1,v("username")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,$e]),Ae("design:returntype",Promise)],st.prototype,"forgot",null),Oe([h("/reset"),l("validation",{token:j.string().required(),password:j.string().min(5).required()}),Ie(0,r()),Ie(1,v("token")),Ie(2,v("password")),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,$e]),Ae("design:returntype",Promise)],st.prototype,"reset",null),st=Oe([g("/forgot"),u(et)],st);let ot=class extends tt{constructor(){super(...arguments),this._crud={}}add(e){return Ee(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return Ee(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}CrudCreate(){return this._crud}del(e){return Ee(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return Ee(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return Ee(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}CrudUpdate(){return this._crud}validationAdd(e){return Ee(this,void 0,void 0,(function*(){const t=this.CrudCreate();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}validationSet(e){return Ee(this,void 0,void 0,(function*(){const t=this.CrudUpdate();if(t==this._crud)return e.error("Internal Server Error");yield this.validation(e,t)}))}};Oe([h(),l("auth"),l("create"),l("validationAdd"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"add",null),Oe([c(),l("auth"),l("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"all",null),Oe([_("/:id"),l("auth"),l("delete"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"del",null),Oe([c("/:id"),l("auth"),l("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"get",null),Oe([m("/:id"),l("auth"),l("update"),l("validationSet"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"set",null),Oe([Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"validationAdd",null),Oe([Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],ot.prototype,"validationSet",null),ot=Oe([u(tt)],ot);let dt=class extends ot{model(){return xe}CrudCreate(){return{name:j.string().required(),description:j.string().empty(""),state:j.boolean().parse().required()}}CrudUpdate(){return{name:j.string().empty(),description:j.string().empty(),state:j.boolean().parse().empty()}}};dt=Oe([g("/groups"),u(ot)],dt);let at=class extends tt{model(){return Be}all(e,t){return Ee(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{group_id:t},include:[{model:Ce,required:!0}]},callback:e=>e.map((e=>e.permission))})}))}set(e,t,r,i){return Ee(this,void 0,void 0,(function*(){const n=yield xe.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){const t=n.id;if(yield Be.destroy(Object.assign({where:{group_id:t},individualHooks:!0},i)),r){let e=0;yield R(1e3);for(let n=0;n<r.length;n++)e=yield Ce.count({where:{id:r[n]}}),e&&(yield Be.create({group_id:t,permission_id:r[n]},Object.assign({},i)))}return e.success("OK")}if(C(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Oe([c("/:id/routes"),l("auth"),l("read","groups"),Ie(0,r()),Ie(1,f("id")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],at.prototype,"all",null),Oe([m("/:id/permissions"),l("auth"),l("update","groups"),l("validation",{permissions:j.array(j.number().parse())}),Ie(0,r()),Ie(1,f("id")),Ie(2,v("permissions")),Ie(3,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Array,Object]),Ae("design:returntype",Promise)],at.prototype,"set",null),at=Oe([g("/groups"),u(tt)],at);let ut=class extends tt{model(){return He}all(e,t,r){return Ee(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.source=r),yield this._all({ctx:e,options:{where:i,order:[["created_at","DESC"]]}})}))}};Oe([c(),l("auth"),l("read"),Ie(0,r()),Ie(1,y("type")),Ie(2,y("source")),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String]),Ae("design:returntype",Promise)],ut.prototype,"all",null),ut=Oe([g("/logs"),u(tt)],ut);let pt=class extends ot{model(){return Ce}CrudCreate(){return{name:j.string().required(),description:j.string().empty(""),state:j.boolean().parse().required()}}CrudUpdate(){return{name:j.string().empty(),description:j.string().empty(),state:j.boolean().parse().empty()}}};pt=Oe([g("/permissions"),u(ot)],pt);let ct=class extends et{register(e,t,r){return Ee(this,void 0,void 0,(function*(){yield R(Se.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,p=E(d);if(yield Fe.count({where:{[me.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(p!=E(a))return e.error("Invalid password");const c=yield Fe.create({name:i,email:s,username:u,password:p,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!c)return e.error("Internal Server Error");const l=yield Re.create({token:yield this.getId(),user_id:c.id,state:!0}).catch(this.error);if(!l)return yield c.destroy().catch(this.error),e.error("Internal Server Error");e.success("OK"),r.emit("register.user",{ctx:e,register:l,user:c}),this.emit("register.user",{ctx:e,register:l,user:c})}))}confirm(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=yield Re.findOne({where:{token:t,state:!0},include:[{model:Fe,required:!0}]}).catch(this.error);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})}))}send(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=t,n=yield Re.findOne({where:{state:!0},include:[{model:Fe,required:!0,where:{[me.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})}))}getId(){return Ee(this,void 0,void 0,(function*(){const e=k();return(yield Re.count({where:{token:e}}))?this.getId():e}))}};Oe([h(),l("validation",{name:j.string().required(),date:j.date().required(),email:j.string().email().required(),username:j.string().min(4).empty(),password:j.string().min(5).required(),confirm:j.string().min(5).required()}),Ie(0,r()),Ie(1,v()),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object,$e]),Ae("design:returntype",Promise)],ct.prototype,"register",null),Oe([h("/confirm"),l("validation",{token:j.string().required()}),Ie(0,r()),Ie(1,v("token")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,$e]),Ae("design:returntype",Promise)],ct.prototype,"confirm",null),Oe([h("/send"),l("validation",{username:j.string().min(4).required()}),Ie(0,r()),Ie(1,v("username")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,$e]),Ae("design:returntype",Promise)],ct.prototype,"send",null),ct=Oe([g("/register"),u(et)],ct);let lt=class extends et{setup(e,t){return Ee(this,void 0,void 0,(function*(){if(0==(yield Fe.count())){const e=L(),r=yield Fe.create({name:"Admin",email:"admin@localhost",username:"admin",password:E("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),i={description:"API CORE",state:!0},n=yield xe.create(Object.assign({name:"admin"},i),Object.assign({},t));yield je.create({user_id:r.id,group_id:n.id},Object.assign({},t));const s=["audits","users","groups","routes"],o=["create","read","update","delete"];yield B(s,(e=>Ee(this,void 0,void 0,(function*(){yield B(o,(r=>Ee(this,void 0,void 0,(function*(){const s=yield Ce.create(Object.assign({name:`${e} ${r}`,route:`${e}.${r}`},i),Object.assign({},t));yield Be.create({group_id:n.id,permission_id:s.id},Object.assign({},t))}))))}))));const d=["delete","list","read","rename","upload","write"];yield B(d,(e=>Ee(this,void 0,void 0,(function*(){const r=yield Ce.create(Object.assign({name:`files ${e}`,route:`files.${e}`},i),Object.assign({},t));yield Be.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))));const a=["logs"];yield B(a,(e=>Ee(this,void 0,void 0,(function*(){const r=yield Ce.create(Object.assign({name:`${e} files`,route:`${e}.read`},i),Object.assign({},t));yield Be.create({group_id:n.id,permission_id:r.id},Object.assign({},t))}))))}e.success("OK")}))}};Oe([c(),Ie(0,r()),Ie(1,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,Object]),Ae("design:returntype",Promise)],lt.prototype,"setup",null),lt=Oe([g("/setup"),u(et)],lt);let yt=class extends tt{model(){return Fe}constructor(){super(),this.path=Se.API_HTTP_PUBLIC+"/avatar",Se.API_HTTP_PUBLIC&&pe(Se.API_HTTP_PUBLIC)&&!pe(this.path)&&ge(this.path)}avatar(e,t,r,i){return Ee(this,void 0,void 0,(function*(){if(t.length){const n=t[0].filename||"";if(n){const t=this.path+"/"+r.avatar;if(pe(t)&&he(t).isFile()&&ve(t),r.avatar=n,yield r.save(Object.assign({},i)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_delete(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&pe(i)&&ve(i),e.success("OK")}))}password(e,t,r,i,n){return Ee(this,void 0,void 0,(function*(){var s;const o=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);return t+=null!==(s=null==o?void 0:o.salt)&&void 0!==s?s:"",o&&o.password==E(t)?(o.salt=L(),o.password=E(r+o.salt),(yield o.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_get(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_delete(e,t,r){return Ee(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i)return i.token="",yield i.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r,i){return Ee(this,void 0,void 0,(function*(){const n=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(n){const t=yield this.token_new();return n.token=i.hash.encrypt(t),yield n.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return Ee(this,void 0,void 0,(function*(){var e;const t=k();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t}))}add(e,t){return Ee(this,void 0,void 0,(function*(){const r=L();yield this._add({ctx:e,body:{password:E(t+r),salt:r}})}))}all(e){return Ee(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return Ee(this,void 0,void 0,(function*(){if(r.id.toString()==t)return e.notFound("Record not found");yield this._del({ctx:e})}))}get(e){return Ee(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return Ee(this,void 0,void 0,(function*(){const r=L();yield this._set({ctx:e,body:t?{password:E(t+r),salt:r}:{}})}))}};Oe([h("/avatar"),l("auth"),l("upload",(e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32}))),Ie(0,r()),Ie(1,P()),Ie(2,Qe()),Ie(3,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,Array,Fe,Object]),Ae("design:returntype",Promise)],yt.prototype,"avatar",null),Oe([_("/avatar"),l("auth"),Ie(0,r()),Ie(1,Qe()),Ie(2,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,Fe,Object]),Ae("design:returntype",Promise)],yt.prototype,"avatar_delete",null),Oe([h("/password"),l("auth"),l("validation",{oldPassword:j.string().min(5).required(),newPassword:j.string().min(5).required()}),Ie(0,r()),Ie(1,v("oldPassword")),Ie(2,v("newPassword")),Ie(3,Qe()),Ie(4,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,String,Fe,Object]),Ae("design:returntype",Promise)],yt.prototype,"password",null),Oe([c("/token"),l("auth"),Ie(0,r()),Ie(1,Qe()),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,Fe,$e]),Ae("design:returntype",Promise)],yt.prototype,"token",null),Oe([c("/token/:id"),l("auth"),l("create"),Ie(0,r()),Ie(1,f("id")),Ie(2,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,$e]),Ae("design:returntype",Promise)],yt.prototype,"token_get",null),Oe([_("/token/:id"),l("auth"),l("delete"),Ie(0,r()),Ie(1,f("id")),Ie(2,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object]),Ae("design:returntype",Promise)],yt.prototype,"token_delete",null),Oe([c("/token/renew/:id"),l("auth"),l("update"),Ie(0,r()),Ie(1,f("id")),Ie(2,Ve()),Ie(3,n()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Object,$e]),Ae("design:returntype",Promise)],yt.prototype,"token_renew",null),Oe([h(),l("auth"),l("create"),l("validation",{name:j.string().required(),email:j.string().email().required(),username:j.string().min(4).required(),password:j.string().min(5).required(),description:j.string().empty(""),state:j.boolean().parse().required()}),Ie(0,r()),Ie(1,v("password")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],yt.prototype,"add",null),Oe([c(),l("auth"),l("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],yt.prototype,"all",null),Oe([_("/:id"),l("auth"),l("delete"),Ie(0,r()),Ie(1,f("id")),Ie(2,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Fe]),Ae("design:returntype",Promise)],yt.prototype,"del",null),Oe([c("/:id"),l("auth"),l("read"),Ie(0,r()),Ae("design:type",Function),Ae("design:paramtypes",[a]),Ae("design:returntype",Promise)],yt.prototype,"get",null),Oe([m("/:id"),l("auth"),l("update"),l("validation",{name:j.string().empty(),email:j.string().email().empty(),username:j.string().min(4).empty(),password:j.string().min(5).empty().filter(""),description:j.string().empty(),state:j.boolean().parse().empty()}),Ie(0,r()),Ie(1,v("password")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],yt.prototype,"set",null),yt=Oe([g("/users"),u(tt),Ae("design:paramtypes",[])],yt);let gt=class extends tt{model(){return je}groups(e,t){return Ee(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return Ee(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{user_id:t},include:[{model:xe,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r,i){return Ee(this,void 0,void 0,(function*(){const n=yield Fe.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){if(yield je.destroy(Object.assign({where:{user_id:n.id},individualHooks:!0},i)),r){let e=0;yield R(1e3);for(let t=0;t<r.length;t++)e=yield xe.count({where:{id:r[t]}}),e&&(yield je.create({user_id:n.id,group_id:r[t]},Object.assign({},i)))}return e.success("OK")}if(C(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Oe([c("/groups"),l("auth"),l("read","users"),Ie(0,r()),Ie(1,Qe()),Ae("design:type",Function),Ae("design:paramtypes",[a,Fe]),Ae("design:returntype",Promise)],gt.prototype,"groups",null),Oe([c("/:id/groups"),l("auth"),l("read","users"),Ie(0,r()),Ie(1,f("id")),Ae("design:type",Function),Ae("design:paramtypes",[a,String]),Ae("design:returntype",Promise)],gt.prototype,"all",null),Oe([m("/:id/groups"),l("auth"),l("update","users"),l("validation",{groups:j.array(j.number().parse())}),Ie(0,r()),Ie(1,f("id")),Ie(2,v("groups")),Ie(3,Ve()),Ae("design:type",Function),Ae("design:paramtypes",[a,String,Array,Object]),Ae("design:returntype",Promise)],gt.prototype,"set",null),gt=Oe([g("/users"),u(tt)],gt);export{$e as Application,Ne as Audit,rt as AuditsController,ke as Auth,it as AuthController,Je as Config,qe as Configs,et as ControllerBase,ot as CrudController,Se as Env,nt as FilesController,Le as Forgot,st as ForgotController,xe as Group,Be as GroupPermission,dt as GroupsController,at as GroupsPermissionsController,He as Log,Ue as Logs,ut as LogsController,be as Model,tt as ModelController,Ce as Permission,pt as PermissionsController,Re as Register,ct as RegisterController,Ve as ReqAudit,Ze as ReqAuth,Qe as ReqUser,Ke as Session,lt as SetupController,ze as Token,Fe as User,je as UserGroup,yt as UsersController,gt as UsersGroupsController,Xe as audit,Te as conn,Ye as crt,De as hooks,Ge as key};
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.4",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"main": "./dist/index.cjs.js",
|
|
6
7
|
"types": "./dist/index.d.ts",
|
|
7
8
|
"module": "./dist/index.esm.js",
|
|
@@ -18,8 +19,8 @@
|
|
|
18
19
|
"dist"
|
|
19
20
|
],
|
|
20
21
|
"scripts": {
|
|
21
|
-
"
|
|
22
|
-
"
|
|
22
|
+
"dev": "tsx-dev --watch --clear ./src/dev.ts",
|
|
23
|
+
"build": "rollup --bundleConfigAsCjs -c rollup.config.js"
|
|
23
24
|
},
|
|
24
25
|
"repository": {
|
|
25
26
|
"type": "git",
|
|
@@ -45,14 +46,15 @@
|
|
|
45
46
|
},
|
|
46
47
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
47
48
|
"dependencies": {
|
|
48
|
-
"@andrewcaires/express": "^1.
|
|
49
|
-
"@andrewcaires/node": "^1.
|
|
50
|
-
"@andrewcaires/sequelize": "^1.
|
|
51
|
-
"@andrewcaires/utils.js": "^0.
|
|
49
|
+
"@andrewcaires/express": "^1.2.0",
|
|
50
|
+
"@andrewcaires/node": "^1.2.0",
|
|
51
|
+
"@andrewcaires/sequelize": "^1.1.2",
|
|
52
|
+
"@andrewcaires/utils.js": "^0.4.0",
|
|
52
53
|
"cors": "^2.8.5",
|
|
53
54
|
"dotenv": "^16.4.5",
|
|
54
|
-
"express-session": "^1.18.
|
|
55
|
+
"express-session": "^1.18.1",
|
|
55
56
|
"jsonwebtoken": "^9.0.2",
|
|
57
|
+
"tsx": "^4.19.1",
|
|
56
58
|
"ws": "^8.18.0"
|
|
57
59
|
},
|
|
58
60
|
"devDependencies": {
|
|
@@ -62,13 +64,13 @@
|
|
|
62
64
|
"@types/cors": "^2.8.17",
|
|
63
65
|
"@types/express-session": "^1.18.0",
|
|
64
66
|
"@types/jsonwebtoken": "^9.0.7",
|
|
65
|
-
"@types/node": "^22.7.
|
|
67
|
+
"@types/node": "^22.7.5",
|
|
66
68
|
"@types/ws": "^8.5.12",
|
|
67
|
-
"eslint": "^9.
|
|
69
|
+
"eslint": "^9.12.0",
|
|
68
70
|
"mariadb": "^3.3.2",
|
|
69
71
|
"rollup": "^4.24.0",
|
|
70
72
|
"rollup-plugin-dts": "^6.1.1",
|
|
71
73
|
"tslib": "^2.7.0",
|
|
72
|
-
"typescript-eslint": "^8.
|
|
74
|
+
"typescript-eslint": "^8.9.0"
|
|
73
75
|
}
|
|
74
76
|
}
|