@andrewcaires/api 3.2.7 → 4.0.0
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 +141 -88
- package/dist/index.esm.js +2 -2
- package/package.json +14 -15
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api
|
|
2
|
+
* @andrewcaires/api v4.0.0
|
|
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"),i=require("ws"),o=require("sequelize"),s=require("dotenv"),n=require("fs"),d=require("express-session"),a=require("jsonwebtoken"),l=require("path");function u(e,t,r,i){var o,s=arguments.length,n=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,i);else for(var d=e.length-1;d>=0;d--)(o=e[d])&&(n=(s<3?o(n):s>3?o(t,r,n):o(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function c(e,t){return function(r,i){t(r,i,e)}}function p(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function g(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(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?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,s.config();class h{static getBool(e,t){return r.toBool(h.getString(e,t.toString()))}static getInt(e,t){return parseInt(h.getString(e,t.toString()))}static getMs(e,t){return r.parseMs(h.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}h.API_CONSOLE_ERROR=h.getBool("API_CONSOLE_ERROR",!1),h.API_DEFAULT_PATH=h.getString("API_DEFAULT_PATH","/api"),h.API_DB_DATABASE=h.getString("API_DB_DATABASE",""),h.API_DB_HOST=h.getString("API_DB_HOST","127.0.0.1"),h.API_DB_PASSWORD=h.getString("API_DB_PASSWORD",""),h.API_DB_PORT=h.getInt("API_DB_PORT",3306),h.API_DB_TYPE=h.getString("API_DB_TYPE",""),h.API_DB_USERNAME=h.getString("API_DB_USERNAME","root"),h.API_DB_LOG=h.getBool("API_DB_LOG",!1),h.API_DB_PREFIX=h.getString("API_DB_PREFIX",""),h.API_DB_TIMEZONE=h.getString("API_DB_TIMEZONE","+00:00"),h.API_HTTP_CRT=h.getString("API_HTTP_CRT",""),h.API_HTTP_KEY=h.getString("API_HTTP_KEY",""),h.API_HTTP_PORT=h.getInt("API_HTTP_PORT",3e3),h.API_HTTP_PUBLIC=h.getString("API_HTTP_PUBLIC",""),h.API_HTTP_CROSS=h.getBool("API_HTTP_CROSS",!1),h.API_HTTP_HYBRID=h.getBool("API_HTTP_HYBRID",!1),h.API_HTTP_REDIRECT=h.getString("API_HTTP_REDIRECT",""),h.API_KEY_HASH=h.getString("API_KEY_HASH",""),h.API_KEY_HEADER=h.getString("API_KEY_HEADER","api_key"),h.API_MODEL_LIMIT=h.getInt("API_MODEL_LIMIT",10),h.API_MODEL_LIMIT_MAX=h.getInt("API_MODEL_LIMIT_MAX",500),h.API_NOTFOUND_REDIRECT=h.getString("API_NOTFOUND_REDIRECT",""),h.API_SLEEP_AUTH=h.getMs("API_SLEEP_AUTH","2s"),h.API_SLEEP_FORGOT=h.getMs("API_SLEEP_FORGOT","5s"),h.API_SLEEP_REGISTRY=h.getMs("API_SLEEP_REGISTRY","5s"),h.API_SESSION_NAME=h.getString("API_SESSION_NAME","session.id"),h.API_SESSION_LIFETIME=h.getMs("API_SESSION_LIFETIME","1d"),h.API_SESSION_SECRET=h.getString("API_SESSION_SECRET","yoursecret"),h.API_TOKEN_CRT=h.getString("API_TOKEN_CRT",""),h.API_TOKEN_KEY=h.getString("API_TOKEN_KEY",""),h.API_TOKEN_FORGOT=h.getMs("API_TOKEN_LIFETIME","1d"),h.API_TOKEN_HEADER=h.getString("API_TOKEN_HEADER","authorization"),h.API_TOKEN_LIFETIME=h.getMs("API_TOKEN_LIFETIME","1d"),h.API_TOKEN_RENEW=h.getMs("API_TOKEN_RENEW","1d"),h.API_UPLOAD_COUNT=h.getInt("API_UPLOAD_COUNT",1),h.API_UPLOAD_FIELD=h.getString("API_UPLOAD_FIELD","upload"),h.API_UPLOAD_SIZE=h.getInt("API_UPLOAD_SIZE",2),h.API_UPLOAD_TEMP=h.getString("API_UPLOAD_TEMP","./temp"),h.API_WEBSOCKET_START=h.getBool("API_WEBSOCKET_START",!1);class y{static connect(e){const t="connect_"+h.API_DB_TYPE.toLowerCase();if(t in y)return y[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new o.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mariadb",logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}static connect_memory(){return new o.Sequelize("sqlite::memory:",{logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}static connect_mysql(e){return new o.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mysql",logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}static connect_postgres(e){return new o.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"postgres",logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}static connect_sqlite(e){return new o.Sequelize({dialect:"sqlite",storage:e.database,logging:h.API_DB_LOG,define:{timestamps:!1}})}}const m=y.connect({database:h.API_DB_DATABASE,username:h.API_DB_USERNAME,password:h.API_DB_PASSWORD,hostname:h.API_DB_HOST,hostport:h.API_DB_PORT});class _ extends o.Model{}_.init({secret:o.DataTypes.STRING,logout:o.DataTypes.DATE,useragent:o.DataTypes.STRING},{sequelize:m,modelName:h.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class I extends o.Model{}I.init({token:o.DataTypes.STRING,timestamp:o.DataTypes.BIGINT,state:o.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class x extends o.Model{}x.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class v extends o.Model{}v.init({},{sequelize:m,modelName:h.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),v.removeAttribute("id");class P extends o.Model{}P.init({token:o.DataTypes.STRING,state:o.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class f extends o.Model{}f.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class A extends o.Model{}A.init({name:o.DataTypes.STRING,email:o.DataTypes.STRING,username:o.DataTypes.STRING,password:o.DataTypes.STRING,salt:o.DataTypes.STRING,token:o.DataTypes.STRING,avatar:o.DataTypes.STRING,date:o.DataTypes.DATEONLY,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password","salt","token"]}},scopes:{password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}});class C extends o.Model{}C.init({},{sequelize:m,modelName:h.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),C.removeAttribute("id");class E extends o.Model{}E.init({key:o.DataTypes.STRING,value:o.DataTypes.STRING},{sequelize:m,modelName:h.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),E.removeAttribute("id");class S extends o.Model{}S.init({type:o.DataTypes.STRING,source:o.DataTypes.STRING,message:o.DataTypes.TEXT},{sequelize:m,modelName:h.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class w extends o.Model{}w.init({session:o.DataTypes.STRING,json:o.DataTypes.TEXT,expired:o.DataTypes.BIGINT},{sequelize:m,modelName:h.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),w.removeAttribute("id"),A.hasMany(_),_.belongsTo(A),A.hasMany(I),I.belongsTo(A),A.hasMany(P),P.belongsTo(A),x.hasMany(v),v.belongsTo(x),f.hasMany(v),v.belongsTo(f),A.hasMany(C),C.belongsTo(A),x.hasMany(C),C.belongsTo(x);class O{static write(e,r,i){return g(this,void 0,void 0,(function*(){yield O.writeRaw(t.LogColor.White,"",e,r,i)}))}static error(e,r,i){return g(this,void 0,void 0,(function*(){yield O.writeRaw(t.LogColor.Red,"error",e,r,i)}))}static info(e,r,i){return g(this,void 0,void 0,(function*(){yield O.writeRaw(t.LogColor.Cyan,"info",e,r,i)}))}static success(e,r,i){return g(this,void 0,void 0,(function*(){yield O.writeRaw(t.LogColor.Green,"success",e,r,i)}))}static warning(e,r,i){return g(this,void 0,void 0,(function*(){yield O.writeRaw(t.LogColor.Yellow,"warning",e,r,i)}))}static writeRaw(e,r,i,o,s){return g(this,void 0,void 0,(function*(){s&&t.Log.console(e,r,i),m&&(yield S.create({type:r,source:o,message:i}).catch((()=>null)))}))}}const T=e=>n.existsSync(e)?n.readFileSync(e):void 0,R={http:T(h.API_HTTP_CRT),token:T(h.API_TOKEN_CRT)},D={http:T(h.API_HTTP_KEY),token:T(h.API_TOKEN_KEY)};class M extends d.Store{constructor(){super(),this.all=e=>g(this,void 0,void 0,(function*(){e=e||r.noop;const t=yield w.findAll({attributes:["session"],where:{expired:{[o.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>g(this,void 0,void 0,(function*(){yield w.destroy().catch(r.noop),e&&e()})),this.destroy=(e,t)=>g(this,void 0,void 0,(function*(){yield w.destroy({where:{session:e}}).catch(r.noop),t&&t()})),this.expired=()=>g(this,void 0,void 0,(function*(){yield w.destroy({where:{expired:{[o.Op.lt]:Date.now()}}}).catch(r.noop)})),this.get=(e,t)=>g(this,void 0,void 0,(function*(){t=t||r.noop;const i=yield w.findOne({where:{session:e,expired:{[o.Op.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(i){const e=JSON.parse(i.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield i.destroy().catch(r.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>g(this,void 0,void 0,(function*(){e&&e(null,(yield w.count().catch(r.noop))||0)})),this.set=(e,t,i)=>g(this,void 0,void 0,(function*(){i=i||r.noop;const o=Date.now()+h.API_SESSION_LIFETIME,s=JSON.stringify(t),[n,d]=(yield w.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:o}}).catch(r.noop))||[];n&&(d||(n.json=s,n.expired=o,yield n.save().catch(r.noop))),i()})),this.loop=r.loop(this.expired,3e4),this.loop.start()}}class F{static create(e){return g(this,void 0,void 0,(function*(){if(!D.token)return{error:"Key not found"};const{id:t}=e,i=r.uuidv4(),o=yield _.create({secret:i,userId:t}).catch(F.error);if(!o)return{error:"Internal Server Error"};return{auth:o,token:a.sign({id:t,secret:i},D.token,F.options())}}))}static destroy(e){return g(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){O.error(e.message,"api.token",h.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:h.API_TOKEN_LIFETIME+"ms"}}static renew(e){return g(this,void 0,void 0,(function*(){if(!D.token)return{error:"Key not found"};const{error:t,decode:i}=F.verify(e,h.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield A.findOne({where:{id:e,state:!0}}).catch(F.error);if(i){const o=yield _.findOne({where:{secret:t,userId:i.id}}).catch(F.error);if(o&&!o.logout){o.secret=r.uuidv4(),yield o.save().catch(F.error);return{auth:o,token:a.sign({id:e,secret:o.secret},D.token,F.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return g(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield A.findOne({where:{token:t,state:!0}}).catch(F.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield _.findOrCreate({where:{secret:t,userId:i.id},defaults:{secret:t,userId:i.id}}).catch(F.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:o}=F.verify(t);if(i)return{error:i};if(o){const{id:e,secret:t}=o;if(e&&t){const r=yield A.findOne({where:{id:e,state:!0}}).catch(F.error);if(r){const e=yield _.findOne({where:{secret:t,userId:r.id}}).catch(F.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!R.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:a.verify(e,R.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class b extends e.Application{constructor(e){super(e,{cert:R.http,cross:h.API_HTTP_CROSS,hybrid:h.API_HTTP_HYBRID,key:D.http,notfound:h.API_NOTFOUND_REDIRECT,path:h.API_DEFAULT_PATH,port:h.API_HTTP_PORT,public:h.API_HTTP_PUBLIC,redirect:h.API_HTTP_REDIRECT,session:{store:new M,name:h.API_SESSION_NAME,secret:h.API_SESSION_SECRET,cookie:{maxAge:h.API_SESSION_LIFETIME},genid:r.uuidv4}}),this.hash=new t.Hash(h.API_KEY_HASH)}error(e,t){O.error(e.message,t,h.API_CONSOLE_ERROR)}log(e,t){O.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return g(this,void 0,void 0,(function*(){yield m.sync(),yield e.listen.call(this),h.API_WEBSOCKET_START&&this.server&&(this._webSocket=new i.Server({server:this.server,verifyClient:(e,t)=>t(h.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>g(this,void 0,void 0,(function*(){t.url||(t.url="");const i=t.url.length<=1?"":t.url.replace(/\//g,".");let o;e.on("message",(r=>g(this,void 0,void 0,(function*(){if(o)try{const s=JSON.parse(r);this.emit("ws.message"+i,{data:s,message:r,req:t,user:o,ws:e})}catch(s){this.emit("ws.message"+i,{message:r,req:t,user:o,ws:e})}else{const{user:s}=yield F.user("",r.toString(),this);s&&(o=s,this.emit("ws.connection"+i,{req:t,user:o,ws:e}))}o||e.close()})))),e.on("close",(()=>{o&&this.emit("ws.close"+i,{user:o,ws:e})})),yield r.sleep(2e3),o||e.close()})))))}))}websocket(){return this._webSocket}}class k{static all(){return g(this,void 0,void 0,(function*(){const e=yield E.findAll().catch(k.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return g(this,void 0,void 0,(function*(){return((yield E.destroy({where:{key:e}}).catch(k.error))||0)>0}))}static error(e){O.error(e.message,"api.config",h.API_CONSOLE_ERROR)}static get(e){return g(this,arguments,void 0,(function*(e,t=""){const[r]=(yield E.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(k.error))||[];return r?r.value:t}))}static set(e,t){return g(this,void 0,void 0,(function*(){const[r]=(yield E.findOrCreate({where:{key:e}}).catch(k.error))||[];r&&(r.value=t,yield r.save().catch(k.error))}))}}const q=e.parameterFactory((({ctx:e})=>e.req.auth)),N=e.parameterFactory((({ctx:e})=>e.req.user));class B{static all(e,t){return g(this,void 0,void 0,(function*(){return yield f.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:v,required:!0,include:[{model:x,required:!0,where:{state:!0},include:[{model:C,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{O.error(e.message,"api.permission",h.API_CONSOLE_ERROR)}))}))}static get(e){return g(this,void 0,void 0,(function*(){const t=yield B.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return g(this,void 0,void 0,(function*(){const r=yield B.all(e,{name:t});return!!r&&r.length>0}))}}class L extends r.EventEmitter{auth(e,t,r,i,o){return g(this,void 0,void 0,(function*(){const{auth:s,error:n,user:d}=yield F.user(t,r,o);return n?e.error(n):s&&d?s.useragent&&s.useragent!=i?e.error("Invalid token"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,i){return g(this,void 0,void 0,(function*(){i.auth&&i.user&&(i.useragent?i.useragent!=t&&i.regenerate(r.noop):(i.useragent=t,i.save(r.noop))),e.next()}))}error(e){O.error(e.message,"api.controller",h.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return g(this,void 0,void 0,(function*(){return r?(yield B.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(t,r){r.path||(r.path=h.API_UPLOAD_TEMP),r.size||(r.size=h.API_UPLOAD_SIZE),r.field||(r.field=h.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}validation(e,t){return g(this,void 0,void 0,(function*(){const{error:i,value:o}=yield r.Validation.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=o,e.next()}))}write(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}u([c(0,e.Ctx()),c(1,e.Headers(h.API_KEY_HEADER)),c(2,e.Headers(h.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,String,b]),p("design:returntype",Promise)],L.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),p("design:type",Function),p("design:paramtypes",[e.Context,String,Object]),p("design:returntype",Promise)],L.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,N()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,N()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",void 0)],L.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",Promise)],L.prototype,"validation",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,N()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"write",null),exports.AuthController=class extends L{login(e,i,s,n,d){return g(this,void 0,void 0,(function*(){var a;yield r.sleep(h.API_SLEEP_AUTH);const l=yield A.scope("password").findOne({where:{[o.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(n+=null!==(a=null==l?void 0:l.salt)&&void 0!==a?a:"",!l||l.password!=t.sha256(n))return e.notFound("Invalid username or password"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield P.findOne({where:{state:!0,userId:l.id}}).catch(this.error);if(u)return e.error("Activation required"),d.emit("auth.activation",{ctx:e,register:u,user:l}),void this.emit("auth.activation",{ctx:e,register:u,user:l});if(!l.state)return e.notFound("Invalid username or password"),d.emit("auth.failure",{ctx:e,user:l}),void this.emit("auth.failure",{ctx:e,user:l});const{auth:c,error:p,token:g}=yield F.create(l);return p?(e.error(p),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):c&&g?(c.useragent=i,yield c.save().catch(this.error),e.json({token:g}),d.emit("auth.login",{auth:c,ctx:e,user:l}),void this.emit("auth.login",{auth:c,ctx:e,user:l})):(e.error("Internal Server Error"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return g(this,void 0,void 0,(function*(){if(yield F.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 g(this,void 0,void 0,(function*(){const{auth:o,error:s,token:n}=yield F.renew(r);return s?e.error(s):o?(o.useragent=t,yield o.save().catch(this.error),e.json({token:n}),i.emit("auth.renew",{auth:o,ctx:e}),void this.emit("auth.renew",{auth:o,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return g(this,void 0,void 0,(function*(){const r=yield B.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,String,b]),p("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,q()),c(2,N()),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,_,A,b]),p("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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,b]),p("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,N()),p("design:type",Function),p("design:paramtypes",[e.Context,A]),p("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(L)],exports.AuthController),exports.FilesController=class extends L{directory(){return h.API_HTTP_PUBLIC||"./"}files(e){return g(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=l.join(this.directory(),t);if(!n.existsSync(i)||!n.statSync(i).isDirectory())return e.notFound("Path not Found");let o=[];return o=n.readdirSync(i),o=o.map((e=>this.info(l.join(i,e)))),o=o.filter(r.isDef),Object.assign(Object.assign({},this.info(i)),{files:o})}))}access(e,t,r){return g(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 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"}},u([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.FilesController.prototype,"files",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,N()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(L)],exports.FilesController),exports.ForgotController=class extends L{check(e,t){return g(this,void 0,void 0,(function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("User not found");i.token=r.uniqueID(),yield i.save(),e.json({token:i.token})}))}forgot(e,t,i){return g(this,void 0,void 0,(function*(){yield r.sleep(h.API_SLEEP_FORGOT);const s=t,n=yield A.findOne({where:{[o.Op.or]:[{email:s},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const d=r.uniqueID(),a=Date.now()+6e4*h.API_TOKEN_FORGOT,l=yield I.create({token:d,timestamp:a,state:!0,userId:n.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:l,user:n}),this.emit("forgot.send",{ctx:e,forgot:l,user:n})}))}reset(e,r,i,o){return g(this,void 0,void 0,(function*(){const s=yield this.find(r);if(!s)return e.notFound("User not found");s.state=!1,yield s.save().catch(this.error),s.user.password=t.sha256(i),yield s.user.save().catch(this.error),e.success("OK"),o.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})}))}find(e){return g(this,void 0,void 0,(function*(){return yield I.findOne({where:{token:e,state:!0},include:[{model:A,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")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,b]),p("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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,b]),p("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(L)],exports.ForgotController),exports.ModelController=class extends L{constructor(){super(...arguments),this._columns=[]}_add(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,body:i}){const o=yield this.model().create(Object.assign(Object.assign({},t.req.body),i||{}),r||{}).catch(this.error);if(o){const r=this.key();return t.prepare(e.Status.OK,{[r]:o.getDataValue(r)}),o}t.error("Internal Server Error")}))}_all(t){return g(this,arguments,void 0,(function*({ctx:t,options:i,callback:s,scope:n}){var d,a,l,u,c,p;const g=this.scope(n),y=Object.assign({},i||{});y.where=Object.assign({},y.where||{});const m=t.req.query.limit,_=r.isString(m)?parseInt(m):h.API_MODEL_LIMIT;y.limit=_>=0?Math.min(_,h.API_MODEL_LIMIT_MAX):void 0;const I=t.req.query.offset;if(r.isString(I)){const e=I?parseInt(I):0;y.offset=e>0?e:void 0}const x=[],v=this.columns(),P=e=>v.indexOf(e)>=0,f=null===(d=t.req.query.asc)||void 0===d?void 0:d.toString();f&&f.length&&x.push(...f.split(",").filter(P).map((e=>[e,"ASC"])));const A=null===(a=t.req.query.desc)||void 0===a?void 0:a.toString();A&&A.length&&x.push(...A.split(",").filter(P).map((e=>[e,"DESC"]))),x.length&&(y.order=x);const C=[],E=null===(l=t.req.query.search)||void 0===l?void 0:l.toString();(r.isArray(y.attributes)?y.attributes:v).filter(r.isString).forEach((e=>{var r;if(E&&E.length&&C.push({[e]:{[o.Op.like]:`%${E}%`}}),"search_"+e in t.req.query){const i=null===(r=t.req.query["search_"+e])||void 0===r?void 0:r.toString();i&&i.length&&C.push({[e]:{[o.Op.like]:`%${i}%`}})}})),C.length&&(y.where=Object.assign(Object.assign({},y.where),{[o.Op.or]:[...C]}));const S=null!==(u=yield g.count(Object.assign(Object.assign({},y),{col:v[0]})).catch(this.error))&&void 0!==u?u:0,w=yield g.findAll(y).catch(this.error),O={count:S,limit:null!==(c=y.limit)&&void 0!==c?c:-1,offset:null!==(p=y.offset)&&void 0!==p?p:0};return w?(t.prepare(e.Status.OK,Object.assign(Object.assign({},O),{records:s?yield s(w):w})),Object.assign(Object.assign({},O),{records:w})):(t.error("Internal Server Error"),Object.assign(Object.assign({},O),{records:[]}))}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return g(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 o=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i})})).catch(this.error);return o?(e.success("OK"),o):(e.notFound("Record not found"),0)}))}error(e){e.sql?O.error(e.message+"\n"+e.sql,"api.controller.sql",h.API_CONSOLE_ERROR):super.error(e)}_get(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,callback:i,scope:o}){const s=this.key(),{[s]:n}=t.req.params,d=yield this.scope(o).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[s]:n})})).catch(this.error);return d?(t.prepare(e.Status.OK,i?yield i(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 g(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=this.key(),{[i]:o}=e.req.params,[s]=(yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:o})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=u([e.Extends(L)],exports.ModelController),exports.CrudController=class extends exports.ModelController{add(e){return g(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}create(){return{}}del(e){return g(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return g(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return g(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return g(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return g(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}},u([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationAdd"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationSet"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"set",null),u([c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),u([c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("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 x}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=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return v}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:f,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,i){return g(this,void 0,void 0,(function*(){const o=yield x.findByPk(t,{attributes:["id"]}).catch(this.error);if(o){const t=o.id;if(yield v.destroy({where:{groupId:t}}),i){let e=0;for(let r=0;r<i.length;r++)e=yield f.count({where:{id:i[r]}}),e&&(yield v.create({groupId:t,routeId:i[r]}))}return e.success("OK")}if(r.isNull(o))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")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),u([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")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return S}all(e,t,r){return g(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","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),p("design:type",Function),p("design:paramtypes",[e.Context,String,String]),p("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends L{register(e,i,s){return g(this,void 0,void 0,(function*(){yield r.sleep(h.API_SLEEP_REGISTRY);const{name:n,date:d,email:a,username:l,password:u,confirm:c}=i,p=l||a,g=t.sha256(u);if(yield A.count({where:{[o.Op.or]:[{email:a},{username:p}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=t.sha256(c))return e.error("Invalid password");const y=yield A.create({name:n,email:a,username:p,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const m=yield P.create({token:yield this.getId(),userId:y.id,state:!0}).catch(this.error);if(!m)return y.destroy(),e.error("Internal Server Error");e.success("OK"),s.emit("register.user",{ctx:e,register:m,user:y}),this.emit("register.user",{ctx:e,register:m,user:y})}))}confirm(e,t,r){return g(this,void 0,void 0,(function*(){const i=yield P.findOne({where:{token:t,state:!0},include:[{model:A,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 g(this,void 0,void 0,(function*(){const i=t,s=yield P.findOne({where:{state:!0},include:[{model:A,required:!0,where:{[o.Op.or]:[{email:i},{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 g(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield P.count({where:{token:e}}))?this.getId():e}))}},u([e.Post(),e.Middleware("validation",{name:r.Validation.string().required(),date:r.Validation.string().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()),p("design:type",Function),p("design:paramtypes",[e.Context,Object,b]),p("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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,b]),p("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()),p("design:type",Function),p("design:paramtypes",[e.Context,String,b]),p("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(L)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return f}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=u([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends L{setup(e){return g(this,void 0,void 0,(function*(){if(0==(yield A.count())){const e=r.uniqueID(),i=yield A.create({name:"Admin",email:"admin@localhost",username:"admin",password:t.sha256("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),o={description:"API CORE",state:!0},s=yield x.create(Object.assign({name:"admin"},o));yield C.create({userId:i.id,groupId:s.id});const n=["read","write"],d=["users","groups","routes"];yield r.forEachSeries(d,(e=>g(this,void 0,void 0,(function*(){yield r.forEachSeries(n,(t=>g(this,void 0,void 0,(function*(){const r=e+"."+t,i=yield f.create(Object.assign({name:r},o));yield v.create({groupId:s.id,routeId:i.id})}))))}))));const a=[...n,"delete","list","rename","upload"];yield r.forEachSeries(a,(e=>g(this,void 0,void 0,(function*(){const t="files."+e,r=yield f.create(Object.assign({name:t},o));yield v.create({groupId:s.id,routeId:r.id})}))));const l=yield f.create(Object.assign({name:"logs.read"},o));yield v.create({groupId:s.id,routeId:l.id})}e.success("OK")}))}},u([e.Get(),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=u([e.Controller("/setup"),e.Extends(L)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return A}constructor(){super(),this.dir=h.API_HTTP_PUBLIC+"/avatar",h.API_HTTP_PUBLIC&&n.existsSync(h.API_HTTP_PUBLIC)&&!n.existsSync(this.dir)&&n.mkdirSync(this.dir)}avatar(e,t,r){return g(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=i,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return g(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="",(yield t.save().catch(this.error))&&n.existsSync(r)&&n.rmSync(r),e.success("OK")}))}password(e,i,o,s){return g(this,void 0,void 0,(function*(){var n;const d=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return i+=null!==(n=null==d?void 0:d.salt)&&void 0!==n?n:"",d&&d.password==t.sha256(i)?(d.salt=r.uniqueID(),d.password=t.sha256(o+d.salt),(yield d.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return g(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 g(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){return g(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save().catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r){return g(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=r.hash.encrypt(t),yield i.save().catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return g(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield this.model().count({where:{token:e}}))?this.token_new():e}))}add(e,i){return g(this,void 0,void 0,(function*(){const o=r.uniqueID();yield this._add({ctx:e,body:{password:t.sha256(i+o),salt:o}})}))}all(e){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return g(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return g(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,i){return g(this,void 0,void 0,(function*(){const o=r.uniqueID();yield this._set({ctx:e,body:i?{password:t.sha256(i+o),salt:o}:{}})}))}},u([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,N()),p("design:type",Function),p("design:paramtypes",[e.Context,Array,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Get("/avatar/remove"),e.Middleware("auth"),c(0,e.Ctx()),c(1,N()),p("design:type",Function),p("design:paramtypes",[e.Context,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"avatar_remove",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,N()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,N()),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,A,b]),p("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,b]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Get("/token/remove/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_remove",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,b]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([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")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,N()),c(2,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,A,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([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")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),p("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return C}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:x,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,i){return g(this,void 0,void 0,(function*(){const o=yield A.findByPk(t,{attributes:["id"]}).catch(this.error);if(o){if(yield C.destroy({where:{userId:o.id}}),i){let e=0;for(let t=0;t<i.length;t++)e=yield x.count({where:{id:i[t]}}),e&&(yield C.create({userId:o.id,groupId:i[t]}))}return e.success("OK")}if(r.isNull(o))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([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")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=b,exports.Auth=_,exports.Config=k,exports.Configs=E,exports.ControllerBase=L,exports.Database=y,exports.Env=h,exports.Forgot=I,exports.Group=x,exports.GroupRoute=v,exports.Log=S,exports.Logs=O,exports.Permission=B,exports.Register=P,exports.ReqAuth=q,exports.ReqUser=N,exports.Route=f,exports.Session=w,exports.Token=F,exports.User=A,exports.UserGroup=C,exports.crt=R,exports.key=D,exports.sequelize=m;
|
|
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_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 m={afterCreate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;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()),userId:null!==(i=null==t?void 0:t.userId)&&void 0!==i?i:null}).catch(r.noop)})),afterUpdate:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;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}),userId:null!==(i=null==t?void 0:t.userId)&&void 0!==i?i:null}).catch(r.noop)})),afterDestroy:(e,t)=>y(void 0,void 0,void 0,(function*(){var o,s,i;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()),userId:null!==(i=null==t?void 0:t.userId)&&void 0!==i?i:null}).catch(r.noop)}))};exports.Auth=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Auth.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Auth.prototype,"deletedAt",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Auth.prototype,"userId",void 0),exports.Auth=l([s.Database(h),s.ModelName("auth")],exports.Auth),exports.Register=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Register.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Register.prototype,"deletedAt",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Register.prototype,"userId",void 0),exports.Register=l([s.Database(h),s.ModelName("register")],exports.Register),exports.Group=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Group.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Group.prototype,"deletedAt",void 0),l([s.HasMany((()=>exports.UserGroup),"groupId"),g("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),l([s.HasMany((()=>exports.UserGroup),"groupId"),g("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=l([s.Database(h),s.ModelName("group"),s.Hooks(m)],exports.Group),exports.UserGroup=class extends v{},l([s.CreatedAt,g("design:type",Date)],exports.UserGroup.prototype,"createdAt",void 0),l([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.UserGroup.prototype,"groupId",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.UserGroup.prototype,"userId",void 0),exports.UserGroup=l([s.Database(h),s.ModelName("users_groups"),s.Hooks(m)],exports.UserGroup),exports.User=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.User.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.User.prototype,"deletedAt",void 0),l([s.HasMany((()=>exports.Audit),"userId"),g("design:type",Array)],exports.User.prototype,"audits",void 0),l([s.HasMany((()=>exports.Auth),"userId"),g("design:type",Array)],exports.User.prototype,"auths",void 0),l([s.HasMany((()=>exports.Register),"userId"),g("design:type",Array)],exports.User.prototype,"registers",void 0),l([s.HasMany((()=>exports.UserGroup),"userId"),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(m)],exports.User),exports.Audit=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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.CreatedAt,g("design:type",Date)],exports.Audit.prototype,"createdAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Audit.prototype,"deletedAt",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Audit.prototype,"userId",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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Configs.prototype,"updatedAt",void 0),exports.Configs=l([s.Database(h),s.ModelName("configs"),s.Hooks(m)],exports.Configs),exports.Forgot=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Forgot.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Forgot.prototype,"deletedAt",void 0),l([s.BelongsTo((()=>exports.User)),g("design:type",Number)],exports.Forgot.prototype,"userId",void 0),exports.Forgot=l([s.Database(h),s.ModelName("forgot")],exports.Forgot),exports.Route=class extends v{},l([s.Integer(),s.PrimaryKey,s.NotNull,s.AutoIncrement,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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Route.prototype,"updatedAt",void 0),l([s.DeletedAt,g("design:type",Date)],exports.Route.prototype,"deletedAt",void 0),l([s.HasMany((()=>exports.GroupRoute),"routeId"),g("design:type",Array)],exports.Route.prototype,"groups_routes",void 0),exports.Route=l([s.Database(h),s.ModelName("route"),s.Hooks(m)],exports.Route),exports.GroupRoute=class extends v{},l([s.CreatedAt,g("design:type",Date)],exports.GroupRoute.prototype,"createdAt",void 0),l([s.BelongsTo((()=>exports.Group)),g("design:type",Number)],exports.GroupRoute.prototype,"groupId",void 0),l([s.BelongsTo((()=>exports.Route)),g("design:type",Number)],exports.GroupRoute.prototype,"routeId",void 0),exports.GroupRoute=l([s.Database(h),s.ModelName("groups_routes"),s.Hooks(m)],exports.GroupRoute),exports.Log=class extends v{},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,"createdAt",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,"createdAt",void 0),l([s.UpdatedAt,g("design:type",Date)],exports.Session.prototype,"updatedAt",void 0),exports.Session=l([s.Database(h),s.ModelName("session")],exports.Session);class A{static write(e,r,o){return y(this,void 0,void 0,(function*(){yield A.writeRaw(t.LogColor.White,"",e,r,o)}))}static error(e,r,o){return y(this,void 0,void 0,(function*(){yield A.writeRaw(t.LogColor.Red,"error",e,r,o)}))}static info(e,r,o){return y(this,void 0,void 0,(function*(){yield A.writeRaw(t.LogColor.Cyan,"info",e,r,o)}))}static success(e,r,o){return y(this,void 0,void 0,(function*(){yield A.writeRaw(t.LogColor.Green,"success",e,r,o)}))}static warning(e,r,o){return y(this,void 0,void 0,(function*(){yield A.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,I={http:f(x.API_HTTP_CRT),token:f(x.API_TOKEN_CRT)},_={http:f(x.API_HTTP_KEY),token:f(x.API_TOKEN_KEY)};class C 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 S{static create(e){return y(this,void 0,void 0,(function*(){if(!_.token)return{error:"Key not found"};const{id:t}=e,o=r.uuidv4(),s=yield exports.Auth.create({secret:o,userId:t}).catch(S.error);if(!s)return{error:"Internal Server Error"};return{auth:s,token:p.sign({id:t,secret:o},_.token,S.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){A.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(!_.token)return{error:"Key not found"};const{error:t,decode:o}=S.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(S.error);if(o){const s=yield exports.Auth.findOne({where:{secret:t,userId:o.id}}).catch(S.error);if(s&&!s.logout){s.secret=r.uuidv4(),yield s.save().catch(S.error);return{auth:s,token:p.sign({id:e,secret:s.secret},_.token,S.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(S.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,userId:o.id},defaults:{secret:t,userId:o.id}}).catch(S.error))||[];if(r)return{auth:r,user:o}}return{error:"Access denied"}}const{error:o,decode:s}=S.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(S.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,userId:r.id}}).catch(S.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!I.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:p.verify(e,I.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class P extends e.Application{constructor(e){super(e,{cert:I.http,cross:x.API_HTTP_CROSS,hybrid:x.API_HTTP_HYBRID,key:_.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 C,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){A.error(e.message,t,x.API_CONSOLE_ERROR)}log(e,t){A.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 S.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}},{userId:o})).catch(O.error))||0)>0}))}static error(e){A.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}},{userId:s})).catch(O.error))||[];i&&(i.value=t,yield i.save().catch(O.error))}))}}const w=e.parameterFactory((({ctx:e})=>e.req.auth)),E=e.parameterFactory((({ctx:e})=>e.req.user));class R{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:{userId:e.id}}]}]}]}).catch((e=>{A.error(e.message,"api.permission",x.API_CONSOLE_ERROR)}))}))}static get(e){return y(this,void 0,void 0,(function*(){const t=yield R.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return y(this,void 0,void 0,(function*(){const r=yield R.all(e,{name:t});return!!r&&r.length>0}))}}class T 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 S.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){A.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 R.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,P]),g("design:returntype",Promise)],T.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)],T.prototype,"session",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],T.prototype,"permission",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],T.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)],T.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)],T.prototype,"validation",null),l([c(0,e.Ctx()),c(1,e.Argument()),c(2,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),g("design:returntype",Promise)],T.prototype,"write",null),exports.ModelController=class extends T{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||{}),{userId: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 m=t.req.query.offset;if(r.isString(m)){const e=m?parseInt(m):0;y.offset=e>0?e:void 0}const A=[],f=this.columns(),I=e=>f.indexOf(e)>=0,_=null===(n=t.req.query.asc)||void 0===n?void 0:n.toString();_&&_.length&&A.push(..._.split(",").filter(I).map((e=>[e,"ASC"])));const C=null===(d=t.req.query.desc)||void 0===d?void 0:d.toString();C&&C.length&&A.push(...C.split(",").filter(I).map((e=>[e,"DESC"]))),A.length&&(y.order=A);const S=[],P=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(P&&P.length&&S.push({[e]:{[a.Op.like]:`%${P}%`}}),"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&&S.push({[e]:{[a.Op.like]:`%${o}%`}})}})),S.length&&(y.where=Object.assign(Object.assign({},y.where),{[a.Op.or]:[...S]}));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}),{userId:n})).catch(this.error);return d?(e.success("OK"),d):(e.notFound("Record not found"),0)}))}error(e){e.sql?A.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}),{userId: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(T)],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","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 T{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,userId: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 S.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 S.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 S.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 R.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,P]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),l([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,w()),c(2,E()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.Auth,exports.User,P]),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,P]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),l([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,E()),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(T)],exports.AuthController),exports.FilesController=class extends T{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,E()),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(T)],exports.FilesController),exports.ForgotController=class extends T{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,userId: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,P]),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,P]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=l([e.Controller("/forgot"),e.Extends(T)],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,E()),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,E()),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,E()),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:{groupId: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,r={userId:s.id};if(yield exports.GroupRoute.destroy(Object.assign({where:{groupId:t}},r)),o){let e=0;for(let s=0;s<o.length;s++)e=yield exports.Route.count({where:{id:o[s]}}),e&&(yield exports.GroupRoute.create({groupId:t,routeId:o[s]},Object.assign({},r)))}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,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,exports.User]),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","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 T{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(),userId:y.id,state:!0}).catch(this.error);if(!h)return y.destroy(),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.string().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,P]),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,P]),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,P]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=l([e.Controller("/register"),e.Extends(T)],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 T{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({userId:o.id,groupId: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({groupId:i.id,routeId: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({groupId:i.id,routeId: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({groupId:i.id,routeId: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(T)],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){return y(this,void 0,void 0,(function*(){if(t.length){const o=t[0].filename||"";if(o){const t=this.dir+"/"+r.avatar;n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=o;const s={userId:r.id};if(yield r.save(Object.assign({},s)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return y(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="";const o={userId:t.id};(yield t.save(Object.assign({},o)).catch(this.error))&&n.existsSync(r)&&n.rmSync(r),e.success("OK")}))}password(e,o,s,i){return y(this,void 0,void 0,(function*(){var n;const d=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);if(o+=null!==(n=null==d?void 0:d.salt)&&void 0!==n?n:"",!d||d.password!=t.sha256(o))return e.error("Record not changed");d.salt=r.uniqueID(),d.password=t.sha256(s+d.salt);const a={userId:i.id};if(yield d.save(Object.assign({},a)).catch(this.error))return e.success("OK");e.success("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){o.token="";const t={userId:r.id};return yield o.save(Object.assign({},t)).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();s.token=o.hash.encrypt(t);const i={userId:r.id};return yield s.save(Object.assign({},i)).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,E()),g("design:type",Function),g("design:paramtypes",[e.Context,Array,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),l([e.Get("/avatar/remove"),e.Middleware("auth"),c(0,e.Ctx()),c(1,E()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User]),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,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,exports.User]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),l([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,E()),c(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,exports.User,P]),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,P]),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,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User]),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,E()),c(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,exports.User,P]),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,E()),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,E()),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,E()),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:{userId: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){const t={userId:s.id};if(yield exports.UserGroup.destroy(Object.assign({where:{userId:i.id}},t)),o){let e=0;for(let r=0;r<o.length;r++)e=yield exports.Group.count({where:{id:o[r]}}),e&&(yield exports.UserGroup.create({userId:i.id,groupId:o[r]},Object.assign({},t)))}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,E()),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,E()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array,exports.User]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=l([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=P,exports.Config=O,exports.ControllerBase=T,exports.Env=x,exports.Logs=A,exports.Model=v,exports.Permission=R,exports.ReqAuth=w,exports.ReqUser=E,exports.Token=S,exports.audit=m,exports.conn=h,exports.crt=I,exports.key=_;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api
|
|
2
|
+
* @andrewcaires/api v4.0.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
@@ -7,22 +7,53 @@
|
|
|
7
7
|
import { Context, IStore, IUpload, Application as Application$1, IFile } from '@andrewcaires/express';
|
|
8
8
|
import { Hash } from '@andrewcaires/node';
|
|
9
9
|
import WebSocket from 'ws';
|
|
10
|
-
import { EventEmitter, TypeObject, ValidationBase,
|
|
11
|
-
import { Model
|
|
10
|
+
import { EventEmitter, TypeObject, ValidationBase, TypeObjectAny, TypeObjectString } from '@andrewcaires/utils.js';
|
|
11
|
+
import { Model as Model$1, Connection } from '@andrewcaires/sequelize';
|
|
12
|
+
import { Model as Model$2, CreateOptions, Attributes, FindOptions, UpdateOptions, ModelStatic, WhereOptions } from 'sequelize';
|
|
13
|
+
|
|
14
|
+
declare class Model extends Model$1 {
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
declare class Auth extends Model {
|
|
18
|
+
id: number;
|
|
19
|
+
secret: string;
|
|
20
|
+
logout: Date;
|
|
21
|
+
useragent: string;
|
|
22
|
+
createdAt: Date;
|
|
23
|
+
updatedAt: Date;
|
|
24
|
+
deletedAt: Date;
|
|
25
|
+
userId: number;
|
|
26
|
+
user: User;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
declare class Register extends Model {
|
|
30
|
+
id: number;
|
|
31
|
+
token: string;
|
|
32
|
+
state: boolean;
|
|
33
|
+
createdAt: Date;
|
|
34
|
+
updatedAt: Date;
|
|
35
|
+
deletedAt: Date;
|
|
36
|
+
userId: number;
|
|
37
|
+
user: User;
|
|
38
|
+
}
|
|
12
39
|
|
|
13
40
|
declare class Route extends Model {
|
|
14
41
|
id: number;
|
|
15
42
|
name: string;
|
|
16
43
|
description: string;
|
|
17
44
|
state: boolean;
|
|
45
|
+
createdAt: Date;
|
|
46
|
+
updatedAt: Date;
|
|
47
|
+
deletedAt: Date;
|
|
18
48
|
groups_routes: Array<GroupRoute>;
|
|
19
49
|
}
|
|
20
50
|
|
|
21
51
|
declare class GroupRoute extends Model {
|
|
22
|
-
|
|
52
|
+
createdAt: Date;
|
|
23
53
|
groupId: number;
|
|
24
|
-
|
|
54
|
+
group: Group;
|
|
25
55
|
routeId: number;
|
|
56
|
+
route: Route;
|
|
26
57
|
}
|
|
27
58
|
|
|
28
59
|
declare class Group extends Model {
|
|
@@ -30,15 +61,19 @@ declare class Group extends Model {
|
|
|
30
61
|
name: string;
|
|
31
62
|
description: string;
|
|
32
63
|
state: boolean;
|
|
64
|
+
createdAt: Date;
|
|
65
|
+
updatedAt: Date;
|
|
66
|
+
deletedAt: Date;
|
|
33
67
|
groups_routes: Array<GroupRoute>;
|
|
34
68
|
users_groups: Array<UserGroup>;
|
|
35
69
|
}
|
|
36
70
|
|
|
37
71
|
declare class UserGroup extends Model {
|
|
38
|
-
|
|
39
|
-
userId: number;
|
|
40
|
-
group: Group;
|
|
72
|
+
createdAt: Date;
|
|
41
73
|
groupId: number;
|
|
74
|
+
group: Group;
|
|
75
|
+
userId: number;
|
|
76
|
+
user: User;
|
|
42
77
|
}
|
|
43
78
|
|
|
44
79
|
declare class User extends Model {
|
|
@@ -53,21 +88,32 @@ declare class User extends Model {
|
|
|
53
88
|
date: string;
|
|
54
89
|
description: string;
|
|
55
90
|
state: boolean;
|
|
91
|
+
createdAt: Date;
|
|
92
|
+
updatedAt: Date;
|
|
93
|
+
deletedAt: Date;
|
|
94
|
+
audits: Array<Audit>;
|
|
95
|
+
auths: Array<Auth>;
|
|
96
|
+
registers: Array<Register>;
|
|
56
97
|
users_groups: Array<UserGroup>;
|
|
57
98
|
}
|
|
58
99
|
|
|
59
|
-
declare class
|
|
100
|
+
declare class Audit extends Model {
|
|
60
101
|
id: number;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
102
|
+
type: string;
|
|
103
|
+
model: string;
|
|
104
|
+
record: string;
|
|
105
|
+
data: string;
|
|
106
|
+
createdAt: Date;
|
|
107
|
+
deletedAt: Date;
|
|
65
108
|
userId: number;
|
|
109
|
+
user: User;
|
|
66
110
|
}
|
|
67
111
|
|
|
68
112
|
declare class Configs extends Model {
|
|
69
113
|
key: string;
|
|
70
114
|
value: string;
|
|
115
|
+
createdAt: Date;
|
|
116
|
+
updatedAt: Date;
|
|
71
117
|
}
|
|
72
118
|
|
|
73
119
|
declare class Forgot extends Model {
|
|
@@ -75,28 +121,26 @@ declare class Forgot extends Model {
|
|
|
75
121
|
token: string;
|
|
76
122
|
timestamp: number;
|
|
77
123
|
state: boolean;
|
|
78
|
-
|
|
124
|
+
createdAt: Date;
|
|
125
|
+
updatedAt: Date;
|
|
126
|
+
deletedAt: Date;
|
|
79
127
|
userId: number;
|
|
128
|
+
user: User;
|
|
80
129
|
}
|
|
81
130
|
|
|
82
131
|
declare class Log extends Model {
|
|
83
132
|
type: string;
|
|
84
133
|
source: string;
|
|
85
134
|
message: string;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
declare class Register extends Model {
|
|
89
|
-
id: number;
|
|
90
|
-
token: string;
|
|
91
|
-
state: boolean;
|
|
92
|
-
user: User;
|
|
93
|
-
userId: number;
|
|
135
|
+
createdAt: Date;
|
|
94
136
|
}
|
|
95
137
|
|
|
96
138
|
declare class Session extends Model {
|
|
97
139
|
session: string;
|
|
98
140
|
json: string;
|
|
99
141
|
expired: number;
|
|
142
|
+
createdAt: Date;
|
|
143
|
+
updatedAt: Date;
|
|
100
144
|
}
|
|
101
145
|
|
|
102
146
|
declare abstract class ControllerBase extends EventEmitter {
|
|
@@ -121,69 +165,58 @@ declare class Application extends Application$1 {
|
|
|
121
165
|
websocket(): WebSocket.Server | undefined;
|
|
122
166
|
}
|
|
123
167
|
|
|
168
|
+
declare const audit: {
|
|
169
|
+
afterCreate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
170
|
+
afterUpdate: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
171
|
+
afterDestroy: (record: Model, options: TypeObjectAny) => Promise<void>;
|
|
172
|
+
};
|
|
173
|
+
|
|
124
174
|
declare class Config {
|
|
125
175
|
static all(): Promise<TypeObjectString>;
|
|
126
|
-
static del(key: string): Promise<boolean>;
|
|
176
|
+
static del(key: string, user?: User): Promise<boolean>;
|
|
127
177
|
private static error;
|
|
128
178
|
static get(key: string, value?: string): Promise<string>;
|
|
129
|
-
static set(key: string, value: string): Promise<void>;
|
|
179
|
+
static set(key: string, value: string, user?: User): Promise<void>;
|
|
130
180
|
}
|
|
131
181
|
|
|
132
|
-
declare
|
|
133
|
-
protected login(ctx: Context, useragent: string, username: string, password: string, app: Application): Promise<void>;
|
|
134
|
-
protected logout(ctx: Context, auth: Auth, user: User, app: Application): Promise<void>;
|
|
135
|
-
protected renew(ctx: Context, useragent: string, old: string, app: Application): Promise<void>;
|
|
136
|
-
protected user(ctx: Context, user: User): Promise<void>;
|
|
137
|
-
}
|
|
182
|
+
declare const conn: Connection;
|
|
138
183
|
|
|
139
|
-
|
|
140
|
-
directory(): string;
|
|
141
|
-
files(ctx: Context): Promise<TypeObjectAny | void>;
|
|
142
|
-
access(ctx: Context, name: string, user: User): Promise<void>;
|
|
143
|
-
private info;
|
|
144
|
-
name(): string;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
declare class ForgotController extends ControllerBase {
|
|
148
|
-
check(ctx: Context, token: string): Promise<void>;
|
|
149
|
-
forgot(ctx: Context, username: string, app: Application): Promise<void>;
|
|
150
|
-
reset(ctx: Context, token: string, password: string, app: Application): Promise<void>;
|
|
151
|
-
private find;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
interface ArgumentsModelAdd<M extends Model<M>> {
|
|
184
|
+
interface ArgumentsModelAdd<M extends Model$2<M>> {
|
|
155
185
|
ctx: Context;
|
|
156
186
|
options?: CreateOptions<Attributes<M>>;
|
|
157
187
|
body?: TypeObjectAny;
|
|
188
|
+
user?: User;
|
|
158
189
|
}
|
|
159
190
|
|
|
160
191
|
type CallbackModelAll<M> = (records: Array<M>) => Array<any> | Promise<Array<any>>;
|
|
161
192
|
|
|
162
|
-
interface ArgumentsModelAll<M extends Model<M>> {
|
|
193
|
+
interface ArgumentsModelAll<M extends Model$2<M>> {
|
|
163
194
|
ctx: Context;
|
|
164
195
|
options?: FindOptions<Attributes<M>>;
|
|
165
196
|
callback?: CallbackModelAll<M>;
|
|
166
197
|
scope?: string;
|
|
167
198
|
}
|
|
168
199
|
|
|
169
|
-
interface ArgumentsModelDel<M extends Model<M>> {
|
|
200
|
+
interface ArgumentsModelDel<M extends Model$2<M>> {
|
|
170
201
|
ctx: Context;
|
|
171
202
|
options?: FindOptions<Attributes<M>>;
|
|
203
|
+
user?: User;
|
|
172
204
|
}
|
|
173
205
|
|
|
174
206
|
type CallbackModelGet<M> = (records: M) => any | Promise<any>;
|
|
175
207
|
|
|
176
|
-
interface ArgumentsModelGet<M extends Model<M>> {
|
|
208
|
+
interface ArgumentsModelGet<M extends Model$2<M>> {
|
|
177
209
|
ctx: Context;
|
|
178
210
|
options?: FindOptions<Attributes<M>>;
|
|
179
211
|
callback?: CallbackModelGet<M>;
|
|
180
212
|
scope?: string;
|
|
181
213
|
}
|
|
182
214
|
|
|
183
|
-
interface ArgumentsModelSet<M extends Model<M>> {
|
|
215
|
+
interface ArgumentsModelSet<M extends Model$2<M>> {
|
|
184
216
|
ctx: Context;
|
|
185
217
|
options?: UpdateOptions<Attributes<M>>;
|
|
186
218
|
body?: TypeObjectAny;
|
|
219
|
+
user?: User;
|
|
187
220
|
}
|
|
188
221
|
|
|
189
222
|
interface IDatabaseOptions {
|
|
@@ -203,38 +236,67 @@ interface ITokenParameters {
|
|
|
203
236
|
user?: User;
|
|
204
237
|
}
|
|
205
238
|
|
|
206
|
-
interface ResultModelAll<M extends Model<M>> {
|
|
239
|
+
interface ResultModelAll<M extends Model$2<M>> {
|
|
207
240
|
count: number;
|
|
208
241
|
limit: number;
|
|
209
242
|
offset: number;
|
|
210
243
|
records: Array<M>;
|
|
211
244
|
}
|
|
212
245
|
|
|
213
|
-
declare abstract class ModelController<M extends Model<M>> extends ControllerBase {
|
|
246
|
+
declare abstract class ModelController<M extends Model$2<M>> extends ControllerBase {
|
|
214
247
|
private _columns;
|
|
215
|
-
protected _add({ ctx, options, body }: ArgumentsModelAdd<M>): Promise<M | void>;
|
|
248
|
+
protected _add({ ctx, options, body, user }: ArgumentsModelAdd<M>): Promise<M | void>;
|
|
216
249
|
protected _all({ ctx, options, callback, scope }: ArgumentsModelAll<M>): Promise<ResultModelAll<M>>;
|
|
217
|
-
protected columns(): string
|
|
218
|
-
protected _del({ ctx, options }: ArgumentsModelDel<M>): Promise<number>;
|
|
250
|
+
protected columns(): Array<string>;
|
|
251
|
+
protected _del({ ctx, options, user }: ArgumentsModelDel<M>): Promise<number>;
|
|
219
252
|
error(error: any): void;
|
|
220
253
|
protected _get({ ctx, options, callback, scope }: ArgumentsModelGet<M>): Promise<M | void>;
|
|
221
254
|
key(): string;
|
|
222
255
|
abstract model(): ModelStatic<M>;
|
|
223
256
|
name(): string;
|
|
224
257
|
scope(name?: string): ModelStatic<M>;
|
|
225
|
-
protected _set({ ctx, options, body }: ArgumentsModelSet<M>): Promise<boolean>;
|
|
258
|
+
protected _set({ ctx, options, body, user }: ArgumentsModelSet<M>): Promise<boolean>;
|
|
226
259
|
}
|
|
227
260
|
|
|
228
|
-
declare
|
|
229
|
-
|
|
230
|
-
all(ctx: Context): Promise<void>;
|
|
261
|
+
declare class AuditsController extends ModelController<Audit> {
|
|
262
|
+
model(): typeof Audit;
|
|
263
|
+
protected all(ctx: Context, type: string, table: string): Promise<void>;
|
|
264
|
+
protected get(ctx: Context): Promise<void>;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
declare class AuthController extends ControllerBase {
|
|
268
|
+
protected login(ctx: Context, useragent: string, username: string, password: string, app: Application): Promise<void>;
|
|
269
|
+
protected logout(ctx: Context, auth: Auth, user: User, app: Application): Promise<void>;
|
|
270
|
+
protected renew(ctx: Context, useragent: string, old: string, app: Application): Promise<void>;
|
|
271
|
+
protected user(ctx: Context, user: User): Promise<void>;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
declare class FilesController extends ControllerBase {
|
|
275
|
+
directory(): string;
|
|
276
|
+
protected files(ctx: Context): Promise<TypeObjectAny | void>;
|
|
277
|
+
protected access(ctx: Context, name: string, user: User): Promise<void>;
|
|
278
|
+
private info;
|
|
279
|
+
name(): string;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
declare class ForgotController extends ControllerBase {
|
|
283
|
+
protected check(ctx: Context, token: string): Promise<void>;
|
|
284
|
+
protected forgot(ctx: Context, username: string, app: Application): Promise<void>;
|
|
285
|
+
protected reset(ctx: Context, token: string, password: string, app: Application): Promise<void>;
|
|
286
|
+
private find;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
declare abstract class CrudController<M extends Model$2<M>> extends ModelController<M> {
|
|
290
|
+
private _crud;
|
|
291
|
+
protected add(ctx: Context, user: User): Promise<void>;
|
|
292
|
+
protected all(ctx: Context): Promise<void>;
|
|
231
293
|
create(): TypeObject<ValidationBase>;
|
|
232
|
-
del(ctx: Context): Promise<void>;
|
|
233
|
-
get(ctx: Context): Promise<void>;
|
|
234
|
-
set(ctx: Context): Promise<void>;
|
|
294
|
+
protected del(ctx: Context, user: User): Promise<void>;
|
|
295
|
+
protected get(ctx: Context): Promise<void>;
|
|
296
|
+
protected set(ctx: Context, user: User): Promise<void>;
|
|
235
297
|
update(): TypeObject<ValidationBase>;
|
|
236
|
-
validationAdd(ctx: Context): Promise<void>;
|
|
237
|
-
validationSet(ctx: Context): Promise<void>;
|
|
298
|
+
protected validationAdd(ctx: Context): Promise<void>;
|
|
299
|
+
protected validationSet(ctx: Context): Promise<void>;
|
|
238
300
|
}
|
|
239
301
|
|
|
240
302
|
declare class GroupsController extends CrudController<Group> {
|
|
@@ -245,8 +307,8 @@ declare class GroupsController extends CrudController<Group> {
|
|
|
245
307
|
|
|
246
308
|
declare class GroupsRoutesController extends ModelController<GroupRoute> {
|
|
247
309
|
model(): typeof GroupRoute;
|
|
248
|
-
all(ctx: Context, groupId: string): Promise<void>;
|
|
249
|
-
set(ctx: Context, id: string, routes: Array<number
|
|
310
|
+
protected all(ctx: Context, groupId: string): Promise<void>;
|
|
311
|
+
protected set(ctx: Context, id: string, routes: Array<number>, user: User): Promise<void>;
|
|
250
312
|
}
|
|
251
313
|
|
|
252
314
|
declare class LogsController extends ModelController<Log> {
|
|
@@ -256,8 +318,8 @@ declare class LogsController extends ModelController<Log> {
|
|
|
256
318
|
|
|
257
319
|
declare class RegisterController extends ControllerBase {
|
|
258
320
|
protected register(ctx: Context, body: TypeObjectAny, app: Application): Promise<void>;
|
|
259
|
-
confirm(ctx: Context, token: string, app: Application): Promise<void>;
|
|
260
|
-
send(ctx: Context, username: string, app: Application): Promise<void>;
|
|
321
|
+
protected confirm(ctx: Context, token: string, app: Application): Promise<void>;
|
|
322
|
+
protected send(ctx: Context, username: string, app: Application): Promise<void>;
|
|
261
323
|
private getId;
|
|
262
324
|
}
|
|
263
325
|
|
|
@@ -280,31 +342,22 @@ declare class UsersController extends ModelController<User> {
|
|
|
280
342
|
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User): Promise<void>;
|
|
281
343
|
protected token(ctx: Context, user: User, app: Application): Promise<void>;
|
|
282
344
|
protected token_get(ctx: Context, id: string, app: Application): Promise<void>;
|
|
283
|
-
protected token_remove(ctx: Context, id: string): Promise<void>;
|
|
284
|
-
protected token_renew(ctx: Context, id: string, app: Application): Promise<void>;
|
|
345
|
+
protected token_remove(ctx: Context, id: string, user: User): Promise<void>;
|
|
346
|
+
protected token_renew(ctx: Context, id: string, user: User, app: Application): Promise<void>;
|
|
285
347
|
private token_new;
|
|
286
|
-
protected add(ctx: Context, password: string): Promise<void>;
|
|
348
|
+
protected add(ctx: Context, password: string, user: User): Promise<void>;
|
|
287
349
|
protected all(ctx: Context): Promise<void>;
|
|
288
|
-
protected del(ctx: Context,
|
|
350
|
+
protected del(ctx: Context, id: string, user: User): Promise<void>;
|
|
289
351
|
protected get(ctx: Context): Promise<void>;
|
|
290
|
-
protected set(ctx: Context, password: string): Promise<void>;
|
|
352
|
+
protected set(ctx: Context, password: string, user: User): Promise<void>;
|
|
291
353
|
}
|
|
292
354
|
|
|
293
355
|
declare class UsersGroupsController extends ModelController<UserGroup> {
|
|
294
356
|
model(): typeof UserGroup;
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
declare class Database {
|
|
300
|
-
static connect(options: IDatabaseOptions): Sequelize;
|
|
301
|
-
static connect_mariadb(options: IDatabaseOptions): Sequelize;
|
|
302
|
-
static connect_memory(): Sequelize;
|
|
303
|
-
static connect_mysql(options: IDatabaseOptions): Sequelize;
|
|
304
|
-
static connect_postgres(options: IDatabaseOptions): Sequelize;
|
|
305
|
-
static connect_sqlite(options: IDatabaseOptions): Sequelize;
|
|
357
|
+
protected groups(ctx: Context, user: User): Promise<void>;
|
|
358
|
+
protected all(ctx: Context, userId: string): Promise<void>;
|
|
359
|
+
protected set(ctx: Context, id: string, groups: Array<number>, user: User): Promise<void>;
|
|
306
360
|
}
|
|
307
|
-
declare const sequelize: Sequelize;
|
|
308
361
|
|
|
309
362
|
declare class Env {
|
|
310
363
|
static readonly API_CONSOLE_ERROR: boolean;
|
|
@@ -353,8 +406,8 @@ declare class Env {
|
|
|
353
406
|
protected static getString(key: string, value: string): string;
|
|
354
407
|
}
|
|
355
408
|
|
|
356
|
-
declare const ReqAuth: (key?: string
|
|
357
|
-
declare const ReqUser: (key?: string
|
|
409
|
+
declare const ReqAuth: (key?: string) => ParameterDecorator;
|
|
410
|
+
declare const ReqUser: (key?: string) => ParameterDecorator;
|
|
358
411
|
declare global {
|
|
359
412
|
namespace Express {
|
|
360
413
|
interface Request {
|
|
@@ -398,4 +451,4 @@ declare class Token {
|
|
|
398
451
|
private static verify;
|
|
399
452
|
}
|
|
400
453
|
|
|
401
|
-
export { Application, type ArgumentsModelAdd, type ArgumentsModelAll, type ArgumentsModelDel, type ArgumentsModelGet, type ArgumentsModelSet, Auth, AuthController, type CallbackModelAll, type CallbackModelGet, Config, Configs, ControllerBase, CrudController,
|
|
454
|
+
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, GroupRoute, GroupsController, GroupsRoutesController, type IDatabaseOptions, type ITokenParameters, Log, Logs, LogsController, Model, ModelController, Permission, Register, RegisterController, ReqAuth, ReqUser, type ResultModelAll, Route, RoutesController, Session, SetupController, Token, User, UserGroup, UsersController, UsersGroupsController, audit, conn, crt, key };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api
|
|
2
|
+
* @andrewcaires/api v4.0.0
|
|
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 s,Argument as o,Upload as d,Context as a,Post as u,Middleware as c,Body as l,Get as p,Controller as g,Extends as h,Status as m,Delete as y,Put as _,Params as I,Query as v,Files as f}from"@andrewcaires/express";import{LogColor as P,Log as A,Hash as E,sha256 as O}from"@andrewcaires/node";import{toBool as S,parseMs as T,noop as w,loop as R,uuidv4 as b,sleep as D,EventEmitter as k,Validation as N,isDef as x,uniqueID as F,isString as q,isArray as L,isNull as B,forEachSeries as j}from"@andrewcaires/utils.js";import K from"ws";import{Sequelize as M,DataTypes as C,Model as H,Op as U}from"sequelize";import{config as G}from"dotenv";import{existsSync as z,readFileSync as Y,statSync as X,readdirSync as W,mkdirSync as Z,lstatSync as J,rmSync as $}from"fs";import{Store as V}from"express-session";import{verify as Q,sign as ee}from"jsonwebtoken";import{join as te}from"path";function re(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 ne(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function se(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,G();class oe{static getBool(e,t){return S(oe.getString(e,t.toString()))}static getInt(e,t){return parseInt(oe.getString(e,t.toString()))}static getMs(e,t){return T(oe.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}oe.API_CONSOLE_ERROR=oe.getBool("API_CONSOLE_ERROR",!1),oe.API_DEFAULT_PATH=oe.getString("API_DEFAULT_PATH","/api"),oe.API_DB_DATABASE=oe.getString("API_DB_DATABASE",""),oe.API_DB_HOST=oe.getString("API_DB_HOST","127.0.0.1"),oe.API_DB_PASSWORD=oe.getString("API_DB_PASSWORD",""),oe.API_DB_PORT=oe.getInt("API_DB_PORT",3306),oe.API_DB_TYPE=oe.getString("API_DB_TYPE",""),oe.API_DB_USERNAME=oe.getString("API_DB_USERNAME","root"),oe.API_DB_LOG=oe.getBool("API_DB_LOG",!1),oe.API_DB_PREFIX=oe.getString("API_DB_PREFIX",""),oe.API_DB_TIMEZONE=oe.getString("API_DB_TIMEZONE","+00:00"),oe.API_HTTP_CRT=oe.getString("API_HTTP_CRT",""),oe.API_HTTP_KEY=oe.getString("API_HTTP_KEY",""),oe.API_HTTP_PORT=oe.getInt("API_HTTP_PORT",3e3),oe.API_HTTP_PUBLIC=oe.getString("API_HTTP_PUBLIC",""),oe.API_HTTP_CROSS=oe.getBool("API_HTTP_CROSS",!1),oe.API_HTTP_HYBRID=oe.getBool("API_HTTP_HYBRID",!1),oe.API_HTTP_REDIRECT=oe.getString("API_HTTP_REDIRECT",""),oe.API_KEY_HASH=oe.getString("API_KEY_HASH",""),oe.API_KEY_HEADER=oe.getString("API_KEY_HEADER","api_key"),oe.API_MODEL_LIMIT=oe.getInt("API_MODEL_LIMIT",10),oe.API_MODEL_LIMIT_MAX=oe.getInt("API_MODEL_LIMIT_MAX",500),oe.API_NOTFOUND_REDIRECT=oe.getString("API_NOTFOUND_REDIRECT",""),oe.API_SLEEP_AUTH=oe.getMs("API_SLEEP_AUTH","2s"),oe.API_SLEEP_FORGOT=oe.getMs("API_SLEEP_FORGOT","5s"),oe.API_SLEEP_REGISTRY=oe.getMs("API_SLEEP_REGISTRY","5s"),oe.API_SESSION_NAME=oe.getString("API_SESSION_NAME","session.id"),oe.API_SESSION_LIFETIME=oe.getMs("API_SESSION_LIFETIME","1d"),oe.API_SESSION_SECRET=oe.getString("API_SESSION_SECRET","yoursecret"),oe.API_TOKEN_CRT=oe.getString("API_TOKEN_CRT",""),oe.API_TOKEN_KEY=oe.getString("API_TOKEN_KEY",""),oe.API_TOKEN_FORGOT=oe.getMs("API_TOKEN_LIFETIME","1d"),oe.API_TOKEN_HEADER=oe.getString("API_TOKEN_HEADER","authorization"),oe.API_TOKEN_LIFETIME=oe.getMs("API_TOKEN_LIFETIME","1d"),oe.API_TOKEN_RENEW=oe.getMs("API_TOKEN_RENEW","1d"),oe.API_UPLOAD_COUNT=oe.getInt("API_UPLOAD_COUNT",1),oe.API_UPLOAD_FIELD=oe.getString("API_UPLOAD_FIELD","upload"),oe.API_UPLOAD_SIZE=oe.getInt("API_UPLOAD_SIZE",2),oe.API_UPLOAD_TEMP=oe.getString("API_UPLOAD_TEMP","./temp"),oe.API_WEBSOCKET_START=oe.getBool("API_WEBSOCKET_START",!1);class de{static connect(e){const t="connect_"+oe.API_DB_TYPE.toLowerCase();if(t in de)return de[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new M(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mariadb",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_memory(){return new M("sqlite::memory:",{logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_mysql(e){return new M(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mysql",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_postgres(e){return new M(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"postgres",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_sqlite(e){return new M({dialect:"sqlite",storage:e.database,logging:oe.API_DB_LOG,define:{timestamps:!1}})}}const ae=de.connect({database:oe.API_DB_DATABASE,username:oe.API_DB_USERNAME,password:oe.API_DB_PASSWORD,hostname:oe.API_DB_HOST,hostport:oe.API_DB_PORT});class ue extends H{}ue.init({secret:C.STRING,logout:C.DATE,useragent:C.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends H{}ce.init({token:C.STRING,timestamp:C.BIGINT,state:C.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends H{}le.init({name:C.STRING,description:C.TEXT,state:C.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class pe extends H{}pe.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),pe.removeAttribute("id");class ge extends H{}ge.init({token:C.STRING,state:C.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends H{}he.init({name:C.STRING,description:C.TEXT,state:C.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class me extends H{}me.init({name:C.STRING,email:C.STRING,username:C.STRING,password:C.STRING,salt:C.STRING,token:C.STRING,avatar:C.STRING,date:C.DATEONLY,description:C.TEXT,state:C.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password","salt","token"]}},scopes:{password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}});class ye extends H{}ye.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),ye.removeAttribute("id");class _e extends H{}_e.init({key:C.STRING,value:C.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),_e.removeAttribute("id");class Ie extends H{}Ie.init({type:C.STRING,source:C.STRING,message:C.TEXT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class ve extends H{}ve.init({session:C.STRING,json:C.TEXT,expired:C.BIGINT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),ve.removeAttribute("id"),me.hasMany(ue),ue.belongsTo(me),me.hasMany(ce),ce.belongsTo(me),me.hasMany(ge),ge.belongsTo(me),le.hasMany(pe),pe.belongsTo(le),he.hasMany(pe),pe.belongsTo(he),me.hasMany(ye),ye.belongsTo(me),le.hasMany(ye),ye.belongsTo(le);class fe{static write(e,t,r){return se(this,void 0,void 0,(function*(){yield fe.writeRaw(P.White,"",e,t,r)}))}static error(e,t,r){return se(this,void 0,void 0,(function*(){yield fe.writeRaw(P.Red,"error",e,t,r)}))}static info(e,t,r){return se(this,void 0,void 0,(function*(){yield fe.writeRaw(P.Cyan,"info",e,t,r)}))}static success(e,t,r){return se(this,void 0,void 0,(function*(){yield fe.writeRaw(P.Green,"success",e,t,r)}))}static warning(e,t,r){return se(this,void 0,void 0,(function*(){yield fe.writeRaw(P.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return se(this,void 0,void 0,(function*(){n&&A.console(e,t,r),ae&&(yield Ie.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Pe=e=>z(e)?Y(e):void 0,Ae={http:Pe(oe.API_HTTP_CRT),token:Pe(oe.API_TOKEN_CRT)},Ee={http:Pe(oe.API_HTTP_KEY),token:Pe(oe.API_TOKEN_KEY)};class Oe extends V{constructor(){super(),this.all=e=>se(this,void 0,void 0,(function*(){e=e||w;const t=yield ve.findAll({attributes:["session"],where:{expired:{[U.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>se(this,void 0,void 0,(function*(){yield ve.destroy().catch(w),e&&e()})),this.destroy=(e,t)=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{session:e}}).catch(w),t&&t()})),this.expired=()=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{expired:{[U.lt]:Date.now()}}}).catch(w)})),this.get=(e,t)=>se(this,void 0,void 0,(function*(){t=t||w;const r=yield ve.findOne({where:{session:e,expired:{[U.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=>se(this,void 0,void 0,(function*(){e&&e(null,(yield ve.count().catch(w))||0)})),this.set=(e,t,r)=>se(this,void 0,void 0,(function*(){r=r||w;const i=Date.now()+oe.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield ve.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=R(this.expired,3e4),this.loop.start()}}class Se{static create(e){return se(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{id:t}=e,r=b(),i=yield ue.create({secret:r,userId:t}).catch(Se.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:ee({id:t,secret:r},Ee.token,Se.options())}}))}static destroy(e){return se(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){fe.error(e.message,"api.token",oe.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:oe.API_TOKEN_LIFETIME+"ms"}}static renew(e){return se(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{error:t,decode:r}=Se.verify(e,oe.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield me.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const i=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(i&&!i.logout){i.secret=b(),yield i.save().catch(Se.error);return{auth:i,token:ee({id:e,secret:i.secret},Ee.token,Se.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return se(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield me.findOne({where:{token:t,state:!0}}).catch(Se.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield ue.findOrCreate({where:{secret:t,userId:i.id},defaults:{secret:t,userId:i.id}}).catch(Se.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:n}=Se.verify(t);if(i)return{error:i};if(n){const{id:e,secret:t}=n;if(e&&t){const r=yield me.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const e=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ae.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:Q(e,Ae.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class Te extends e{constructor(e){super(e,{cert:Ae.http,cross:oe.API_HTTP_CROSS,hybrid:oe.API_HTTP_HYBRID,key:Ee.http,notfound:oe.API_NOTFOUND_REDIRECT,path:oe.API_DEFAULT_PATH,port:oe.API_HTTP_PORT,public:oe.API_HTTP_PUBLIC,redirect:oe.API_HTTP_REDIRECT,session:{store:new Oe,name:oe.API_SESSION_NAME,secret:oe.API_SESSION_SECRET,cookie:{maxAge:oe.API_SESSION_LIFETIME},genid:b}}),this.hash=new E(oe.API_KEY_HASH)}error(e,t){fe.error(e.message,t,oe.API_CONSOLE_ERROR)}log(e,t){fe.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return se(this,void 0,void 0,(function*(){yield ae.sync(),yield e.listen.call(this),oe.API_WEBSOCKET_START&&this.server&&(this._webSocket=new K.Server({server:this.server,verifyClient:(e,t)=>t(oe.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>se(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=>se(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 Se.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 D(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class we{static all(){return se(this,void 0,void 0,(function*(){const e=yield _e.findAll().catch(we.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return se(this,void 0,void 0,(function*(){return((yield _e.destroy({where:{key:e}}).catch(we.error))||0)>0}))}static error(e){fe.error(e.message,"api.config",oe.API_CONSOLE_ERROR)}static get(e){return se(this,arguments,void 0,(function*(e,t=""){const[r]=(yield _e.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(we.error))||[];return r?r.value:t}))}static set(e,t){return se(this,void 0,void 0,(function*(){const[r]=(yield _e.findOrCreate({where:{key:e}}).catch(we.error))||[];r&&(r.value=t,yield r.save().catch(we.error))}))}}const Re=t((({ctx:e})=>e.req.auth)),be=t((({ctx:e})=>e.req.user));class De{static all(e,t){return se(this,void 0,void 0,(function*(){return yield he.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:pe,required:!0,include:[{model:le,required:!0,where:{state:!0},include:[{model:ye,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{fe.error(e.message,"api.permission",oe.API_CONSOLE_ERROR)}))}))}static get(e){return se(this,void 0,void 0,(function*(){const t=yield De.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return se(this,void 0,void 0,(function*(){const r=yield De.all(e,{name:t});return!!r&&r.length>0}))}}class ke extends k{auth(e,t,r,i,n){return se(this,void 0,void 0,(function*(){const{auth:s,error:o,user:d}=yield Se.user(t,r,n);return o?e.error(o):s&&d?s.useragent&&s.useragent!=i?e.error("Invalid token"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,r){return se(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(w):(r.useragent=t,r.save(w))),e.next()}))}error(e){fe.error(e.message,"api.controller",oe.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return se(this,void 0,void 0,(function*(){return r?(yield De.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){t.path||(t.path=oe.API_UPLOAD_TEMP),t.size||(t.size=oe.API_UPLOAD_SIZE),t.field||(t.field=oe.API_UPLOAD_FIELD),d.middleware(e,t)}validation(e,t){return se(this,void 0,void 0,(function*(){const{error:r,value:i}=yield N.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=i,e.next()}))}write(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}re([ie(0,r()),ie(1,i(oe.API_KEY_HEADER)),ie(2,i(oe.API_TOKEN_HEADER)),ie(3,i("user-agent")),ie(4,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,String,Te]),ne("design:returntype",Promise)],ke.prototype,"auth",null),re([ie(0,r()),ie(1,i("user-agent")),ie(2,s()),ne("design:type",Function),ne("design:paramtypes",[a,String,Object]),ne("design:returntype",Promise)],ke.prototype,"session",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,me]),ne("design:returntype",Promise)],ke.prototype,"permission",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,me]),ne("design:returntype",Promise)],ke.prototype,"read",null),re([ie(0,r()),ie(1,o()),ne("design:type",Function),ne("design:paramtypes",[a,Object]),ne("design:returntype",void 0)],ke.prototype,"upload",null),re([ie(0,r()),ie(1,o()),ne("design:type",Function),ne("design:paramtypes",[a,Object]),ne("design:returntype",Promise)],ke.prototype,"validation",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,me]),ne("design:returntype",Promise)],ke.prototype,"write",null);let Ne=class extends ke{login(e,t,r,i,n){return se(this,void 0,void 0,(function*(){var s;yield D(oe.API_SLEEP_AUTH);const o=yield me.scope("password").findOne({where:{[U.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!=O(i))return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield ge.findOne({where:{state:!0,userId: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:c}=yield Se.create(o);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: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 se(this,void 0,void 0,(function*(){if(yield Se.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 se(this,void 0,void 0,(function*(){const{auth:n,error:s,token:o}=yield Se.renew(r);return s?e.error(s):n?(n.useragent=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 se(this,void 0,void 0,(function*(){const r=yield De.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};re([u("/login"),c("validation",{username:N.string().min(3).required(),password:N.string().min(5).required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,l("username")),ie(3,l("password")),ie(4,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,String,Te]),ne("design:returntype",Promise)],Ne.prototype,"login",null),re([p("/logout"),c("auth"),ie(0,r()),ie(1,Re()),ie(2,be()),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,ue,me,Te]),ne("design:returntype",Promise)],Ne.prototype,"logout",null),re([u("/renew"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,l("token")),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,Te]),ne("design:returntype",Promise)],Ne.prototype,"renew",null),re([p(),c("auth"),ie(0,r()),ie(1,be()),ne("design:type",Function),ne("design:paramtypes",[a,me]),ne("design:returntype",Promise)],Ne.prototype,"user",null),Ne=re([g("/auth"),h(ke)],Ne);let xe=class extends ke{directory(){return oe.API_HTTP_PUBLIC||"./"}files(e){return se(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=te(this.directory(),t);if(!z(r)||!X(r).isDirectory())return e.notFound("Path not Found");let i=[];return i=W(r),i=i.map((e=>this.info(te(r,e)))),i=i.filter(x),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!z(e))return null;const t=X(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"}};re([p("/path/?*"),c("auth"),c("access","list"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],xe.prototype,"files",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,me]),ne("design:returntype",Promise)],xe.prototype,"access",null),xe=re([g("/files"),h(ke)],xe);let Fe=class extends ke{check(e,t){return se(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("User not found");r.token=F(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return se(this,void 0,void 0,(function*(){yield D(oe.API_SLEEP_FORGOT);const i=t,n=yield me.findOne({where:{[U.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=F(),o=Date.now()+6e4*oe.API_TOKEN_FORGOT,d=yield ce.create({token:s,timestamp:o,state:!0,userId: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 se(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=O(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 se(this,void 0,void 0,(function*(){return yield ce.findOne({where:{token:e,state:!0},include:[{model:me,required:!0}]}).catch(this.error)}))}};re([p("/check"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,l("token")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Fe.prototype,"check",null),re([u(),c("validation",{username:N.string().min(4).required()}),ie(0,r()),ie(1,l("username")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"forgot",null),re([u("/reset"),c("validation",{token:N.string().required(),password:N.string().min(5).required()}),ie(0,r()),ie(1,l("token")),ie(2,l("password")),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"reset",null),Fe=re([g("/forgot"),h(ke)],Fe);let qe=class extends ke{constructor(){super(...arguments),this._columns=[]}_add(e){return se(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||{}),t||{}).catch(this.error);if(i){const t=this.key();return e.prepare(m.OK,{[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all(e){return se(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){var n,s,o,d,a,u;const c=this.scope(i),l=Object.assign({},t||{});l.where=Object.assign({},l.where||{});const p=e.req.query.limit,g=q(p)?parseInt(p):oe.API_MODEL_LIMIT;l.limit=g>=0?Math.min(g,oe.API_MODEL_LIMIT_MAX):void 0;const h=e.req.query.offset;if(q(h)){const e=h?parseInt(h):0;l.offset=e>0?e:void 0}const y=[],_=this.columns(),I=e=>_.indexOf(e)>=0,v=null===(n=e.req.query.asc)||void 0===n?void 0:n.toString();v&&v.length&&y.push(...v.split(",").filter(I).map((e=>[e,"ASC"])));const f=null===(s=e.req.query.desc)||void 0===s?void 0:s.toString();f&&f.length&&y.push(...f.split(",").filter(I).map((e=>[e,"DESC"]))),y.length&&(l.order=y);const P=[],A=null===(o=e.req.query.search)||void 0===o?void 0:o.toString();(L(l.attributes)?l.attributes:_).filter(q).forEach((t=>{var r;if(A&&A.length&&P.push({[t]:{[U.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&&P.push({[t]:{[U.like]:`%${i}%`}})}})),P.length&&(l.where=Object.assign(Object.assign({},l.where),{[U.or]:[...P]}));const E=null!==(d=yield c.count(Object.assign(Object.assign({},l),{col:_[0]})).catch(this.error))&&void 0!==d?d:0,O=yield c.findAll(l).catch(this.error),S={count:E,limit:null!==(a=l.limit)&&void 0!==a?a:-1,offset:null!==(u=l.offset)&&void 0!==u?u:0};return O?(e.prepare(m.OK,Object.assign(Object.assign({},S),{records:r?yield r(O):O})),Object.assign(Object.assign({},S),{records:O})):(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 se(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({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i})})).catch(this.error);return n?(e.success("OK"),n):(e.notFound("Record not found"),0)}))}error(e){e.sql?fe.error(e.message+"\n"+e.sql,"api.controller.sql",oe.API_CONSOLE_ERROR):super.error(e)}_get(e){return se(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(m.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 se(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=this.key(),{[i]:n}=e.req.params,[s]=(yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:n})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};qe=re([h(ke)],qe);let Le=class extends qe{add(e){return se(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}create(){return{}}del(e){return se(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return se(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return se(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return se(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}};re([u(),c("auth"),c("write"),c("validationAdd"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"add",null),re([p(),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"all",null),re([y("/:id"),c("auth"),c("write"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"del",null),re([p("/:id"),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"get",null),re([_("/:id"),c("auth"),c("write"),c("validationSet"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"set",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"validationAdd",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Le.prototype,"validationSet",null),Le=re([h(qe)],Le);let Be=class extends Le{model(){return le}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};Be=re([g("/groups"),h(Le)],Be);let je=class extends qe{model(){return pe}all(e,t){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:he,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield le.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield pe.destroy({where:{groupId:t}}),r){let e=0;for(let i=0;i<r.length;i++)e=yield he.count({where:{id:r[i]}}),e&&(yield pe.create({groupId:t,routeId:r[i]}))}return e.success("OK")}if(B(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([p("/:id/routes"),c("auth"),c("read","groups"),ie(0,r()),ie(1,I("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],je.prototype,"all",null),re([_("/:id/routes"),c("auth"),c("write","groups"),c("validation",{routes:N.array(N.number().parse())}),ie(0,r()),ie(1,I("id")),ie(2,l("routes")),ne("design:type",Function),ne("design:paramtypes",[a,String,Array]),ne("design:returntype",Promise)],je.prototype,"set",null),je=re([g("/groups"),h(qe)],je);let Ke=class extends qe{model(){return Ie}all(e,t,r){return se(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","DESC"]]}})}))}};re([p(),c("auth"),c("read"),ie(0,r()),ie(1,v("type")),ie(2,v("source")),ne("design:type",Function),ne("design:paramtypes",[a,String,String]),ne("design:returntype",Promise)],Ke.prototype,"all",null),Ke=re([g("/logs"),h(qe)],Ke);let Me=class extends ke{register(e,t,r){return se(this,void 0,void 0,(function*(){yield D(oe.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=O(d);if(yield me.count({where:{[U.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=O(a))return e.error("Invalid password");const l=yield me.create({name:i,email:s,username:u,password:c,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!l)return e.error("Internal Server Error");const p=yield ge.create({token:yield this.getId(),userId:l.id,state:!0}).catch(this.error);if(!p)return l.destroy(),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 se(this,void 0,void 0,(function*(){const i=yield ge.findOne({where:{token:t,state:!0},include:[{model:me,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 se(this,void 0,void 0,(function*(){const i=t,n=yield ge.findOne({where:{state:!0},include:[{model:me,required:!0,where:{[U.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 se(this,void 0,void 0,(function*(){const e=b();return(yield ge.count({where:{token:e}}))?this.getId():e}))}};re([u(),c("validation",{name:N.string().required(),date:N.string().date().required(),email:N.string().email().required(),username:N.string().min(4).empty(),password:N.string().min(5).required(),confirm:N.string().min(5).required()}),ie(0,r()),ie(1,l()),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,Object,Te]),ne("design:returntype",Promise)],Me.prototype,"register",null),re([u("/confirm"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,l("token")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Me.prototype,"confirm",null),re([u("/send"),c("validation",{username:N.string().min(4).required()}),ie(0,r()),ie(1,l("username")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Me.prototype,"send",null),Me=re([g("/register"),h(ke)],Me);let Ce=class extends Le{model(){return he}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};Ce=re([g("/routes"),h(Le)],Ce);let He=class extends ke{setup(e){return se(this,void 0,void 0,(function*(){if(0==(yield me.count())){const e=F(),t=yield me.create({name:"Admin",email:"admin@localhost",username:"admin",password:O("admin"+e),salt:e,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),r={description:"API CORE",state:!0},i=yield le.create(Object.assign({name:"admin"},r));yield ye.create({userId:t.id,groupId:i.id});const n=["read","write"],s=["users","groups","routes"];yield j(s,(e=>se(this,void 0,void 0,(function*(){yield j(n,(t=>se(this,void 0,void 0,(function*(){const n=e+"."+t,s=yield he.create(Object.assign({name:n},r));yield pe.create({groupId:i.id,routeId:s.id})}))))}))));const o=[...n,"delete","list","rename","upload"];yield j(o,(e=>se(this,void 0,void 0,(function*(){const t="files."+e,n=yield he.create(Object.assign({name:t},r));yield pe.create({groupId:i.id,routeId:n.id})}))));const d=yield he.create(Object.assign({name:"logs.read"},r));yield pe.create({groupId:i.id,routeId:d.id})}e.success("OK")}))}};re([p(),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],He.prototype,"setup",null),He=re([g("/setup"),h(ke)],He);let Ue=class extends qe{model(){return me}constructor(){super(),this.dir=oe.API_HTTP_PUBLIC+"/avatar",oe.API_HTTP_PUBLIC&&z(oe.API_HTTP_PUBLIC)&&!z(this.dir)&&Z(this.dir)}avatar(e,t,r){return se(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;if(z(t)&&J(t).isFile()&&$(t),r.avatar=i,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return se(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="",(yield t.save().catch(this.error))&&z(r)&&$(r),e.success("OK")}))}password(e,t,r,i){return se(this,void 0,void 0,(function*(){var n;const s=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);return t+=null!==(n=null==s?void 0:s.salt)&&void 0!==n?n:"",s&&s.password==O(t)?(s.salt=F(),s.password=O(r+s.salt),(yield s.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return se(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 se(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){return se(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save().catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=r.hash.encrypt(t),yield i.save().catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return se(this,void 0,void 0,(function*(){const e=b();return(yield this.model().count({where:{token:e}}))?this.token_new():e}))}add(e,t){return se(this,void 0,void 0,(function*(){const r=F();yield this._add({ctx:e,body:{password:O(t+r),salt:r}})}))}all(e){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return se(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return se(this,void 0,void 0,(function*(){const r=F();yield this._set({ctx:e,body:t?{password:O(t+r),salt:r}:{}})}))}};re([u("/avatar"),c("auth"),c("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),ie(0,r()),ie(1,f()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,Array,me]),ne("design:returntype",Promise)],Ue.prototype,"avatar",null),re([p("/avatar/remove"),c("auth"),ie(0,r()),ie(1,be()),ne("design:type",Function),ne("design:paramtypes",[a,me]),ne("design:returntype",Promise)],Ue.prototype,"avatar_remove",null),re([u("/password"),c("auth"),c("validation",{oldPassword:N.string().min(5).required(),newPassword:N.string().min(5).required()}),ie(0,r()),ie(1,l("oldPassword")),ie(2,l("newPassword")),ie(3,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,me]),ne("design:returntype",Promise)],Ue.prototype,"password",null),re([p("/token"),c("auth"),ie(0,r()),ie(1,be()),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,me,Te]),ne("design:returntype",Promise)],Ue.prototype,"token",null),re([p("/token/:id"),c("auth"),c("write"),ie(0,r()),ie(1,I("id")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ue.prototype,"token_get",null),re([p("/token/remove/:id"),c("auth"),c("write"),ie(0,r()),ie(1,I("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"token_remove",null),re([p("/token/renew/:id"),c("auth"),c("write"),ie(0,r()),ie(1,I("id")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ue.prototype,"token_renew",null),re([u(),c("auth"),c("write"),c("validation",{name:N.string().required(),email:N.string().email().required(),username:N.string().min(4).required(),password:N.string().min(5).required(),description:N.string().empty(""),state:N.boolean().parse().required()}),ie(0,r()),ie(1,l("password")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"add",null),re([p(),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Ue.prototype,"all",null),re([y("/:id"),c("auth"),c("write"),ie(0,r()),ie(1,be()),ie(2,I("id")),ne("design:type",Function),ne("design:paramtypes",[a,me,String]),ne("design:returntype",Promise)],Ue.prototype,"del",null),re([p("/:id"),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Ue.prototype,"get",null),re([_("/:id"),c("auth"),c("write"),c("validation",{name:N.string().empty(),email:N.string().email().empty(),username:N.string().min(4).empty(),password:N.string().min(5).empty().filter(""),description:N.string().empty(),state:N.boolean().parse().empty()}),ie(0,r()),ie(1,l("password")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"set",null),Ue=re([g("/users"),h(qe),ne("design:paramtypes",[])],Ue);let Ge=class extends qe{model(){return ye}all(e,t){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:le,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield me.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield ye.destroy({where:{userId:i.id}}),r){let e=0;for(let t=0;t<r.length;t++)e=yield le.count({where:{id:r[t]}}),e&&(yield ye.create({userId:i.id,groupId:r[t]}))}return e.success("OK")}if(B(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([p("/:id/groups"),c("auth"),c("read","users"),ie(0,r()),ie(1,I("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ge.prototype,"all",null),re([_("/:id/groups"),c("auth"),c("write","users"),c("validation",{groups:N.array(N.number().parse())}),ie(0,r()),ie(1,I("id")),ie(2,l("groups")),ne("design:type",Function),ne("design:paramtypes",[a,String,Array]),ne("design:returntype",Promise)],Ge.prototype,"set",null),Ge=re([g("/users"),h(qe)],Ge);export{Te as Application,ue as Auth,Ne as AuthController,we as Config,_e as Configs,ke as ControllerBase,Le as CrudController,de as Database,oe as Env,xe as FilesController,ce as Forgot,Fe as ForgotController,le as Group,pe as GroupRoute,Be as GroupsController,je as GroupsRoutesController,Ie as Log,fe as Logs,Ke as LogsController,qe as ModelController,De as Permission,ge as Register,Me as RegisterController,Re as ReqAuth,be as ReqUser,he as Route,Ce as RoutesController,ve as Session,He as SetupController,Se as Token,me as User,ye as UserGroup,Ue as UsersController,Ge as UsersGroupsController,Ae as crt,Ee as key,ae as sequelize};
|
|
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 p,Middleware as l,Query as y,Controller as g,Post as h,Body as v,Delete as m,Put as f,Params as _,Files as I}from"@andrewcaires/express";import{LogColor as P,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 K,forEachSeries as C}from"@andrewcaires/utils.js";import B from"ws";import{Connection as H,Model as M,Integer as U,PrimaryKey as Y,NotNull as G,AutoIncrement as z,String as W,FullDate as J,CreatedAt as X,UpdatedAt as $,DeletedAt as V,BelongsTo as Z,Database as Q,ModelName as ee,Boolean as te,Text as re,HasMany as ie,Hooks as ne,DateOnly as oe,DefaultScope as se,Scopes as de,BigInt as ae}from"@andrewcaires/sequelize";import{config as ue}from"dotenv";import{existsSync as ce,readFileSync as pe,statSync as le,readdirSync as ye,mkdirSync as ge,lstatSync as he,rmSync as ve}from"fs";import{Store as me}from"express-session";import{Op as fe}from"sequelize";import{verify as _e,sign as Ie}from"jsonwebtoken";import{join as Pe}from"path";function Ae(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 Oe(e,t){return function(r,i){t(r,i,e)}}function Ee(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Se(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,ue();class we{static getBool(e,t){return S(we.getString(e,t.toString()))}static getInt(e,t){return parseInt(we.getString(e,t.toString()))}static getMs(e,t){return w(we.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}we.API_CONSOLE_ERROR=we.getBool("API_CONSOLE_ERROR",!1),we.API_DEFAULT_PATH=we.getString("API_DEFAULT_PATH","/api"),we.API_DB_DATABASE=we.getString("API_DB_DATABASE",""),we.API_DB_HOST=we.getString("API_DB_HOST","127.0.0.1"),we.API_DB_PASSWORD=we.getString("API_DB_PASSWORD",""),we.API_DB_PORT=we.getInt("API_DB_PORT",3306),we.API_DB_TYPE=we.getString("API_DB_TYPE",""),we.API_DB_USERNAME=we.getString("API_DB_USERNAME","root"),we.API_DB_LOG=we.getBool("API_DB_LOG",!1),we.API_DB_PREFIX=we.getString("API_DB_PREFIX",""),we.API_DB_TIMEZONE=we.getString("API_DB_TIMEZONE","+00:00"),we.API_HTTP_CRT=we.getString("API_HTTP_CRT",""),we.API_HTTP_KEY=we.getString("API_HTTP_KEY",""),we.API_HTTP_PORT=we.getInt("API_HTTP_PORT",3e3),we.API_HTTP_PUBLIC=we.getString("API_HTTP_PUBLIC",""),we.API_HTTP_CROSS=we.getBool("API_HTTP_CROSS",!1),we.API_HTTP_HYBRID=we.getBool("API_HTTP_HYBRID",!1),we.API_HTTP_REDIRECT=we.getString("API_HTTP_REDIRECT",""),we.API_KEY_HASH=we.getString("API_KEY_HASH",""),we.API_KEY_HEADER=we.getString("API_KEY_HEADER","api_key"),we.API_MODEL_LIMIT=we.getInt("API_MODEL_LIMIT",10),we.API_MODEL_LIMIT_MAX=we.getInt("API_MODEL_LIMIT_MAX",500),we.API_NOTFOUND_REDIRECT=we.getString("API_NOTFOUND_REDIRECT",""),we.API_SLEEP_AUTH=we.getMs("API_SLEEP_AUTH","2s"),we.API_SLEEP_FORGOT=we.getMs("API_SLEEP_FORGOT","5s"),we.API_SLEEP_REGISTRY=we.getMs("API_SLEEP_REGISTRY","5s"),we.API_SESSION_NAME=we.getString("API_SESSION_NAME","session.id"),we.API_SESSION_LIFETIME=we.getMs("API_SESSION_LIFETIME","1d"),we.API_SESSION_SECRET=we.getString("API_SESSION_SECRET","yoursecret"),we.API_TOKEN_CRT=we.getString("API_TOKEN_CRT",""),we.API_TOKEN_KEY=we.getString("API_TOKEN_KEY",""),we.API_TOKEN_FORGOT=we.getMs("API_TOKEN_LIFETIME","1d"),we.API_TOKEN_HEADER=we.getString("API_TOKEN_HEADER","authorization"),we.API_TOKEN_LIFETIME=we.getMs("API_TOKEN_LIFETIME","1d"),we.API_TOKEN_RENEW=we.getMs("API_TOKEN_RENEW","1d"),we.API_UPLOAD_COUNT=we.getInt("API_UPLOAD_COUNT",1),we.API_UPLOAD_FIELD=we.getString("API_UPLOAD_FIELD","upload"),we.API_UPLOAD_SIZE=we.getInt("API_UPLOAD_SIZE",2),we.API_UPLOAD_TEMP=we.getString("API_UPLOAD_TEMP","./temp"),we.API_WEBSOCKET_START=we.getBool("API_WEBSOCKET_START",!1);const Te=new H({type:we.API_DB_TYPE,database:we.API_DB_DATABASE,username:we.API_DB_USERNAME,password:we.API_DB_PASSWORD,hostname:we.API_DB_HOST,hostport:we.API_DB_PORT,logging:we.API_DB_LOG,prefix:we.API_DB_PREFIX});class be extends M{}const De={afterCreate:(e,t)=>Se(void 0,void 0,void 0,(function*(){var r,i,n;const o=T(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield je.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()),userId:null!==(n=null==t?void 0:t.userId)&&void 0!==n?n:null}).catch(b)})),afterUpdate:(e,t)=>Se(void 0,void 0,void 0,(function*(){var r,i,n;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 je.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}),userId:null!==(n=null==t?void 0:t.userId)&&void 0!==n?n:null}).catch(b)})),afterDestroy:(e,t)=>Se(void 0,void 0,void 0,(function*(){var r,i,n;const o=T(e)?e.constructor:null,s=null!==(r=null==o?void 0:o.primaryKeyAttribute)&&void 0!==r?r:null;yield je.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()),userId:null!==(n=null==t?void 0:t.userId)&&void 0!==n?n:null}).catch(b)}))};let Re=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],Re.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],Re.prototype,"secret",void 0),Ae([J(),Ee("design:type",Date)],Re.prototype,"logout",void 0),Ae([W(),Ee("design:type",W)],Re.prototype,"useragent",void 0),Ae([X,Ee("design:type",Date)],Re.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],Re.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],Re.prototype,"deletedAt",void 0),Ae([Z((()=>Ne)),Ee("design:type",Number)],Re.prototype,"userId",void 0),Re=Ae([Q(Te),ee("auth")],Re);let ke=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],ke.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],ke.prototype,"token",void 0),Ae([te(),Ee("design:type",te)],ke.prototype,"state",void 0),Ae([X,Ee("design:type",Date)],ke.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],ke.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],ke.prototype,"deletedAt",void 0),Ae([Z((()=>Ne)),Ee("design:type",Number)],ke.prototype,"userId",void 0),ke=Ae([Q(Te),ee("register")],ke);let xe=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],xe.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],xe.prototype,"name",void 0),Ae([re(),Ee("design:type",W)],xe.prototype,"description",void 0),Ae([te(),Ee("design:type",te)],xe.prototype,"state",void 0),Ae([X,Ee("design:type",Date)],xe.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],xe.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],xe.prototype,"deletedAt",void 0),Ae([ie((()=>Fe),"groupId"),Ee("design:type",Array)],xe.prototype,"groups_routes",void 0),Ae([ie((()=>Fe),"groupId"),Ee("design:type",Array)],xe.prototype,"users_groups",void 0),xe=Ae([Q(Te),ee("group"),ne(De)],xe);let Fe=class extends be{};Ae([X,Ee("design:type",Date)],Fe.prototype,"createdAt",void 0),Ae([Z((()=>xe)),Ee("design:type",Number)],Fe.prototype,"groupId",void 0),Ae([Z((()=>Ne)),Ee("design:type",Number)],Fe.prototype,"userId",void 0),Fe=Ae([Q(Te),ee("users_groups"),ne(De)],Fe);let Ne=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],Ne.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"name",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"email",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"username",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"password",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"salt",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"token",void 0),Ae([W(),Ee("design:type",W)],Ne.prototype,"avatar",void 0),Ae([oe(),Ee("design:type",W)],Ne.prototype,"date",void 0),Ae([re(),Ee("design:type",W)],Ne.prototype,"description",void 0),Ae([te(),Ee("design:type",te)],Ne.prototype,"state",void 0),Ae([X,Ee("design:type",Date)],Ne.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],Ne.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],Ne.prototype,"deletedAt",void 0),Ae([ie((()=>je),"userId"),Ee("design:type",Array)],Ne.prototype,"audits",void 0),Ae([ie((()=>Re),"userId"),Ee("design:type",Array)],Ne.prototype,"auths",void 0),Ae([ie((()=>ke),"userId"),Ee("design:type",Array)],Ne.prototype,"registers",void 0),Ae([ie((()=>Fe),"userId"),Ee("design:type",Array)],Ne.prototype,"users_groups",void 0),Ne=Ae([Q(Te),ee("user"),se({attributes:{exclude:["password","salt","token"]}}),de({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),ne(De)],Ne);let je=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],je.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],je.prototype,"type",void 0),Ae([W(),Ee("design:type",W)],je.prototype,"model",void 0),Ae([U(),Ee("design:type",W)],je.prototype,"record",void 0),Ae([re(),Ee("design:type",W)],je.prototype,"data",void 0),Ae([X,Ee("design:type",Date)],je.prototype,"createdAt",void 0),Ae([V,Ee("design:type",Date)],je.prototype,"deletedAt",void 0),Ae([Z((()=>Ne)),Ee("design:type",Number)],je.prototype,"userId",void 0),je=Ae([Q(Te),ee("audit")],je);let qe=class extends be{};Ae([W(),Ee("design:type",W)],qe.prototype,"key",void 0),Ae([W(),Ee("design:type",W)],qe.prototype,"value",void 0),Ae([X,Ee("design:type",Date)],qe.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],qe.prototype,"updatedAt",void 0),qe=Ae([Q(Te),ee("configs"),ne(De)],qe);let Le=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],Le.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],Le.prototype,"token",void 0),Ae([ae(),Ee("design:type",Number)],Le.prototype,"timestamp",void 0),Ae([te(),Ee("design:type",te)],Le.prototype,"state",void 0),Ae([X,Ee("design:type",Date)],Le.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],Le.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],Le.prototype,"deletedAt",void 0),Ae([Z((()=>Ne)),Ee("design:type",Number)],Le.prototype,"userId",void 0),Le=Ae([Q(Te),ee("forgot")],Le);let Ke=class extends be{};Ae([U(),Y,G,z,Ee("design:type",Number)],Ke.prototype,"id",void 0),Ae([W(),Ee("design:type",W)],Ke.prototype,"name",void 0),Ae([re(),Ee("design:type",W)],Ke.prototype,"description",void 0),Ae([te(),Ee("design:type",te)],Ke.prototype,"state",void 0),Ae([X,Ee("design:type",Date)],Ke.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],Ke.prototype,"updatedAt",void 0),Ae([V,Ee("design:type",Date)],Ke.prototype,"deletedAt",void 0),Ae([ie((()=>Ce),"routeId"),Ee("design:type",Array)],Ke.prototype,"groups_routes",void 0),Ke=Ae([Q(Te),ee("route"),ne(De)],Ke);let Ce=class extends be{};Ae([X,Ee("design:type",Date)],Ce.prototype,"createdAt",void 0),Ae([Z((()=>xe)),Ee("design:type",Number)],Ce.prototype,"groupId",void 0),Ae([Z((()=>Ke)),Ee("design:type",Number)],Ce.prototype,"routeId",void 0),Ce=Ae([Q(Te),ee("groups_routes"),ne(De)],Ce);let Be=class extends be{};Ae([W(),Ee("design:type",W)],Be.prototype,"type",void 0),Ae([W(),Ee("design:type",W)],Be.prototype,"source",void 0),Ae([re(),Ee("design:type",W)],Be.prototype,"message",void 0),Ae([X,Ee("design:type",Date)],Be.prototype,"createdAt",void 0),Be=Ae([Q(Te),ee("log")],Be);let He=class extends be{};Ae([W(),Ee("design:type",W)],He.prototype,"session",void 0),Ae([re(),Ee("design:type",W)],He.prototype,"json",void 0),Ae([ae(),Ee("design:type",Number)],He.prototype,"expired",void 0),Ae([X,Ee("design:type",Date)],He.prototype,"createdAt",void 0),Ae([$,Ee("design:type",Date)],He.prototype,"updatedAt",void 0),He=Ae([Q(Te),ee("session")],He);class Me{static write(e,t,r){return Se(this,void 0,void 0,(function*(){yield Me.writeRaw(P.White,"",e,t,r)}))}static error(e,t,r){return Se(this,void 0,void 0,(function*(){yield Me.writeRaw(P.Red,"error",e,t,r)}))}static info(e,t,r){return Se(this,void 0,void 0,(function*(){yield Me.writeRaw(P.Cyan,"info",e,t,r)}))}static success(e,t,r){return Se(this,void 0,void 0,(function*(){yield Me.writeRaw(P.Green,"success",e,t,r)}))}static warning(e,t,r){return Se(this,void 0,void 0,(function*(){yield Me.writeRaw(P.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return Se(this,void 0,void 0,(function*(){n&&A.console(e,t,r),Te&&(yield Be.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Ue=e=>ce(e)?pe(e):void 0,Ye={http:Ue(we.API_HTTP_CRT),token:Ue(we.API_TOKEN_CRT)},Ge={http:Ue(we.API_HTTP_KEY),token:Ue(we.API_TOKEN_KEY)};class ze extends me{constructor(){super(),this.all=e=>Se(this,void 0,void 0,(function*(){e=e||b;const t=yield He.findAll({attributes:["session"],where:{expired:{[fe.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>Se(this,void 0,void 0,(function*(){yield He.destroy().catch(b),e&&e()})),this.destroy=(e,t)=>Se(this,void 0,void 0,(function*(){yield He.destroy({where:{session:e}}).catch(b),t&&t()})),this.expired=()=>Se(this,void 0,void 0,(function*(){yield He.destroy({where:{expired:{[fe.lt]:Date.now()}}}).catch(b)})),this.get=(e,t)=>Se(this,void 0,void 0,(function*(){t=t||b;const r=yield He.findOne({where:{session:e,expired:{[fe.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=>Se(this,void 0,void 0,(function*(){e&&e(null,(yield He.count().catch(b))||0)})),this.set=(e,t,r)=>Se(this,void 0,void 0,(function*(){r=r||b;const i=Date.now()+we.API_SESSION_LIFETIME,n=JSON.stringify(t),[o,s]=(yield He.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 We{static create(e){return Se(this,void 0,void 0,(function*(){if(!Ge.token)return{error:"Key not found"};const{id:t}=e,r=R(),i=yield Re.create({secret:r,userId:t}).catch(We.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:Ie({id:t,secret:r},Ge.token,We.options())}}))}static destroy(e){return Se(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){Me.error(e.message,"api.token",we.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:we.API_TOKEN_LIFETIME+"ms"}}static renew(e){return Se(this,void 0,void 0,(function*(){if(!Ge.token)return{error:"Key not found"};const{error:t,decode:r}=We.verify(e,we.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield Ne.findOne({where:{id:e,state:!0}}).catch(We.error);if(r){const i=yield Re.findOne({where:{secret:t,userId:r.id}}).catch(We.error);if(i&&!i.logout){i.secret=R(),yield i.save().catch(We.error);return{auth:i,token:Ie({id:e,secret:i.secret},Ge.token,We.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return Se(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield Ne.findOne({where:{token:t,state:!0}}).catch(We.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield Re.findOrCreate({where:{secret:t,userId:i.id},defaults:{secret:t,userId:i.id}}).catch(We.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:n}=We.verify(t);if(i)return{error:i};if(n){const{id:e,secret:t}=n;if(e&&t){const r=yield Ne.findOne({where:{id:e,state:!0}}).catch(We.error);if(r){const e=yield Re.findOne({where:{secret:t,userId:r.id}}).catch(We.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:_e(e,Ye.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class Je extends e{constructor(e){super(e,{cert:Ye.http,cross:we.API_HTTP_CROSS,hybrid:we.API_HTTP_HYBRID,key:Ge.http,notfound:we.API_NOTFOUND_REDIRECT,path:we.API_DEFAULT_PATH,port:we.API_HTTP_PORT,public:we.API_HTTP_PUBLIC,redirect:we.API_HTTP_REDIRECT,session:{store:new ze,name:we.API_SESSION_NAME,secret:we.API_SESSION_SECRET,cookie:{maxAge:we.API_SESSION_LIFETIME},genid:R}}),this.hash=new O(we.API_KEY_HASH)}error(e,t){Me.error(e.message,t,we.API_CONSOLE_ERROR)}log(e,t){Me.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Se(this,void 0,void 0,(function*(){yield Te.sync(),yield e.listen.call(this),we.API_WEBSOCKET_START&&this.server&&(this._webSocket=new B.Server({server:this.server,verifyClient:(e,t)=>t(we.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>Se(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=>Se(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 We.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 Xe{static all(){return Se(this,void 0,void 0,(function*(){const e=yield qe.findAll().catch(Xe.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e,t){return Se(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}},{userId:i})).catch(Xe.error))||0)>0}))}static error(e){Me.error(e.message,"api.config",we.API_CONSOLE_ERROR)}static get(e){return Se(this,arguments,void 0,(function*(e,t=""){const[r]=(yield qe.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(Xe.error))||[];return r?r.value:t}))}static set(e,t,r){return Se(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 qe.findOrCreate(Object.assign({where:{key:e}},{userId:n})).catch(Xe.error))||[];o&&(o.value=t,yield o.save().catch(Xe.error))}))}}const $e=t((({ctx:e})=>e.req.auth)),Ve=t((({ctx:e})=>e.req.user));class Ze{static all(e,t){return Se(this,void 0,void 0,(function*(){return yield Ke.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:Ce,required:!0,include:[{model:xe,required:!0,where:{state:!0},include:[{model:Fe,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{Me.error(e.message,"api.permission",we.API_CONSOLE_ERROR)}))}))}static get(e){return Se(this,void 0,void 0,(function*(){const t=yield Ze.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return Se(this,void 0,void 0,(function*(){const r=yield Ze.all(e,{name:t});return!!r&&r.length>0}))}}class Qe extends x{auth(e,t,r,i,n){return Se(this,void 0,void 0,(function*(){const{auth:o,error:s,user:d}=yield We.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 Se(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){Me.error(e.message,"api.controller",we.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return Se(this,void 0,void 0,(function*(){return r?(yield Ze.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return Se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){t.path||(t.path=we.API_UPLOAD_TEMP),t.size||(t.size=we.API_UPLOAD_SIZE),t.field||(t.field=we.API_UPLOAD_FIELD),d.middleware(e,t)}validation(e,t){return Se(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 Se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}Ae([Oe(0,r()),Oe(1,i(we.API_KEY_HEADER)),Oe(2,i(we.API_TOKEN_HEADER)),Oe(3,i("user-agent")),Oe(4,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String,String,Je]),Ee("design:returntype",Promise)],Qe.prototype,"auth",null),Ae([Oe(0,r()),Oe(1,i("user-agent")),Oe(2,o()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Object]),Ee("design:returntype",Promise)],Qe.prototype,"session",null),Ae([Oe(0,r()),Oe(1,s()),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],Qe.prototype,"permission",null),Ae([Oe(0,r()),Oe(1,s()),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],Qe.prototype,"read",null),Ae([Oe(0,r()),Oe(1,s()),Ee("design:type",Function),Ee("design:paramtypes",[a,Object]),Ee("design:returntype",void 0)],Qe.prototype,"upload",null),Ae([Oe(0,r()),Oe(1,s()),Ee("design:type",Function),Ee("design:paramtypes",[a,Object]),Ee("design:returntype",Promise)],Qe.prototype,"validation",null),Ae([Oe(0,r()),Oe(1,s()),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],Qe.prototype,"write",null);let et=class extends Qe{constructor(){super(...arguments),this._columns=[]}_add(e){return Se(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||{}),{userId: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 Se(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){var n,o,s,d,a,u;const p=this.scope(i),l=Object.assign({},t||{});l.where=Object.assign({},l.where||{});const y=e.req.query.limit,g=N(y)?parseInt(y):we.API_MODEL_LIMIT;l.limit=g>=0?Math.min(g,we.API_MODEL_LIMIT_MAX):void 0;const h=e.req.query.offset;if(N(h)){const e=h?parseInt(h):0;l.offset=e>0?e:void 0}const v=[],m=this.columns(),f=e=>m.indexOf(e)>=0,_=null===(n=e.req.query.asc)||void 0===n?void 0:n.toString();_&&_.length&&v.push(..._.split(",").filter(f).map((e=>[e,"ASC"])));const I=null===(o=e.req.query.desc)||void 0===o?void 0:o.toString();I&&I.length&&v.push(...I.split(",").filter(f).map((e=>[e,"DESC"]))),v.length&&(l.order=v);const P=[],A=null===(s=e.req.query.search)||void 0===s?void 0:s.toString();(j(l.attributes)?l.attributes:m).filter(N).forEach((t=>{var r;if(A&&A.length&&P.push({[t]:{[fe.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&&P.push({[t]:{[fe.like]:`%${i}%`}})}})),P.length&&(l.where=Object.assign(Object.assign({},l.where),{[fe.or]:[...P]}));const O=null!==(d=yield p.count(Object.assign(Object.assign({},l),{col:m[0]})).catch(this.error))&&void 0!==d?d:0,E=yield p.findAll(l).catch(this.error),S={count:O,limit:null!==(a=l.limit)&&void 0!==a?a:-1,offset:null!==(u=l.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 Se(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}),{userId:s})).catch(this.error);return d?(e.success("OK"),d):(e.notFound("Record not found"),0)}))}error(e){e.sql?Me.error(e.message+"\n"+e.sql,"api.controller.sql",we.API_CONSOLE_ERROR):super.error(e)}_get(e){return Se(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 Se(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}),{userId:a})).catch(this.error))&&void 0!==o?o:[];return u?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};et=Ae([u(Qe)],et);let tt=class extends et{model(){return je}all(e,t,r){return Se(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","DESC"]]}})}))}get(e){return Se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}};Ae([p(),l("auth"),l("read"),Oe(0,r()),Oe(1,y("type")),Oe(2,y("table")),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String]),Ee("design:returntype",Promise)],tt.prototype,"all",null),Ae([p("/:id"),l("auth"),l("read"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],tt.prototype,"get",null),tt=Ae([g("/audits"),u(et)],tt);let rt=class extends Qe{login(e,t,r,i,n){return Se(this,void 0,void 0,(function*(){var o;yield k(we.API_SLEEP_AUTH);const s=yield Ne.scope("password").findOne({where:{[fe.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 ke.findOne({where:{state:!0,userId: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 We.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 Se(this,void 0,void 0,(function*(){if(yield We.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 Se(this,void 0,void 0,(function*(){const{auth:n,error:o,token:s}=yield We.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 Se(this,void 0,void 0,(function*(){const r=yield Ze.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};Ae([h("/login"),l("validation",{username:F.string().min(3).required(),password:F.string().min(5).required()}),Oe(0,r()),Oe(1,i("user-agent")),Oe(2,v("username")),Oe(3,v("password")),Oe(4,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String,String,Je]),Ee("design:returntype",Promise)],rt.prototype,"login",null),Ae([p("/logout"),l("auth"),Oe(0,r()),Oe(1,$e()),Oe(2,Ve()),Oe(3,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,Re,Ne,Je]),Ee("design:returntype",Promise)],rt.prototype,"logout",null),Ae([h("/renew"),l("validation",{token:F.string().required()}),Oe(0,r()),Oe(1,i("user-agent")),Oe(2,v("token")),Oe(3,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String,Je]),Ee("design:returntype",Promise)],rt.prototype,"renew",null),Ae([p(),l("auth"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],rt.prototype,"user",null),rt=Ae([g("/auth"),u(Qe)],rt);let it=class extends Qe{directory(){return we.API_HTTP_PUBLIC||"./"}files(e){return Se(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(!ce(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 Se(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!ce(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"}};Ae([p("/path/?*"),l("auth"),l("access","list"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],it.prototype,"files",null),Ae([Oe(0,r()),Oe(1,s()),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],it.prototype,"access",null),it=Ae([g("/files"),u(Qe)],it);let nt=class extends Qe{check(e,t){return Se(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 Se(this,void 0,void 0,(function*(){yield k(we.API_SLEEP_FORGOT);const i=t,n=yield Ne.findOne({where:{[fe.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const o=L(),s=Date.now()+6e4*we.API_TOKEN_FORGOT,d=yield Le.create({token:o,timestamp:s,state:!0,userId: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 Se(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 Se(this,void 0,void 0,(function*(){return yield Le.findOne({where:{token:e,state:!0},include:[{model:Ne,required:!0}]}).catch(this.error)}))}};Ae([p("/check"),l("validation",{token:F.string().required()}),Oe(0,r()),Oe(1,v("token")),Ee("design:type",Function),Ee("design:paramtypes",[a,String]),Ee("design:returntype",Promise)],nt.prototype,"check",null),Ae([h(),l("validation",{username:F.string().min(4).required()}),Oe(0,r()),Oe(1,v("username")),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Je]),Ee("design:returntype",Promise)],nt.prototype,"forgot",null),Ae([h("/reset"),l("validation",{token:F.string().required(),password:F.string().min(5).required()}),Oe(0,r()),Oe(1,v("token")),Oe(2,v("password")),Oe(3,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String,Je]),Ee("design:returntype",Promise)],nt.prototype,"reset",null),nt=Ae([g("/forgot"),u(Qe)],nt);let ot=class extends et{constructor(){super(...arguments),this._crud={}}add(e,t){return Se(this,void 0,void 0,(function*(){yield this._add({ctx:e,user:t})}))}all(e){return Se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}create(){return this._crud}del(e,t){return Se(this,void 0,void 0,(function*(){yield this._del({ctx:e,user:t})}))}get(e){return Se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return Se(this,void 0,void 0,(function*(){yield this._set({ctx:e,user:t})}))}update(){return this._crud}validationAdd(e){return Se(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 Se(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)}))}};Ae([h(),l("auth"),l("write"),l("validationAdd"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],ot.prototype,"add",null),Ae([p(),l("auth"),l("read"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],ot.prototype,"all",null),Ae([m("/:id"),l("auth"),l("write"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],ot.prototype,"del",null),Ae([p("/:id"),l("auth"),l("read"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],ot.prototype,"get",null),Ae([f("/:id"),l("auth"),l("write"),l("validationSet"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],ot.prototype,"set",null),Ae([Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],ot.prototype,"validationAdd",null),Ae([Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],ot.prototype,"validationSet",null),ot=Ae([u(et)],ot);let st=class extends ot{model(){return xe}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()}}};st=Ae([g("/groups"),u(ot)],st);let dt=class extends et{model(){return Ce}all(e,t){return Se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:Ke,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r,i){return Se(this,void 0,void 0,(function*(){const n=yield xe.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){const t=n.id,o={userId:i.id};if(yield Ce.destroy(Object.assign({where:{groupId:t}},o)),r){let e=0;for(let i=0;i<r.length;i++)e=yield Ke.count({where:{id:r[i]}}),e&&(yield Ce.create({groupId:t,routeId:r[i]},Object.assign({},o)))}return e.success("OK")}if(K(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Ae([p("/:id/routes"),l("auth"),l("read","groups"),Oe(0,r()),Oe(1,_("id")),Ee("design:type",Function),Ee("design:paramtypes",[a,String]),Ee("design:returntype",Promise)],dt.prototype,"all",null),Ae([f("/:id/routes"),l("auth"),l("write","groups"),l("validation",{routes:F.array(F.number().parse())}),Oe(0,r()),Oe(1,_("id")),Oe(2,v("routes")),Oe(3,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Array,Ne]),Ee("design:returntype",Promise)],dt.prototype,"set",null),dt=Ae([g("/groups"),u(et)],dt);let at=class extends et{model(){return Be}all(e,t,r){return Se(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","DESC"]]}})}))}};Ae([p(),l("auth"),l("read"),Oe(0,r()),Oe(1,y("type")),Oe(2,y("source")),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String]),Ee("design:returntype",Promise)],at.prototype,"all",null),at=Ae([g("/logs"),u(et)],at);let ut=class extends Qe{register(e,t,r){return Se(this,void 0,void 0,(function*(){yield k(we.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 Ne.count({where:{[fe.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 p=yield Ne.create({name:i,email:o,username:u,password:c,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!p)return e.error("Internal Server Error");const l=yield ke.create({token:yield this.getId(),userId:p.id,state:!0}).catch(this.error);if(!l)return p.destroy(),e.error("Internal Server Error");e.success("OK"),r.emit("register.user",{ctx:e,register:l,user:p}),this.emit("register.user",{ctx:e,register:l,user:p})}))}confirm(e,t,r){return Se(this,void 0,void 0,(function*(){const i=yield ke.findOne({where:{token:t,state:!0},include:[{model:Ne,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 Se(this,void 0,void 0,(function*(){const i=t,n=yield ke.findOne({where:{state:!0},include:[{model:Ne,required:!0,where:{[fe.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 Se(this,void 0,void 0,(function*(){const e=R();return(yield ke.count({where:{token:e}}))?this.getId():e}))}};Ae([h(),l("validation",{name:F.string().required(),date:F.string().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()}),Oe(0,r()),Oe(1,v()),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,Object,Je]),Ee("design:returntype",Promise)],ut.prototype,"register",null),Ae([h("/confirm"),l("validation",{token:F.string().required()}),Oe(0,r()),Oe(1,v("token")),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Je]),Ee("design:returntype",Promise)],ut.prototype,"confirm",null),Ae([h("/send"),l("validation",{username:F.string().min(4).required()}),Oe(0,r()),Oe(1,v("username")),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Je]),Ee("design:returntype",Promise)],ut.prototype,"send",null),ut=Ae([g("/register"),u(Qe)],ut);let ct=class extends ot{model(){return Ke}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()}}};ct=Ae([g("/routes"),u(ot)],ct);let pt=class extends Qe{setup(e){return Se(this,void 0,void 0,(function*(){if(0==(yield Ne.count())){const e=L(),t=yield Ne.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 xe.create(Object.assign({name:"admin"},r));yield Fe.create({userId:t.id,groupId:i.id});const n=["read","write"],o=["audits","users","groups","routes"];yield C(o,(e=>Se(this,void 0,void 0,(function*(){yield C(n,(t=>Se(this,void 0,void 0,(function*(){const n=yield Ke.create(Object.assign({name:`${e}.${t}`},r));yield Ce.create({groupId:i.id,routeId:n.id})}))))}))));const s=["delete","list","read","rename","upload","write"];yield C(s,(e=>Se(this,void 0,void 0,(function*(){const t=yield Ke.create(Object.assign({name:`files.${e}`},r));yield Ce.create({groupId:i.id,routeId:t.id})}))));const d=["logs"];yield C(d,(e=>Se(this,void 0,void 0,(function*(){const t=yield Ke.create(Object.assign({name:`${e}.read`},r));yield Ce.create({groupId:i.id,routeId:t.id})}))))}e.success("OK")}))}};Ae([p(),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],pt.prototype,"setup",null),pt=Ae([g("/setup"),u(Qe)],pt);let lt=class extends et{model(){return Ne}constructor(){super(),this.dir=we.API_HTTP_PUBLIC+"/avatar",we.API_HTTP_PUBLIC&&ce(we.API_HTTP_PUBLIC)&&!ce(this.dir)&&ge(this.dir)}avatar(e,t,r){return Se(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;ce(t)&&he(t).isFile()&&ve(t),r.avatar=i;const n={userId:r.id};if(yield r.save(Object.assign({},n)).catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return Se(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="";const i={userId:t.id};(yield t.save(Object.assign({},i)).catch(this.error))&&ce(r)&&ve(r),e.success("OK")}))}password(e,t,r,i){return Se(this,void 0,void 0,(function*(){var n;const o=yield this.scope("password").findOne({where:{id:i.id,state:!0}}).catch(this.error);if(t+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",!o||o.password!=E(t))return e.error("Record not changed");o.salt=L(),o.password=E(r+o.salt);const s={userId:i.id};if(yield o.save(Object.assign({},s)).catch(this.error))return e.success("OK");e.success("Record not changed")}))}token(e,t,r){return Se(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 Se(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 Se(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){i.token="";const t={userId:r.id};return yield i.save(Object.assign({},t)).catch(this.error),e.success("OK")}e.notFound("Record not found")}))}token_renew(e,t,r,i){return Se(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();n.token=i.hash.encrypt(t);const o={userId:r.id};return yield n.save(Object.assign({},o)).catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return Se(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 Se(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 Se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return Se(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 Se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t,r){return Se(this,void 0,void 0,(function*(){const i=L();yield this._set({ctx:e,body:t?{password:E(t+i),salt:i}:{},user:r})}))}};Ae([h("/avatar"),l("auth"),l("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),Oe(0,r()),Oe(1,I()),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Array,Ne]),Ee("design:returntype",Promise)],lt.prototype,"avatar",null),Ae([p("/avatar/remove"),l("auth"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],lt.prototype,"avatar_remove",null),Ae([h("/password"),l("auth"),l("validation",{oldPassword:F.string().min(5).required(),newPassword:F.string().min(5).required()}),Oe(0,r()),Oe(1,v("oldPassword")),Oe(2,v("newPassword")),Oe(3,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,String,Ne]),Ee("design:returntype",Promise)],lt.prototype,"password",null),Ae([p("/token"),l("auth"),Oe(0,r()),Oe(1,Ve()),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne,Je]),Ee("design:returntype",Promise)],lt.prototype,"token",null),Ae([p("/token/:id"),l("auth"),l("write"),Oe(0,r()),Oe(1,_("id")),Oe(2,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Je]),Ee("design:returntype",Promise)],lt.prototype,"token_get",null),Ae([p("/token/remove/:id"),l("auth"),l("write"),Oe(0,r()),Oe(1,_("id")),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],lt.prototype,"token_remove",null),Ae([p("/token/renew/:id"),l("auth"),l("write"),Oe(0,r()),Oe(1,_("id")),Oe(2,Ve()),Oe(3,n()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne,Je]),Ee("design:returntype",Promise)],lt.prototype,"token_renew",null),Ae([h(),l("auth"),l("write"),l("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()}),Oe(0,r()),Oe(1,v("password")),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],lt.prototype,"add",null),Ae([p(),l("auth"),l("read"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],lt.prototype,"all",null),Ae([m("/:id"),l("auth"),l("write"),Oe(0,r()),Oe(1,_("id")),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],lt.prototype,"del",null),Ae([p("/:id"),l("auth"),l("read"),Oe(0,r()),Ee("design:type",Function),Ee("design:paramtypes",[a]),Ee("design:returntype",Promise)],lt.prototype,"get",null),Ae([f("/:id"),l("auth"),l("write"),l("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()}),Oe(0,r()),Oe(1,v("password")),Oe(2,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Ne]),Ee("design:returntype",Promise)],lt.prototype,"set",null),lt=Ae([g("/users"),u(et),Ee("design:paramtypes",[])],lt);let yt=class extends et{model(){return Fe}groups(e,t){return Se(this,void 0,void 0,(function*(){yield this.all(e,t.id.toString())}))}all(e,t){return Se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:xe,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r,i){return Se(this,void 0,void 0,(function*(){const n=yield Ne.findByPk(t,{attributes:["id"]}).catch(this.error);if(n){const t={userId:i.id};if(yield Fe.destroy(Object.assign({where:{userId:n.id}},t)),r){let e=0;for(let i=0;i<r.length;i++)e=yield xe.count({where:{id:r[i]}}),e&&(yield Fe.create({userId:n.id,groupId:r[i]},Object.assign({},t)))}return e.success("OK")}if(K(n))return e.notFound("Record not found");e.error("Internal Server Error")}))}};Ae([p("/groups"),l("auth"),Oe(0,r()),Oe(1,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,Ne]),Ee("design:returntype",Promise)],yt.prototype,"groups",null),Ae([p("/:id/groups"),l("auth"),l("read","users"),Oe(0,r()),Oe(1,_("id")),Ee("design:type",Function),Ee("design:paramtypes",[a,String]),Ee("design:returntype",Promise)],yt.prototype,"all",null),Ae([f("/:id/groups"),l("auth"),l("write","users"),l("validation",{groups:F.array(F.number().parse())}),Oe(0,r()),Oe(1,_("id")),Oe(2,v("groups")),Oe(3,Ve()),Ee("design:type",Function),Ee("design:paramtypes",[a,String,Array,Ne]),Ee("design:returntype",Promise)],yt.prototype,"set",null),yt=Ae([g("/users"),u(et)],yt);export{Je as Application,je as Audit,tt as AuditsController,Re as Auth,rt as AuthController,Xe as Config,qe as Configs,Qe as ControllerBase,ot as CrudController,we as Env,it as FilesController,Le as Forgot,nt as ForgotController,xe as Group,Ce as GroupRoute,st as GroupsController,dt as GroupsRoutesController,Be as Log,Me as Logs,at as LogsController,be as Model,et as ModelController,Ze as Permission,ke as Register,ut as RegisterController,$e as ReqAuth,Ve as ReqUser,Ke as Route,ct as RoutesController,He as Session,pt as SetupController,We as Token,Ne as User,Fe as UserGroup,lt as UsersController,yt as UsersGroupsController,De as audit,Te as conn,Ye as crt,Ge as key};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"main": "./dist/index.cjs.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -45,31 +45,30 @@
|
|
|
45
45
|
},
|
|
46
46
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@andrewcaires/express": "^1.1.
|
|
49
|
-
"@andrewcaires/node": "^1.1.
|
|
50
|
-
"@andrewcaires/
|
|
48
|
+
"@andrewcaires/express": "^1.1.11",
|
|
49
|
+
"@andrewcaires/node": "^1.1.5",
|
|
50
|
+
"@andrewcaires/sequelize": "^1.0.1",
|
|
51
|
+
"@andrewcaires/utils.js": "^0.3.5",
|
|
51
52
|
"cors": "^2.8.5",
|
|
52
53
|
"dotenv": "^16.4.5",
|
|
53
54
|
"express-session": "^1.18.0",
|
|
54
55
|
"jsonwebtoken": "^9.0.2",
|
|
55
|
-
"mariadb": "^3.3.1",
|
|
56
|
-
"mysql2": "^3.11.0",
|
|
57
|
-
"sequelize": "^6.37.3",
|
|
58
56
|
"ws": "^8.18.0"
|
|
59
57
|
},
|
|
60
58
|
"devDependencies": {
|
|
61
|
-
"@rollup/plugin-commonjs": "^
|
|
59
|
+
"@rollup/plugin-commonjs": "^28.0.0",
|
|
62
60
|
"@rollup/plugin-terser": "^0.4.4",
|
|
63
|
-
"@rollup/plugin-typescript": "^
|
|
61
|
+
"@rollup/plugin-typescript": "^12.1.0",
|
|
64
62
|
"@types/cors": "^2.8.17",
|
|
65
63
|
"@types/express-session": "^1.18.0",
|
|
66
|
-
"@types/jsonwebtoken": "^9.0.
|
|
67
|
-
"@types/node": "^22.
|
|
64
|
+
"@types/jsonwebtoken": "^9.0.7",
|
|
65
|
+
"@types/node": "^22.7.2",
|
|
68
66
|
"@types/ws": "^8.5.12",
|
|
69
|
-
"eslint": "^9.
|
|
70
|
-
"
|
|
67
|
+
"eslint": "^9.11.1",
|
|
68
|
+
"mariadb": "^3.3.2",
|
|
69
|
+
"rollup": "^4.22.4",
|
|
71
70
|
"rollup-plugin-dts": "^6.1.1",
|
|
72
|
-
"tslib": "^2.
|
|
73
|
-
"typescript-eslint": "^8.
|
|
71
|
+
"tslib": "^2.7.0",
|
|
72
|
+
"typescript-eslint": "^8.7.0"
|
|
74
73
|
}
|
|
75
74
|
}
|