@andrewcaires/api 3.1.0 → 3.1.2
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 +13 -24
- package/dist/index.esm.js +2 -2
- package/package.json +11 -12
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.1.
|
|
2
|
+
* @andrewcaires/api v3.1.2
|
|
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/utils.js"),r=require("ws"),o=require("sequelize"),i=require("dotenv"),s=require("fs"),n=require("express-session"),d=require("jsonwebtoken"),a=require("multer"),l=require("path"),u=require("crypto-js");function c(e,t,r,o){var i,s=arguments.length,n=s<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--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function p(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(i,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(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 h{static getBool(e,r){return t.toBool(h.getString(e,r.toString()))}static getInt(e,t){return parseInt(h.getString(e,t.toString()))}static getMs(e,r){return t.parseMs(h.getString(e,r))}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_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=process.env.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 m{static connect(e){const t="connect_"+h.API_DB_TYPE.toLowerCase();if(t in m)return m[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},timezone:h.API_DB_TIMEZONE})}}const x=m.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:x,modelName:h.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class v extends o.Model{}v.init({token:o.DataTypes.STRING,timestamp:o.DataTypes.BIGINT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:h.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class I extends o.Model{}I.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:h.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class P extends o.Model{}P.init({},{sequelize:x,modelName:h.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),P.removeAttribute("id");class f extends o.Model{}f.init({token:o.DataTypes.STRING,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:h.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class A extends o.Model{}A.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:h.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class C extends o.Model{}C.init({name:o.DataTypes.STRING,email:o.DataTypes.STRING,username:o.DataTypes.STRING,password:o.DataTypes.STRING,avatar:o.DataTypes.STRING,date:o.DataTypes.DATEONLY,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:h.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class S extends o.Model{}S.init({},{sequelize:x,modelName:h.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),S.removeAttribute("id");class E extends o.Model{}E.init({key:o.DataTypes.STRING,value:o.DataTypes.STRING},{sequelize:x,modelName:h.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),E.removeAttribute("id");class O extends o.Model{}O.init({type:o.DataTypes.STRING,source:o.DataTypes.STRING,message:o.DataTypes.TEXT},{sequelize:x,modelName:h.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class T extends o.Model{}var w;T.init({session:o.DataTypes.STRING,json:o.DataTypes.TEXT,expired:o.DataTypes.BIGINT},{sequelize:x,modelName:h.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),T.removeAttribute("id"),C.hasMany(_),_.belongsTo(C),C.hasMany(v),v.belongsTo(C),C.hasMany(f),f.belongsTo(C),I.hasMany(P),P.belongsTo(I),A.hasMany(P),P.belongsTo(A),C.hasMany(S),S.belongsTo(C),I.hasMany(S),S.belongsTo(I),exports.LogsColor=void 0,(w=exports.LogsColor||(exports.LogsColor={})).ERROR="[31m",w.INFO="[36m",w.NONE="[37m",w.SUCCESS="[32m",w.WARNING="[33m";class R{static write(e,t,r){return y(this,void 0,void 0,(function*(){yield R.writeRaw(exports.LogsColor.NONE,"",e,t,r)}))}static error(e,t,r){return y(this,void 0,void 0,(function*(){yield R.writeRaw(exports.LogsColor.ERROR,"error",e,t,r)}))}static info(e,t,r){return y(this,void 0,void 0,(function*(){yield R.writeRaw(exports.LogsColor.INFO,"info",e,t,r)}))}static success(e,t,r){return y(this,void 0,void 0,(function*(){yield R.writeRaw(exports.LogsColor.ERROR,"success",e,t,r)}))}static warning(e,t,r){return y(this,void 0,void 0,(function*(){yield R.writeRaw(exports.LogsColor.WARNING,"warning",e,t,r)}))}static writeConsole(e,r,o){const i=t.dateFormat(new Date,"%H:%M:%S");console.log(">",e,r+" ".repeat(10-r.length),"[37m","|",i,"|",o)}static writeRaw(e,t,r,o,i){return y(this,void 0,void 0,(function*(){i&&R.writeConsole(e,t,r),x&&(yield O.create({type:t,source:o,message:r}).catch((()=>null)))}))}}const D=e=>s.existsSync(e)?s.readFileSync(e):void 0,N={http:D(h.API_HTTP_CRT),token:D(h.API_TOKEN_CRT)},F={http:D(h.API_HTTP_KEY),token:D(h.API_TOKEN_KEY)};class M extends n.Store{constructor(){super(),this.all=e=>y(this,void 0,void 0,(function*(){e=e||t.noop;const r=yield T.findAll({attributes:["session"],where:{expired:{[o.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));r&&e(null,r.map((e=>e.session))),e()})),this.clear=e=>y(this,void 0,void 0,(function*(){yield T.destroy().catch(t.noop),e&&e()})),this.destroy=(e,r)=>y(this,void 0,void 0,(function*(){yield T.destroy({where:{session:e}}).catch(t.noop),r&&r()})),this.expired=()=>y(this,void 0,void 0,(function*(){yield T.destroy({where:{expired:{[o.Op.lt]:Date.now()}}}).catch(t.noop)})),this.get=(e,r)=>y(this,void 0,void 0,(function*(){r=r||t.noop;const i=yield T.findOne({where:{session:e,expired:{[o.Op.gte]:Date.now()}}}).catch((e=>(r(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(t.noop),void r(null)}r(null,e)}else r(null)})),this.length=e=>y(this,void 0,void 0,(function*(){e&&e(null,(yield T.count().catch(t.noop))||0)})),this.set=(e,r,o)=>y(this,void 0,void 0,(function*(){o=o||t.noop;const i=Date.now()+h.API_SESSION_LIFETIME,s=JSON.stringify(r),[n,d]=(yield T.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:i}}).catch(t.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(t.noop))),o()})),this.loop=t.loop(this.expired,3e4),this.loop.start()}}class b{static create(e){return y(this,void 0,void 0,(function*(){if(!F.token)return{error:"Key not found"};const{id:r}=e,o=t.uuidv4(),i=yield _.create({secret:o,userId:r}).catch(b.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:d.sign({id:r,secret:o},F.token,b.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){R.error(e.message,"api.token",h.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:h.API_TOKEN_LIFETIME+"ms"}}static renew(e){return y(this,void 0,void 0,(function*(){if(!F.token)return{error:"Key not found"};const{error:r,decode:o}=b.verify(e,h.API_TOKEN_RENEW/1e3);if(r)return{error:r};if(o){const{id:e,secret:r}=o;if(e&&r){const o=yield C.findOne({where:{id:e,state:!0}}).catch(b.error);if(o){const i=yield _.findOne({where:{secret:r,userId:o.id}}).catch(b.error);if(i&&!i.logout){i.secret=t.uuidv4(),yield i.save().catch(b.error);return{auth:i,token:d.sign({id:e,secret:i.secret},F.token,b.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return y(this,void 0,void 0,(function*(){const{error:t,decode:r}=b.verify(e);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield C.findOne({where:{id:e,state:!0}}).catch(b.error);if(r){const e=yield _.findOne({where:{secret:t,userId:r.id}}).catch(b.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!N.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:d.verify(e,N.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class q extends e.Application{constructor(e){super(e,{cert:N.http,cross:h.API_HTTP_CROSS,hybrid:h.API_HTTP_HYBRID,key:F.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:t.uuidv4}})}error(e,t){R.info(e.message,t,h.API_CONSOLE_ERROR)}log(e,t){R.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return y(this,void 0,void 0,(function*(){yield x.sync(),yield e.listen.call(this),h.API_WEBSOCKET_START&&this.server&&(this._webSocket=new r.Server({server:this.server,verifyClient:(e,t)=>t(h.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,r)=>y(this,void 0,void 0,(function*(){r.url||(r.url="");const o=r.url.length<=1?"":r.url.replace(/\//g,".");let i;e.on("message",(t=>y(this,void 0,void 0,(function*(){if(i)try{const s=JSON.parse(t);this.emit("ws.message"+o,{data:s,message:t,req:r,user:i,ws:e})}catch(s){this.emit("ws.message"+o,{message:t,req:r,user:i,ws:e})}else{const{user:s}=yield b.user(t.toString());s&&(i=s,this.emit("ws.connection"+o,{req:r,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+o,{user:i,ws:e})})),yield t.sleep(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class B{static all(){return y(this,void 0,void 0,(function*(){const e=yield E.findAll().catch(B.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return y(this,void 0,void 0,(function*(){return((yield E.destroy({where:{key:e}}).catch(B.error))||0)>0}))}static error(e){R.error(e.message,"api.config",h.API_CONSOLE_ERROR)}static get(e,t=""){return y(this,void 0,void 0,(function*(){const r=yield E.findOne({where:{key:e}}).catch(B.error);return r?r.value:t}))}static set(e,t){return y(this,void 0,void 0,(function*(){const[r]=(yield E.findOrCreate({where:{key:e}}).catch(B.error))||[];r&&(r.value=t,yield r.save().catch(B.error))}))}}const L=e.parameterFactory((({req:e})=>e.auth)),k=e.parameterFactory((({req:e})=>t.toArray(e.files))),G=e.parameterFactory((({req:e})=>e.user));class U{static all(e,t){return y(this,void 0,void 0,(function*(){return yield A.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:P,required:!0,include:[{model:I,required:!0,where:{state:!0},include:[{model:S,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{R.error(e.message,"api.permission",h.API_CONSOLE_ERROR)}))}))}static get(e){return y(this,void 0,void 0,(function*(){const t=yield U.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return y(this,void 0,void 0,(function*(){const r=yield U.all(e,{name:t});return!!r&&r.length>0}))}}class j extends t.EventEmitter{constructor(){super(...arguments),this._uploads=t.cache()}auth(e,t,r,o){return y(this,void 0,void 0,(function*(){const{auth:i,error:s,user:n}=yield b.user(t);return s?e.error(s):i&&n?i.useragent!=r?e.error("Invalid token"):(e.req.auth=i,e.req.user=n,void o()):e.error("Internal Server Error")}))}session(e,r,o){return y(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=e&&r.regenerate(t.noop):(r.useragent=e,r.save(t.noop))),o()}))}error(e){R.error(e.message,"api.controller",h.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r,o){return y(this,void 0,void 0,(function*(){if(!o)return e.unauthorized("Access denied");(yield U.is(o,r))?t():e.unauthorized("Access denied")}))}read(e,t,r,o){return y(this,void 0,void 0,(function*(){yield this.permission(e,t,(r||this.name())+".read",o)}))}upload(e,t,r){const o=this._uploads(r);o.upload||(o.upload=this.uploadMiddleware(r)),o.upload(e.req,e.res,(r=>{var o;if(r)return e.error(r.message),void(null===(o=e.res.socket)||void 0===o||o.destroy(r));t()}))}uploadFile(e,r){const o=t.uuidv4()+"."+r;return s.existsSync(l.join(e,o))?this.uploadFile(e,r):o}uploadMiddleware(e){const t=(null==e?void 0:e.path)||h.API_UPLOAD_TEMP,r=a.diskStorage({destination:(e,r,o)=>o(null,t),filename:(e,r,o)=>y(this,void 0,void 0,(function*(){return o(null,this.uploadFile(t,r.originalname.split(".").pop()||"bin"))}))}),o=(null==e?void 0:e.types)||[],i=a({storage:r,fileFilter(e,t,r){return y(this,void 0,void 0,(function*(){if(o.length){const e=t.originalname.split(".").pop()||"bin";return-1!=o.indexOf(t.mimetype)||-1!=o.indexOf(e)?r(null,!0):r(new Error("File not allowed"))}return r(null,!0)}))},limits:{fileSize:1e6*((null==e?void 0:e.size)||h.API_UPLOAD_SIZE)}});return i.array((null==e?void 0:e.field)||h.API_UPLOAD_FIELD,(null==e?void 0:e.count)||h.API_UPLOAD_COUNT)}validation(e,r,o){return y(this,void 0,void 0,(function*(){const{error:i,value:s}=yield t.Validation.object(o).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=s,r()}))}write(e,t,r,o){return y(this,void 0,void 0,(function*(){yield this.permission(e,t,(r||this.name())+".write",o)}))}}c([p(0,e.Ctx()),p(1,e.Headers(h.API_TOKEN_HEADER)),p(2,e.Headers("user-agent")),p(3,e.Next()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,Function]),g("design:returntype",Promise)],j.prototype,"auth",null),c([p(0,e.Headers("user-agent")),p(1,e.Session()),p(2,e.Next()),g("design:type",Function),g("design:paramtypes",[String,Object,Function]),g("design:returntype",Promise)],j.prototype,"session",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),p(3,G()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,String,C]),g("design:returntype",Promise)],j.prototype,"permission",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),p(3,G()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,String,C]),g("design:returntype",Promise)],j.prototype,"read",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,Object]),g("design:returntype",void 0)],j.prototype,"upload",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,Object]),g("design:returntype",Promise)],j.prototype,"validation",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),p(3,G()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,String,C]),g("design:returntype",Promise)],j.prototype,"write",null),exports.AuthController=class extends j{login(e,r,i,s,n){return y(this,void 0,void 0,(function*(){yield t.sleep(h.API_SLEEP_AUTH);const d=i,a=yield C.findOne({where:{[o.Op.or]:[{email:d},{username:i}],[o.Op.and]:[{password:u.SHA256(s).toString()}]}}).catch(this.error);if(!a)return e.notFound("Invalid username or password"),e.destroy(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield f.findOne({where:{state:!0,userId:a.id}}).catch(this.error);if(l)return e.error("Activation required"),e.destroy(),n.emit("auth.activation",{ctx:e,register:l,user:a}),void this.emit("auth.activation",{ctx:e,register:l,user:a});if(!a.state)return e.notFound("Invalid username or password"),e.destroy(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const{auth:c,error:p,token:g}=yield b.create(a);return p?(e.error(p),e.destroy(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):c&&g?(c.useragent=r,yield c.save().catch(this.error),e.data({token:g}),e.destroy(),n.emit("auth.login",{auth:c,ctx:e,user:a}),void this.emit("auth.login",{auth:c,ctx:e,user:a})):(e.error("Internal Server Error"),e.destroy(),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 b.destroy(t))return e.success("Disconcerted"),e.destroy(),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:i,error:s,token:n}=yield b.renew(r);return s?e.error(s):i?(i.useragent=t,yield i.save().catch(this.error),e.data({token:n}),e.destroy(),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return y(this,void 0,void 0,(function*(){const r=yield U.all(t);if(!r)return e.error("Internal Server Error");e.data(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},c([e.Post("/login"),e.Middleware("validation",{username:t.Validation.string().min(3).required(),password:t.Validation.string().min(5).required()}),p(0,e.Ctx()),p(1,e.Headers("user-agent")),p(2,e.Body("username")),p(3,e.Body("password")),p(4,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,String,q]),g("design:returntype",Promise)],exports.AuthController.prototype,"login",null),c([e.Get("/logout"),e.Middleware("auth"),p(0,e.Ctx()),p(1,L()),p(2,G()),p(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,_,C,q]),g("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),c([e.Post("/renew"),e.Middleware("validation",{token:t.Validation.string().required()}),p(0,e.Ctx()),p(1,e.Headers("user-agent")),p(2,e.Body("token")),p(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,q]),g("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),c([e.Get(),e.Middleware("auth"),p(0,e.Ctx()),p(1,G()),g("design:type",Function),g("design:paramtypes",[e.Context,C]),g("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=c([e.Controller("/auth"),e.Extends(j)],exports.AuthController),exports.FilesController=class extends j{directory(){return h.API_HTTP_PUBLIC||"./"}files(r){return y(this,void 0,void 0,(function*(){let{path:o}=r.req;o=o.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=l.join(this.directory(),o);if(!s.existsSync(i)||!s.statSync(i).isDirectory())return r.status(e.Status.NOT_FOUND),{message:"Path not Found"};let n=[];return n=s.readdirSync(i),n=n.map((e=>this.info(l.join(i,e)))),n=n.filter(t.isDef),Object.assign(Object.assign({},this.info(i)),{files:n})}))}access(e,t,r,o){return y(this,void 0,void 0,(function*(){yield this.permission(e,t,"files_"+this.name()+"."+r,o)}))}info(e){if(!s.existsSync(e))return null;const t=s.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()}}},c([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.FilesController.prototype,"files",null),c([p(0,e.Ctx()),p(1,e.Next()),p(2,e.Argument()),p(3,G()),g("design:type",Function),g("design:paramtypes",[e.Context,Function,String,C]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=c([e.Controller("/files"),e.Extends(j)],exports.FilesController),exports.ForgotController=class extends j{check(e,r){return y(this,void 0,void 0,(function*(){const o=yield this.find(r);if(!o||!o.user)return e.notFound("User not found");o.token=t.uniqueID(),yield o.save(),e.data({token:o.token})}))}forgot(e,r,i){return y(this,void 0,void 0,(function*(){yield t.sleep(h.API_SLEEP_FORGOT);const s=r,n=yield C.findOne({where:{[o.Op.or]:[{email:s},{username:r}]}}).catch(this.error);if(!n)return e.notFound("User not found");const d=t.uniqueID(),a=Date.now()+6e4*h.API_TOKEN_FORGOT,l=yield v.create({token:d,timestamp:a,state:!0,userId:n.id});e.success("OK"),e.destroy(),i.emit("forgot.send",{ctx:e,forgot:l,user:n}),this.emit("forgot.send",{ctx:e,forgot:l,user:n})}))}reset(e,t,r,o){return y(this,void 0,void 0,(function*(){const i=yield this.find(t);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.password=u.SHA256(r).toString(),yield i.user.save().catch(this.error),e.success("OK"),e.destroy(),o.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 v.findOne({where:{token:e,state:!0},include:[{model:C,required:!0}]}).catch(this.error)}))}},c([e.Get("/check"),e.Middleware("validation",{token:t.Validation.string().required()}),p(0,e.Ctx()),p(1,e.Body("token")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),c([e.Post(),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),p(0,e.Ctx()),p(1,e.Body("username")),p(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,q]),g("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),c([e.Post("/reset"),e.Middleware("validation",{token:t.Validation.string().required(),password:t.Validation.string().min(5).required()}),p(0,e.Ctx()),p(1,e.Body("token")),p(2,e.Body("password")),p(3,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,q]),g("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=c([e.Controller("/forgot"),e.Extends(j)],exports.ForgotController),exports.ModelController=class extends j{constructor(){super(...arguments),this._columns=[]}_add({ctx:e,options:t,body:r}){return y(this,void 0,void 0,(function*(){const o=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),t||{}).catch(this.error);if(o){const t=this.key();return e.data({[t]:o.getDataValue(t)}),o}e.error("Internal Server Error")}))}_all({ctx:e,options:r,callback:i}){var s,n,d,a,l;return y(this,void 0,void 0,(function*(){const u=this.model(),c=Object.assign({},r||{});c.where=Object.assign({},c.where||{});const p=null===(s=e.req.query.limit)||void 0===s?void 0:s.toString();p&&(c.limit=parseInt(p));const g=null===(n=e.req.query.offset)||void 0===n?void 0:n.toString();g&&(c.offset=parseInt(g));const y=this.columns(),h=[],m=null===(d=e.req.query.asc)||void 0===d?void 0:d.toString();m&&m.length&&m.split(",").forEach((e=>{y.indexOf(e)>=0&&h.push([e,"ASC"])}));const x=null===(a=e.req.query.desc)||void 0===a?void 0:a.toString();x&&x.length&&x.split(",").forEach((e=>{y.indexOf(e)>=0&&h.push([e,"DESC"])})),h.length&&(c.order=h);const _=[],v=t.isArray(c.attributes)?c.attributes:y,I=null===(l=e.req.query.search)||void 0===l?void 0:l.toString();v.forEach((r=>{var i;if(t.isString(r)&&(I&&I.length&&_.push({[r]:{[o.Op.like]:`%${I}%`}}),"search_"+r in e.req.query)){const t=null===(i=e.req.query["search_"+r])||void 0===i?void 0:i.toString();t&&t.length&&_.push({[r]:{[o.Op.like]:`%${t}%`}})}})),_.length&&(c.where=Object.assign(Object.assign({},c.where),{[o.Op.or]:[..._]}));const P=(yield u.count(Object.assign(Object.assign({},c),{col:y[0]})).catch(this.error))||0,f=yield u.findAll(c).catch(this.error);return f?(e.data({count:P,records:i?yield i(f):f}),[f,P]):(e.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del({ctx:e,options:t}){return y(this,void 0,void 0,(function*(){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("Internal Server Error"),0;const i=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o})})).catch(this.error);return i?(e.success("OK"),i):(e.notFound("Record not found"),0)}))}error(e){e.sql?R.error(e.message+"\n"+e.sql,"api.controller.sql",h.API_CONSOLE_ERROR):super.error(e)}_get({ctx:e,options:t,callback:r}){return y(this,void 0,void 0,(function*(){const o=this.key(),{[o]:i}=e.req.params,s=yield this.model().findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[o]:i})})).catch(this.error);if(s)return e.data(r?yield r(s):s.toJSON()),s;null!==s?e.error("Internal Server Error"):e.notFound("Record not found")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}_set({ctx:e,options:t,body:r}){return y(this,void 0,void 0,(function*(){const o=this.key(),{[o]:i}=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),{[o]:i})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=c([e.Extends(j)],exports.ModelController),exports.CrudController=class extends exports.ModelController{create(){return{}}add(e){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return y(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return y(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return y(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e,t){return y(this,void 0,void 0,(function*(){yield this.validation(e,t,this.create())}))}validationSet(e,t){return y(this,void 0,void 0,(function*(){yield this.validation(e,t,this.update())}))}},c([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationAdd"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"add",null),c([e.Get(),e.Middleware("auth"),e.Middleware("read"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"all",null),c([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"del",null),c([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"get",null),c([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationSet"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"set",null),c([p(0,e.Ctx()),p(1,e.Next()),g("design:type",Function),g("design:paramtypes",[e.Context,Function]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),c([p(0,e.Ctx()),p(1,e.Next()),g("design:type",Function),g("design:paramtypes",[e.Context,Function]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=c([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return I}create(){return{name:t.Validation.string().required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}}update(){return{name:t.Validation.string().empty(),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}}},exports.GroupsController=c([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return P}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:A,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,r,o){return y(this,void 0,void 0,(function*(){const i=yield I.findByPk(r,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield P.destroy({where:{groupId:t}}),o){let e=0;for(let r=0;r<o.length;r++)e=yield A.count({where:{id:o[r]}}),e&&(yield P.create({groupId:t,routeId:o[r]}))}return e.success("OK")}if(t.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},c([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),p(0,e.Ctx()),p(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),c([e.Put("/:id/routes"),e.Middleware("auth"),e.Middleware("write","groups"),e.Middleware("validation",{routes:t.Validation.array(t.Validation.number().parse())}),p(0,e.Ctx()),p(1,e.Params("id")),p(2,e.Body("routes")),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array]),g("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=c([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return O}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"]]}})}))}},c([e.Get(),e.Middleware("auth"),e.Middleware("read"),p(0,e.Ctx()),p(1,e.Query("type")),p(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=c([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends j{register(e,r,i){return y(this,void 0,void 0,(function*(){yield t.sleep(h.API_SLEEP_REGISTRY);const{name:s,date:n,email:d,username:a,password:l,confirm:c}=r,p=a||d,g=u.SHA256(l).toString();if(yield C.count({where:{[o.Op.or]:[{email:d},{username:p}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=u.SHA256(c).toString())return e.error("Invalid password");const y=yield C.create({name:s,email:d,username:p,password:g,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const m=yield f.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"),e.destroy(),i.emit("register.user",{ctx:e,register:m,user:y}),this.emit("register.user",{ctx:e,register:m,user:y})}))}confirm(e,t,r){return y(this,void 0,void 0,(function*(){const o=yield f.findOne({where:{token:t,state:!0},include:[{model:C,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"),e.destroy(),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 i=t,s=yield f.findOne({where:{state:!0},include:[{model:C,required:!0,where:{[o.Op.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("User not found");e.success("OK"),e.destroy(),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=t.uuidv4();return(yield f.count({where:{token:e}}))?this.getId():e}))}},c([e.Post(),e.Middleware("validation",{name:t.Validation.string().required(),date:t.Validation.string().date().required(),email:t.Validation.string().email().required(),username:t.Validation.string().min(4).empty(),password:t.Validation.string().min(5).required(),confirm:t.Validation.string().min(5).required()}),p(0,e.Ctx()),p(1,e.Body()),p(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,Object,q]),g("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),c([e.Post("/confirm"),e.Middleware("validation",{token:t.Validation.string().required()}),p(0,e.Ctx()),p(1,e.Body("token")),p(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,q]),g("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),c([e.Post("/send"),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),p(0,e.Ctx()),p(1,e.Body("username")),p(2,e.App()),g("design:type",Function),g("design:paramtypes",[e.Context,String,q]),g("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=c([e.Controller("/register"),e.Extends(j)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return A}create(){return{name:t.Validation.string().required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}}update(){return{name:t.Validation.string().empty(),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}}},exports.RoutesController=c([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends j{setup(e){return y(this,void 0,void 0,(function*(){if(0==(yield C.count())){const e={description:"",state:!0},r=yield C.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),o=yield I.create(Object.assign({name:"admin"},e));yield S.create({userId:r.id,groupId:o.id});const i=["read","write"],s=["users","groups","routes"];yield t.forEachSeries(s,(r=>y(this,void 0,void 0,(function*(){yield t.forEachSeries(i,(t=>y(this,void 0,void 0,(function*(){const i=r+"."+t,s=yield A.create(Object.assign({name:i},e));yield P.create({groupId:o.id,routeId:s.id})}))))}))));const n=[...i,"delete","list","rename","upload"];yield t.forEachSeries(n,(t=>y(this,void 0,void 0,(function*(){const r="files_api."+t,i=yield A.create(Object.assign({name:r},e));yield P.create({groupId:o.id,routeId:i.id})}))));const d=yield A.create(Object.assign({name:"logs.read"},e));yield P.create({groupId:o.id,routeId:d.id})}e.success("OK")}))}},c([e.Get(),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=c([e.Controller("/setup"),e.Extends(j)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return C}constructor(){super(),this.dir=h.API_HTTP_PUBLIC+"/avatar",h.API_HTTP_PUBLIC&&s.existsSync(h.API_HTTP_PUBLIC)&&!s.existsSync(this.dir)&&s.mkdirSync(this.dir)}avatar(e,r){return y(this,void 0,void 0,(function*(){if(t.isArray(e.req.files)&&e.req.files.length){const t=e.req.files[0].filename||"";if(t){const o=h.API_HTTP_PUBLIC+"/avatar/";if(s.existsSync(o+r.avatar)&&s.lstatSync(o+r.avatar).isFile()&&s.rmSync(o+r.avatar),r.avatar=t,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,o){return y(this,void 0,void 0,(function*(){const i=yield C.scope("password").findOne({where:{id:o.id,password:u.SHA256(t).toString(),state:!0}}).catch(this.error);return i?(i.password=u.SHA256(r).toString(),(yield i.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return y(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:u.SHA256(t).toString()}})}))}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*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}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,body:t?{password:u.SHA256(t).toString()}:{}})}))}},c([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:20}))),p(0,e.Ctx()),p(1,G()),g("design:type",Function),g("design:paramtypes",[e.Context,C]),g("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),c([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:t.Validation.string().min(5).required(),newPassword:t.Validation.string().min(5).required()}),p(0,e.Ctx()),p(1,e.Body("oldPassword")),p(2,e.Body("newPassword")),p(3,G()),g("design:type",Function),g("design:paramtypes",[e.Context,String,String,C]),g("design:returntype",Promise)],exports.UsersController.prototype,"password",null),c([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:t.Validation.string().required(),email:t.Validation.string().email().required(),username:t.Validation.string().min(4).required(),password:t.Validation.string().min(5).required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}),p(0,e.Ctx()),p(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"add",null),c([e.Get(),e.Middleware("auth"),e.Middleware("read"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"all",null),c([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),p(0,e.Ctx()),p(1,G()),p(2,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,C,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"del",null),c([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.UsersController.prototype,"get",null),c([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:t.Validation.string().empty(),email:t.Validation.string().email().empty(),username:t.Validation.string().min(4).empty(),password:t.Validation.string().min(5).empty().filter(""),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}),p(0,e.Ctx()),p(1,e.Body("password")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=c([e.Controller("/users"),e.Extends(exports.ModelController),g("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return S}all(e,t){return y(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:I,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,r,o){return y(this,void 0,void 0,(function*(){const i=yield C.findByPk(r,{attributes:["id"]}).catch(this.error);if(i){if(yield S.destroy({where:{userId:i.id}}),o){let e=0;for(let t=0;t<o.length;t++)e=yield I.count({where:{id:o[t]}}),e&&(yield S.create({userId:i.id,groupId:o[t]}))}return e.success("OK")}if(t.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},c([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),p(0,e.Ctx()),p(1,e.Params("id")),g("design:type",Function),g("design:paramtypes",[e.Context,String]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),c([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("write","users"),e.Middleware("validation",{groups:t.Validation.array(t.Validation.number().parse())}),p(0,e.Ctx()),p(1,e.Params("id")),p(2,e.Body("groups")),g("design:type",Function),g("design:paramtypes",[e.Context,String,Array]),g("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=c([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=q,exports.Auth=_,exports.Config=B,exports.Configs=E,exports.ControllerBase=j,exports.Database=m,exports.Env=h,exports.Forgot=v,exports.Group=I,exports.GroupRoute=P,exports.Log=O,exports.Logs=R,exports.Permission=U,exports.Register=f,exports.ReqAuth=L,exports.ReqFiles=k,exports.ReqUser=G,exports.Route=A,exports.Session=T,exports.Token=b,exports.User=C,exports.UserGroup=S,exports.crt=N,exports.key=F,exports.sequelize=x;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/utils.js"),r=require("ws"),o=require("sequelize"),i=require("dotenv"),s=require("@andrewcaires/node"),n=require("fs"),d=require("express-session"),a=require("jsonwebtoken"),l=require("multer"),u=require("path"),c=require("crypto-js");function p(e,t,r,o){var i,s=arguments.length,n=s<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--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function g(e,t){return function(r,o){t(r,o,e)}}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,r,o){return new(r||(r=Promise))((function(i,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(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 m{static getBool(e,r){return t.toBool(m.getString(e,r.toString()))}static getInt(e,t){return parseInt(m.getString(e,t.toString()))}static getMs(e,r){return t.parseMs(m.getString(e,r))}static getString(e,t){return e in process.env?process.env[e]||"":t}}m.API_CONSOLE_ERROR=m.getBool("API_CONSOLE_ERROR",!1),m.API_DEFAULT_PATH=m.getString("API_DEFAULT_PATH","/api"),m.API_DB_DATABASE=m.getString("API_DB_DATABASE",""),m.API_DB_HOST=m.getString("API_DB_HOST","127.0.0.1"),m.API_DB_PASSWORD=m.getString("API_DB_PASSWORD",""),m.API_DB_PORT=m.getInt("API_DB_PORT",3306),m.API_DB_TYPE=m.getString("API_DB_TYPE",""),m.API_DB_USERNAME=m.getString("API_DB_USERNAME","root"),m.API_DB_LOG=m.getBool("API_DB_LOG",!1),m.API_DB_PREFIX=m.getString("API_DB_PREFIX",""),m.API_DB_TIMEZONE=m.getString("API_DB_TIMEZONE","+00:00"),m.API_HTTP_CRT=m.getString("API_HTTP_CRT",""),m.API_HTTP_KEY=m.getString("API_HTTP_KEY",""),m.API_HTTP_PORT=m.getInt("API_HTTP_PORT",3e3),m.API_HTTP_PUBLIC=m.getString("API_HTTP_PUBLIC",""),m.API_HTTP_CROSS=m.getBool("API_HTTP_CROSS",!1),m.API_HTTP_HYBRID=m.getBool("API_HTTP_HYBRID",!1),m.API_HTTP_REDIRECT=m.getString("API_HTTP_REDIRECT",""),m.API_NOTFOUND_REDIRECT=m.getString("API_NOTFOUND_REDIRECT",""),m.API_SLEEP_AUTH=m.getMs("API_SLEEP_AUTH","2s"),m.API_SLEEP_FORGOT=m.getMs("API_SLEEP_FORGOT","5s"),m.API_SLEEP_REGISTRY=m.getMs("API_SLEEP_REGISTRY","5s"),m.API_SESSION_NAME=m.getString("API_SESSION_NAME","session.id"),m.API_SESSION_LIFETIME=m.getMs("API_SESSION_LIFETIME","1d"),m.API_SESSION_SECRET=m.getString("API_SESSION_SECRET","yoursecret"),m.API_TOKEN_CRT=m.getString("API_TOKEN_CRT",""),m.API_TOKEN_KEY=m.getString("API_TOKEN_KEY",""),m.API_TOKEN_FORGOT=m.getMs("API_TOKEN_LIFETIME","1d"),m.API_TOKEN_HEADER=m.getString("API_TOKEN_HEADER","authorization"),m.API_TOKEN_LIFETIME=m.getMs("API_TOKEN_LIFETIME","1d"),m.API_TOKEN_RENEW=m.getMs("API_TOKEN_RENEW","1d"),m.API_UPLOAD_COUNT=m.getInt("API_UPLOAD_COUNT",1),m.API_UPLOAD_FIELD=process.env.API_UPLOAD_FIELD||"upload",m.API_UPLOAD_SIZE=m.getInt("API_UPLOAD_SIZE",2),m.API_UPLOAD_TEMP=m.getString("API_UPLOAD_TEMP","./temp"),m.API_WEBSOCKET_START=m.getBool("API_WEBSOCKET_START",!1);class _{static connect(e){const t="connect_"+m.API_DB_TYPE.toLowerCase();if(t in _)return _[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:m.API_DB_LOG,define:{timestamps:!1},timezone:m.API_DB_TIMEZONE})}static connect_memory(){return new o.Sequelize("sqlite::memory:",{logging:m.API_DB_LOG,define:{timestamps:!1},timezone:m.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:m.API_DB_LOG,define:{timestamps:!1},timezone:m.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:m.API_DB_LOG,define:{timestamps:!1},timezone:m.API_DB_TIMEZONE})}static connect_sqlite(e){return new o.Sequelize({dialect:"sqlite",storage:e.database,logging:m.API_DB_LOG,define:{timestamps:!1},timezone:m.API_DB_TIMEZONE})}}const x=_.connect({database:m.API_DB_DATABASE,username:m.API_DB_USERNAME,password:m.API_DB_PASSWORD,hostname:m.API_DB_HOST,hostport:m.API_DB_PORT});class v extends o.Model{}v.init({secret:o.DataTypes.STRING,logout:o.DataTypes.DATE,useragent:o.DataTypes.STRING},{sequelize:x,modelName:m.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class P extends o.Model{}P.init({token:o.DataTypes.STRING,timestamp:o.DataTypes.BIGINT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:m.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class I extends o.Model{}I.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:m.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class f extends o.Model{}f.init({},{sequelize:x,modelName:m.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),f.removeAttribute("id");class A extends o.Model{}A.init({token:o.DataTypes.STRING,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:m.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class C extends o.Model{}C.init({name:o.DataTypes.STRING,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:m.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class S extends o.Model{}S.init({name:o.DataTypes.STRING,email:o.DataTypes.STRING,username:o.DataTypes.STRING,password:o.DataTypes.STRING,avatar:o.DataTypes.STRING,date:o.DataTypes.DATEONLY,description:o.DataTypes.TEXT,state:o.DataTypes.BOOLEAN},{sequelize:x,modelName:m.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class E extends o.Model{}E.init({},{sequelize:x,modelName:m.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),E.removeAttribute("id");class T extends o.Model{}T.init({key:o.DataTypes.STRING,value:o.DataTypes.STRING},{sequelize:x,modelName:m.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),T.removeAttribute("id");class O extends o.Model{}O.init({type:o.DataTypes.STRING,source:o.DataTypes.STRING,message:o.DataTypes.TEXT},{sequelize:x,modelName:m.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:x,modelName:m.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),w.removeAttribute("id"),S.hasMany(v),v.belongsTo(S),S.hasMany(P),P.belongsTo(S),S.hasMany(A),A.belongsTo(S),I.hasMany(f),f.belongsTo(I),C.hasMany(f),f.belongsTo(C),S.hasMany(E),E.belongsTo(S),I.hasMany(E),E.belongsTo(I);class R{static write(e,t,r){return h(this,void 0,void 0,(function*(){yield R.writeRaw(s.LogColor.White,"",e,t,r)}))}static error(e,t,r){return h(this,void 0,void 0,(function*(){yield R.writeRaw(s.LogColor.Red,"error",e,t,r)}))}static info(e,t,r){return h(this,void 0,void 0,(function*(){yield R.writeRaw(s.LogColor.Cyan,"info",e,t,r)}))}static success(e,t,r){return h(this,void 0,void 0,(function*(){yield R.writeRaw(s.LogColor.Green,"success",e,t,r)}))}static warning(e,t,r){return h(this,void 0,void 0,(function*(){yield R.writeRaw(s.LogColor.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,o,i){return h(this,void 0,void 0,(function*(){i&&s.Log.console(e,t,r),x&&(yield O.create({type:t,source:o,message:r}).catch((()=>null)))}))}}const D=e=>n.existsSync(e)?n.readFileSync(e):void 0,M={http:D(m.API_HTTP_CRT),token:D(m.API_TOKEN_CRT)},b={http:D(m.API_HTTP_KEY),token:D(m.API_TOKEN_KEY)};class q extends d.Store{constructor(){super(),this.all=e=>h(this,void 0,void 0,(function*(){e=e||t.noop;const r=yield w.findAll({attributes:["session"],where:{expired:{[o.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));r&&e(null,r.map((e=>e.session))),e()})),this.clear=e=>h(this,void 0,void 0,(function*(){yield w.destroy().catch(t.noop),e&&e()})),this.destroy=(e,r)=>h(this,void 0,void 0,(function*(){yield w.destroy({where:{session:e}}).catch(t.noop),r&&r()})),this.expired=()=>h(this,void 0,void 0,(function*(){yield w.destroy({where:{expired:{[o.Op.lt]:Date.now()}}}).catch(t.noop)})),this.get=(e,r)=>h(this,void 0,void 0,(function*(){r=r||t.noop;const i=yield w.findOne({where:{session:e,expired:{[o.Op.gte]:Date.now()}}}).catch((e=>(r(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(t.noop),void r(null)}r(null,e)}else r(null)})),this.length=e=>h(this,void 0,void 0,(function*(){e&&e(null,(yield w.count().catch(t.noop))||0)})),this.set=(e,r,o)=>h(this,void 0,void 0,(function*(){o=o||t.noop;const i=Date.now()+m.API_SESSION_LIFETIME,s=JSON.stringify(r),[n,d]=(yield w.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:i}}).catch(t.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(t.noop))),o()})),this.loop=t.loop(this.expired,3e4),this.loop.start()}}class F{static create(e){return h(this,void 0,void 0,(function*(){if(!b.token)return{error:"Key not found"};const{id:r}=e,o=t.uuidv4(),i=yield v.create({secret:o,userId:r}).catch(F.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:a.sign({id:r,secret:o},b.token,F.options())}}))}static destroy(e){return h(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){R.error(e.message,"api.token",m.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:m.API_TOKEN_LIFETIME+"ms"}}static renew(e){return h(this,void 0,void 0,(function*(){if(!b.token)return{error:"Key not found"};const{error:r,decode:o}=F.verify(e,m.API_TOKEN_RENEW/1e3);if(r)return{error:r};if(o){const{id:e,secret:r}=o;if(e&&r){const o=yield S.findOne({where:{id:e,state:!0}}).catch(F.error);if(o){const i=yield v.findOne({where:{secret:r,userId:o.id}}).catch(F.error);if(i&&!i.logout){i.secret=t.uuidv4(),yield i.save().catch(F.error);return{auth:i,token:a.sign({id:e,secret:i.secret},b.token,F.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return h(this,void 0,void 0,(function*(){const{error:t,decode:r}=F.verify(e);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield S.findOne({where:{id:e,state:!0}}).catch(F.error);if(r){const e=yield v.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(!M.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:a.verify(e,M.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class N extends e.Application{constructor(e){super(e,{cert:M.http,cross:m.API_HTTP_CROSS,hybrid:m.API_HTTP_HYBRID,key:b.http,notfound:m.API_NOTFOUND_REDIRECT,path:m.API_DEFAULT_PATH,port:m.API_HTTP_PORT,public:m.API_HTTP_PUBLIC,redirect:m.API_HTTP_REDIRECT,session:{store:new q,name:m.API_SESSION_NAME,secret:m.API_SESSION_SECRET,cookie:{maxAge:m.API_SESSION_LIFETIME},genid:t.uuidv4}})}error(e,t){R.info(e.message,t,m.API_CONSOLE_ERROR)}log(e,t){R.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return h(this,void 0,void 0,(function*(){yield x.sync(),yield e.listen.call(this),m.API_WEBSOCKET_START&&this.server&&(this._webSocket=new r.Server({server:this.server,verifyClient:(e,t)=>t(m.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,r)=>h(this,void 0,void 0,(function*(){r.url||(r.url="");const o=r.url.length<=1?"":r.url.replace(/\//g,".");let i;e.on("message",(t=>h(this,void 0,void 0,(function*(){if(i)try{const s=JSON.parse(t);this.emit("ws.message"+o,{data:s,message:t,req:r,user:i,ws:e})}catch(s){this.emit("ws.message"+o,{message:t,req:r,user:i,ws:e})}else{const{user:s}=yield F.user(t.toString());s&&(i=s,this.emit("ws.connection"+o,{req:r,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+o,{user:i,ws:e})})),yield t.sleep(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class B{static all(){return h(this,void 0,void 0,(function*(){const e=yield T.findAll().catch(B.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return h(this,void 0,void 0,(function*(){return((yield T.destroy({where:{key:e}}).catch(B.error))||0)>0}))}static error(e){R.error(e.message,"api.config",m.API_CONSOLE_ERROR)}static get(e){return h(this,arguments,void 0,(function*(e,t=""){const r=yield T.findOne({where:{key:e}}).catch(B.error);return r?r.value:t}))}static set(e,t){return h(this,void 0,void 0,(function*(){const[r]=(yield T.findOrCreate({where:{key:e}}).catch(B.error))||[];r&&(r.value=t,yield r.save().catch(B.error))}))}}const L=e.parameterFactory((({req:e})=>e.auth)),k=e.parameterFactory((({req:e})=>t.toArray(e.files))),j=e.parameterFactory((({req:e})=>e.user));class G{static all(e,t){return h(this,void 0,void 0,(function*(){return yield C.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:f,required:!0,include:[{model:I,required:!0,where:{state:!0},include:[{model:E,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{R.error(e.message,"api.permission",m.API_CONSOLE_ERROR)}))}))}static get(e){return h(this,void 0,void 0,(function*(){const t=yield G.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return h(this,void 0,void 0,(function*(){const r=yield G.all(e,{name:t});return!!r&&r.length>0}))}}class U extends t.EventEmitter{constructor(){super(...arguments),this._uploads=t.cache()}auth(e,t,r){return h(this,void 0,void 0,(function*(){const{auth:o,error:i,user:s}=yield F.user(t);return i?(e.error(i),e.close()):o&&s?o.useragent!=r?(e.error("Invalid token"),e.close()):(e.req.auth=o,e.req.user=s,void e.next()):(e.error("Internal Server Error"),e.close())}))}session(e,r,o){return h(this,void 0,void 0,(function*(){o.auth&&o.user&&(o.useragent?o.useragent!=r&&o.regenerate(t.noop):(o.useragent=r,o.save(t.noop))),e.next()}))}error(e){R.error(e.message,"api.controller",m.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return h(this,void 0,void 0,(function*(){return r?(yield G.is(r,t))?e.next():(e.unauthorized("Access denied"),void e.close()):(e.unauthorized("Access denied"),e.close())}))}read(e,t,r){return h(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){const r=this._uploads(t);r.upload||(r.upload=this.uploadMiddleware(t)),r.upload(e.req,e.res,(t=>{if(t)return e.destroy(t);e.next()}))}uploadFile(e,r){const o=t.uuidv4()+"."+r;return n.existsSync(u.join(e,o))?this.uploadFile(e,r):o}uploadMiddleware(e){const t=(null==e?void 0:e.path)||m.API_UPLOAD_TEMP,r=l.diskStorage({destination:(e,r,o)=>o(null,t),filename:(e,r,o)=>h(this,void 0,void 0,(function*(){return o(null,this.uploadFile(t,r.originalname.split(".").pop()||"bin"))}))}),o=(null==e?void 0:e.types)||[],i=l({storage:r,fileFilter(e,t,r){return h(this,void 0,void 0,(function*(){if(o.length){const e=t.originalname.split(".").pop()||"bin";return-1!=o.indexOf(t.mimetype)||-1!=o.indexOf(e)?r(null,!0):r(new Error("File not allowed"))}return r(null,!0)}))},limits:{fileSize:1e6*((null==e?void 0:e.size)||m.API_UPLOAD_SIZE)}});return i.array((null==e?void 0:e.field)||m.API_UPLOAD_FIELD,(null==e?void 0:e.count)||m.API_UPLOAD_COUNT)}validation(e,r){return h(this,void 0,void 0,(function*(){const{error:o,value:i}=yield t.Validation.object(r).parse().validateAsync(e.req.body);if(o)return e.validation(o),e.close();e.req.body=i,e.next()}))}write(e,t,r){return h(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}p([g(0,e.Ctx()),g(1,e.Headers(m.API_TOKEN_HEADER)),g(2,e.Headers("user-agent")),y("design:type",Function),y("design:paramtypes",[e.Context,String,String]),y("design:returntype",Promise)],U.prototype,"auth",null),p([g(0,e.Ctx()),g(1,e.Headers("user-agent")),g(2,e.Session()),y("design:type",Function),y("design:paramtypes",[e.Context,String,Object]),y("design:returntype",Promise)],U.prototype,"session",null),p([g(0,e.Ctx()),g(1,e.Argument()),g(2,j()),y("design:type",Function),y("design:paramtypes",[e.Context,String,S]),y("design:returntype",Promise)],U.prototype,"permission",null),p([g(0,e.Ctx()),g(1,e.Argument()),g(2,j()),y("design:type",Function),y("design:paramtypes",[e.Context,String,S]),y("design:returntype",Promise)],U.prototype,"read",null),p([g(0,e.Ctx()),g(1,e.Argument()),y("design:type",Function),y("design:paramtypes",[e.Context,Object]),y("design:returntype",void 0)],U.prototype,"upload",null),p([g(0,e.Ctx()),g(1,e.Argument()),y("design:type",Function),y("design:paramtypes",[e.Context,Object]),y("design:returntype",Promise)],U.prototype,"validation",null),p([g(0,e.Ctx()),g(1,e.Argument()),g(2,j()),y("design:type",Function),y("design:paramtypes",[e.Context,String,S]),y("design:returntype",Promise)],U.prototype,"write",null),exports.AuthController=class extends U{login(e,r,i,s,n){return h(this,void 0,void 0,(function*(){yield t.sleep(m.API_SLEEP_AUTH);const d=i,a=yield S.findOne({where:{[o.Op.or]:[{email:d},{username:i}],[o.Op.and]:[{password:c.SHA256(s).toString()}]}}).catch(this.error);if(!a)return e.notFound("Invalid username or password"),e.close(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const l=yield A.findOne({where:{state:!0,userId:a.id}}).catch(this.error);if(l)return e.error("Activation required"),e.close(),n.emit("auth.activation",{ctx:e,register:l,user:a}),void this.emit("auth.activation",{ctx:e,register:l,user:a});if(!a.state)return e.notFound("Invalid username or password"),e.close(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const{auth:u,error:p,token:g}=yield F.create(a);return p?(e.error(p),e.close(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&g?(u.useragent=r,yield u.save().catch(this.error),e.json({token:g}),e.close(),n.emit("auth.login",{auth:u,ctx:e,user:a}),void this.emit("auth.login",{auth:u,ctx:e,user:a})):(e.error("Internal Server Error"),e.close(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,o){return h(this,void 0,void 0,(function*(){if(yield F.destroy(t))return e.success("Disconcerted"),e.close(),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 h(this,void 0,void 0,(function*(){const{auth:i,error:s,token:n}=yield F.renew(r);return s?e.error(s):i?(i.useragent=t,yield i.save().catch(this.error),e.json({token:n}),e.close(),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return h(this,void 0,void 0,(function*(){const r=yield G.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},p([e.Post("/login"),e.Middleware("validation",{username:t.Validation.string().min(3).required(),password:t.Validation.string().min(5).required()}),g(0,e.Ctx()),g(1,e.Headers("user-agent")),g(2,e.Body("username")),g(3,e.Body("password")),g(4,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,String,String,N]),y("design:returntype",Promise)],exports.AuthController.prototype,"login",null),p([e.Get("/logout"),e.Middleware("auth"),g(0,e.Ctx()),g(1,L()),g(2,j()),g(3,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,v,S,N]),y("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),p([e.Post("/renew"),e.Middleware("validation",{token:t.Validation.string().required()}),g(0,e.Ctx()),g(1,e.Headers("user-agent")),g(2,e.Body("token")),g(3,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,String,N]),y("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),p([e.Get(),e.Middleware("auth"),g(0,e.Ctx()),g(1,j()),y("design:type",Function),y("design:paramtypes",[e.Context,S]),y("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=p([e.Controller("/auth"),e.Extends(U)],exports.AuthController),exports.FilesController=class extends U{directory(){return m.API_HTTP_PUBLIC||"./"}files(r){return h(this,void 0,void 0,(function*(){let{path:o}=r.req;o=o.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=u.join(this.directory(),o);if(!n.existsSync(i)||!n.statSync(i).isDirectory())return r.status(e.Status.NOT_FOUND),{message:"Path not Found"};let s=[];return s=n.readdirSync(i),s=s.map((e=>this.info(u.join(i,e)))),s=s.filter(t.isDef),Object.assign(Object.assign({},this.info(i)),{files:s})}))}access(e,t,r){return h(this,void 0,void 0,(function*(){yield this.permission(e,"files_"+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()}}},p([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.FilesController.prototype,"files",null),p([g(0,e.Ctx()),g(1,e.Argument()),g(2,j()),y("design:type",Function),y("design:paramtypes",[e.Context,String,S]),y("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=p([e.Controller("/files"),e.Extends(U)],exports.FilesController),exports.ForgotController=class extends U{check(e,r){return h(this,void 0,void 0,(function*(){const o=yield this.find(r);if(!o||!o.user)return e.notFound("User not found");o.token=t.uniqueID(),yield o.save(),e.json({token:o.token})}))}forgot(e,r,i){return h(this,void 0,void 0,(function*(){yield t.sleep(m.API_SLEEP_FORGOT);const s=r,n=yield S.findOne({where:{[o.Op.or]:[{email:s},{username:r}]}}).catch(this.error);if(!n)return e.notFound("User not found");const d=t.uniqueID(),a=Date.now()+6e4*m.API_TOKEN_FORGOT,l=yield P.create({token:d,timestamp:a,state:!0,userId:n.id});e.success("OK"),e.close(),i.emit("forgot.send",{ctx:e,forgot:l,user:n}),this.emit("forgot.send",{ctx:e,forgot:l,user:n})}))}reset(e,t,r,o){return h(this,void 0,void 0,(function*(){const i=yield this.find(t);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.password=c.SHA256(r).toString(),yield i.user.save().catch(this.error),e.success("OK"),e.close(),o.emit("forgot.reset",{ctx:e,user:i.user}),this.emit("forgot.reset",{ctx:e,user:i.user})}))}find(e){return h(this,void 0,void 0,(function*(){return yield P.findOne({where:{token:e,state:!0},include:[{model:S,required:!0}]}).catch(this.error)}))}},p([e.Get("/check"),e.Middleware("validation",{token:t.Validation.string().required()}),g(0,e.Ctx()),g(1,e.Body("token")),y("design:type",Function),y("design:paramtypes",[e.Context,String]),y("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),p([e.Post(),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),g(0,e.Ctx()),g(1,e.Body("username")),g(2,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,N]),y("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),p([e.Post("/reset"),e.Middleware("validation",{token:t.Validation.string().required(),password:t.Validation.string().min(5).required()}),g(0,e.Ctx()),g(1,e.Body("token")),g(2,e.Body("password")),g(3,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,String,N]),y("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=p([e.Controller("/forgot"),e.Extends(U)],exports.ForgotController),exports.ModelController=class extends U{constructor(){super(...arguments),this._columns=[]}_add(e){return h(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const o=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),t||{}).catch(this.error);if(o){const t=this.key();return e.json({[t]:o.getDataValue(t)}),o}e.error("Internal Server Error")}))}_all(e){return h(this,arguments,void 0,(function*({ctx:e,options:r,callback:i}){var s,n,d,a,l;const u=this.model(),c=Object.assign({},r||{});c.where=Object.assign({},c.where||{});const p=null===(s=e.req.query.limit)||void 0===s?void 0:s.toString();p&&(c.limit=parseInt(p));const g=null===(n=e.req.query.offset)||void 0===n?void 0:n.toString();g&&(c.offset=parseInt(g));const y=this.columns(),h=[],m=null===(d=e.req.query.asc)||void 0===d?void 0:d.toString();m&&m.length&&m.split(",").forEach((e=>{y.indexOf(e)>=0&&h.push([e,"ASC"])}));const _=null===(a=e.req.query.desc)||void 0===a?void 0:a.toString();_&&_.length&&_.split(",").forEach((e=>{y.indexOf(e)>=0&&h.push([e,"DESC"])})),h.length&&(c.order=h);const x=[],v=t.isArray(c.attributes)?c.attributes:y,P=null===(l=e.req.query.search)||void 0===l?void 0:l.toString();v.forEach((r=>{var i;if(t.isString(r)&&(P&&P.length&&x.push({[r]:{[o.Op.like]:`%${P}%`}}),"search_"+r in e.req.query)){const t=null===(i=e.req.query["search_"+r])||void 0===i?void 0:i.toString();t&&t.length&&x.push({[r]:{[o.Op.like]:`%${t}%`}})}})),x.length&&(c.where=Object.assign(Object.assign({},c.where),{[o.Op.or]:[...x]}));const I=(yield u.count(Object.assign(Object.assign({},c),{col:y[0]})).catch(this.error))||0,f=yield u.findAll(c).catch(this.error);return f?(e.json({count:I,records:i?yield i(f):f}),[f,I]):(e.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return h(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("Internal Server Error"),0;const i=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o})})).catch(this.error);return i?(e.success("OK"),i):(e.notFound("Record not found"),0)}))}error(e){e.sql?R.error(e.message+"\n"+e.sql,"api.controller.sql",m.API_CONSOLE_ERROR):super.error(e)}_get(e){return h(this,arguments,void 0,(function*({ctx:e,options:t,callback:r}){const o=this.key(),{[o]:i}=e.req.params,s=yield this.model().findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[o]:i})})).catch(this.error);return s?(e.json(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}_set(e){return h(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const o=this.key(),{[o]:i}=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),{[o]:i})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=p([e.Extends(U)],exports.ModelController),exports.CrudController=class extends exports.ModelController{create(){return{}}add(e){return h(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return h(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return h(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return h(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return h(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return h(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return h(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}},p([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationAdd"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"add",null),p([e.Get(),e.Middleware("auth"),e.Middleware("read"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"all",null),p([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"del",null),p([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"get",null),p([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationSet"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"set",null),p([g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),p([g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=p([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return I}create(){return{name:t.Validation.string().required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}}update(){return{name:t.Validation.string().empty(),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}}},exports.GroupsController=p([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return f}all(e,t){return h(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:C,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,r,o){return h(this,void 0,void 0,(function*(){const i=yield I.findByPk(r,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield f.destroy({where:{groupId:t}}),o){let e=0;for(let r=0;r<o.length;r++)e=yield C.count({where:{id:o[r]}}),e&&(yield f.create({groupId:t,routeId:o[r]}))}return e.success("OK")}if(t.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},p([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),g(0,e.Ctx()),g(1,e.Params("id")),y("design:type",Function),y("design:paramtypes",[e.Context,String]),y("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),p([e.Put("/:id/routes"),e.Middleware("auth"),e.Middleware("write","groups"),e.Middleware("validation",{routes:t.Validation.array(t.Validation.number().parse())}),g(0,e.Ctx()),g(1,e.Params("id")),g(2,e.Body("routes")),y("design:type",Function),y("design:paramtypes",[e.Context,String,Array]),y("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=p([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return O}all(e,t,r){return h(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"]]}})}))}},p([e.Get(),e.Middleware("auth"),e.Middleware("read"),g(0,e.Ctx()),g(1,e.Query("type")),g(2,e.Query("source")),y("design:type",Function),y("design:paramtypes",[e.Context,String,String]),y("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=p([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends U{register(e,r,i){return h(this,void 0,void 0,(function*(){yield t.sleep(m.API_SLEEP_REGISTRY);const{name:s,date:n,email:d,username:a,password:l,confirm:u}=r,p=a||d,g=c.SHA256(l).toString();if(yield S.count({where:{[o.Op.or]:[{email:d},{username:p}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=c.SHA256(u).toString())return e.error("Invalid password");const y=yield S.create({name:s,email:d,username:p,password:g,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const h=yield A.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"),e.close(),i.emit("register.user",{ctx:e,register:h,user:y}),this.emit("register.user",{ctx:e,register:h,user:y})}))}confirm(e,t,r){return h(this,void 0,void 0,(function*(){const o=yield A.findOne({where:{token:t,state:!0},include:[{model:S,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"),e.close(),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 h(this,void 0,void 0,(function*(){const i=t,s=yield A.findOne({where:{state:!0},include:[{model:S,required:!0,where:{[o.Op.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("User not found");e.success("OK"),e.close(),r.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})}))}getId(){return h(this,void 0,void 0,(function*(){const e=t.uuidv4();return(yield A.count({where:{token:e}}))?this.getId():e}))}},p([e.Post(),e.Middleware("validation",{name:t.Validation.string().required(),date:t.Validation.string().date().required(),email:t.Validation.string().email().required(),username:t.Validation.string().min(4).empty(),password:t.Validation.string().min(5).required(),confirm:t.Validation.string().min(5).required()}),g(0,e.Ctx()),g(1,e.Body()),g(2,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,Object,N]),y("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),p([e.Post("/confirm"),e.Middleware("validation",{token:t.Validation.string().required()}),g(0,e.Ctx()),g(1,e.Body("token")),g(2,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,N]),y("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),p([e.Post("/send"),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),g(0,e.Ctx()),g(1,e.Body("username")),g(2,e.App()),y("design:type",Function),y("design:paramtypes",[e.Context,String,N]),y("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=p([e.Controller("/register"),e.Extends(U)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return C}create(){return{name:t.Validation.string().required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}}update(){return{name:t.Validation.string().empty(),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}}},exports.RoutesController=p([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends U{setup(e){return h(this,void 0,void 0,(function*(){if(0==(yield S.count())){const e={description:"",state:!0},r=yield S.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),o=yield I.create(Object.assign({name:"admin"},e));yield E.create({userId:r.id,groupId:o.id});const i=["read","write"],s=["users","groups","routes"];yield t.forEachSeries(s,(r=>h(this,void 0,void 0,(function*(){yield t.forEachSeries(i,(t=>h(this,void 0,void 0,(function*(){const i=r+"."+t,s=yield C.create(Object.assign({name:i},e));yield f.create({groupId:o.id,routeId:s.id})}))))}))));const n=[...i,"delete","list","rename","upload"];yield t.forEachSeries(n,(t=>h(this,void 0,void 0,(function*(){const r="files_api."+t,i=yield C.create(Object.assign({name:r},e));yield f.create({groupId:o.id,routeId:i.id})}))));const d=yield C.create(Object.assign({name:"logs.read"},e));yield f.create({groupId:o.id,routeId:d.id})}e.success("OK")}))}},p([e.Get(),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=p([e.Controller("/setup"),e.Extends(U)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return S}constructor(){super(),this.dir=m.API_HTTP_PUBLIC+"/avatar",m.API_HTTP_PUBLIC&&n.existsSync(m.API_HTTP_PUBLIC)&&!n.existsSync(this.dir)&&n.mkdirSync(this.dir)}avatar(e,r){return h(this,void 0,void 0,(function*(){if(t.isArray(e.req.files)&&e.req.files.length){const t=e.req.files[0].filename||"";if(t){const o=m.API_HTTP_PUBLIC+"/avatar/";if(n.existsSync(o+r.avatar)&&n.lstatSync(o+r.avatar).isFile()&&n.rmSync(o+r.avatar),r.avatar=t,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,o){return h(this,void 0,void 0,(function*(){const i=yield S.scope("password").findOne({where:{id:o.id,password:c.SHA256(t).toString(),state:!0}}).catch(this.error);return i?(i.password=c.SHA256(r).toString(),(yield i.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return h(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:c.SHA256(t).toString()}})}))}all(e){return h(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return h(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return h(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return h(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:t?{password:c.SHA256(t).toString()}:{}})}))}},p([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:20}))),g(0,e.Ctx()),g(1,j()),y("design:type",Function),y("design:paramtypes",[e.Context,S]),y("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),p([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:t.Validation.string().min(5).required(),newPassword:t.Validation.string().min(5).required()}),g(0,e.Ctx()),g(1,e.Body("oldPassword")),g(2,e.Body("newPassword")),g(3,j()),y("design:type",Function),y("design:paramtypes",[e.Context,String,String,S]),y("design:returntype",Promise)],exports.UsersController.prototype,"password",null),p([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:t.Validation.string().required(),email:t.Validation.string().email().required(),username:t.Validation.string().min(4).required(),password:t.Validation.string().min(5).required(),description:t.Validation.string().empty(""),state:t.Validation.boolean().parse().required()}),g(0,e.Ctx()),g(1,e.Body("password")),y("design:type",Function),y("design:paramtypes",[e.Context,String]),y("design:returntype",Promise)],exports.UsersController.prototype,"add",null),p([e.Get(),e.Middleware("auth"),e.Middleware("read"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"all",null),p([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),g(0,e.Ctx()),g(1,j()),g(2,e.Params("id")),y("design:type",Function),y("design:paramtypes",[e.Context,S,String]),y("design:returntype",Promise)],exports.UsersController.prototype,"del",null),p([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),g(0,e.Ctx()),y("design:type",Function),y("design:paramtypes",[e.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"get",null),p([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:t.Validation.string().empty(),email:t.Validation.string().email().empty(),username:t.Validation.string().min(4).empty(),password:t.Validation.string().min(5).empty().filter(""),description:t.Validation.string().empty(),state:t.Validation.boolean().parse().empty()}),g(0,e.Ctx()),g(1,e.Body("password")),y("design:type",Function),y("design:paramtypes",[e.Context,String]),y("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=p([e.Controller("/users"),e.Extends(exports.ModelController),y("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return E}all(e,t){return h(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:I,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,r,o){return h(this,void 0,void 0,(function*(){const i=yield S.findByPk(r,{attributes:["id"]}).catch(this.error);if(i){if(yield E.destroy({where:{userId:i.id}}),o){let e=0;for(let t=0;t<o.length;t++)e=yield I.count({where:{id:o[t]}}),e&&(yield E.create({userId:i.id,groupId:o[t]}))}return e.success("OK")}if(t.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},p([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),g(0,e.Ctx()),g(1,e.Params("id")),y("design:type",Function),y("design:paramtypes",[e.Context,String]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),p([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("write","users"),e.Middleware("validation",{groups:t.Validation.array(t.Validation.number().parse())}),g(0,e.Ctx()),g(1,e.Params("id")),g(2,e.Body("groups")),y("design:type",Function),y("design:paramtypes",[e.Context,String,Array]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=p([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=N,exports.Auth=v,exports.Config=B,exports.Configs=T,exports.ControllerBase=U,exports.Database=_,exports.Env=m,exports.Forgot=P,exports.Group=I,exports.GroupRoute=f,exports.Log=O,exports.Logs=R,exports.Permission=G,exports.Register=A,exports.ReqAuth=L,exports.ReqFiles=k,exports.ReqUser=j,exports.Route=C,exports.Session=w,exports.Token=F,exports.User=S,exports.UserGroup=E,exports.crt=M,exports.key=b,exports.sequelize=x;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.1.
|
|
2
|
+
* @andrewcaires/api v3.1.2
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
7
|
import { Context, IStore, Application as Application$1 } from '@andrewcaires/express';
|
|
8
8
|
import WebSocket from 'ws';
|
|
9
|
-
import { TypeObjectAny, EventEmitter,
|
|
9
|
+
import { TypeObjectAny, EventEmitter, TypeObject, ValidationBase, TypeObjectString } from '@andrewcaires/utils.js';
|
|
10
10
|
import { Model, CreateOptions, Attributes, FindOptions, UpdateOptions, ModelStatic, Sequelize, WhereOptions } from 'sequelize';
|
|
11
11
|
|
|
12
12
|
declare class Route extends Model {
|
|
@@ -154,29 +154,19 @@ interface IUploadOptions {
|
|
|
154
154
|
types?: Array<string>;
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
-
declare enum LogsColor {
|
|
158
|
-
ERROR = "\u001B[31m",
|
|
159
|
-
INFO = "\u001B[36m",
|
|
160
|
-
NONE = "\u001B[37m",
|
|
161
|
-
SUCCESS = "\u001B[32m",
|
|
162
|
-
WARNING = "\u001B[33m"
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
type LogsTypes = "error" | "info" | "success" | "warning" | "";
|
|
166
|
-
|
|
167
157
|
declare abstract class ControllerBase extends EventEmitter {
|
|
168
158
|
private _uploads;
|
|
169
|
-
auth(ctx: Context, token: string, useragent: string
|
|
170
|
-
session(useragent: string, store: IStore
|
|
159
|
+
auth(ctx: Context, token: string, useragent: string): Promise<void>;
|
|
160
|
+
session(ctx: Context, useragent: string, store: IStore): Promise<void>;
|
|
171
161
|
error(error: any): void;
|
|
172
162
|
name(): string;
|
|
173
|
-
permission(ctx: Context,
|
|
174
|
-
read(ctx: Context,
|
|
175
|
-
upload(ctx: Context,
|
|
163
|
+
permission(ctx: Context, name: string, user: User): Promise<void>;
|
|
164
|
+
read(ctx: Context, name: string, user: User): Promise<void>;
|
|
165
|
+
upload(ctx: Context, options: IUploadOptions): void;
|
|
176
166
|
private uploadFile;
|
|
177
167
|
private uploadMiddleware;
|
|
178
|
-
validation(ctx: Context,
|
|
179
|
-
write(ctx: Context,
|
|
168
|
+
validation(ctx: Context, options: TypeObject<ValidationBase>): Promise<void>;
|
|
169
|
+
write(ctx: Context, name: string, user: User): Promise<void>;
|
|
180
170
|
}
|
|
181
171
|
|
|
182
172
|
declare class Application extends Application$1 {
|
|
@@ -206,7 +196,7 @@ declare class AuthController extends ControllerBase {
|
|
|
206
196
|
declare class FilesController extends ControllerBase {
|
|
207
197
|
directory(): string;
|
|
208
198
|
files(ctx: Context): Promise<TypeObjectAny>;
|
|
209
|
-
access(ctx: Context,
|
|
199
|
+
access(ctx: Context, name: string, user: User): Promise<void>;
|
|
210
200
|
private info;
|
|
211
201
|
}
|
|
212
202
|
|
|
@@ -239,8 +229,8 @@ declare abstract class CrudController<M extends Model<M>> extends ModelControlle
|
|
|
239
229
|
get(ctx: Context): Promise<void>;
|
|
240
230
|
set(ctx: Context): Promise<void>;
|
|
241
231
|
update(): TypeObject<ValidationBase>;
|
|
242
|
-
validationAdd(ctx: Context
|
|
243
|
-
validationSet(ctx: Context
|
|
232
|
+
validationAdd(ctx: Context): Promise<void>;
|
|
233
|
+
validationSet(ctx: Context): Promise<void>;
|
|
244
234
|
}
|
|
245
235
|
|
|
246
236
|
declare class GroupsController extends CrudController<Group> {
|
|
@@ -367,7 +357,6 @@ declare class Logs {
|
|
|
367
357
|
static info(message: string, source?: string, console?: boolean): Promise<void>;
|
|
368
358
|
static success(message: string, source?: string, console?: boolean): Promise<void>;
|
|
369
359
|
static warning(message: string, source?: string, console?: boolean): Promise<void>;
|
|
370
|
-
private static writeConsole;
|
|
371
360
|
private static writeRaw;
|
|
372
361
|
}
|
|
373
362
|
|
|
@@ -396,4 +385,4 @@ declare class Token {
|
|
|
396
385
|
private static verify;
|
|
397
386
|
}
|
|
398
387
|
|
|
399
|
-
export { Application, type ArgumentsModelAdd, type ArgumentsModelAll, type ArgumentsModelDel, type ArgumentsModelGet, type ArgumentsModelSet, Auth, AuthController, type CallbackModelAll, type CallbackModelGet, Config, Configs, ControllerBase, CrudController, Database, Env, FilesController, Forgot, ForgotController, Group, GroupRoute, GroupsController, GroupsRoutesController, type IDatabaseOptions, type ITokenParameters, type IUploadOptions, Log, Logs,
|
|
388
|
+
export { Application, type ArgumentsModelAdd, type ArgumentsModelAll, type ArgumentsModelDel, type ArgumentsModelGet, type ArgumentsModelSet, Auth, AuthController, type CallbackModelAll, type CallbackModelGet, Config, Configs, ControllerBase, CrudController, Database, Env, FilesController, Forgot, ForgotController, Group, GroupRoute, GroupsController, GroupsRoutesController, type IDatabaseOptions, type ITokenParameters, type IUploadOptions, Log, Logs, LogsController, ModelController, Permission, Register, RegisterController, ReqAuth, ReqFiles, ReqUser, Route, RoutesController, Session, SetupController, Token, User, UserGroup, UsersController, UsersGroupsController, crt, key, sequelize };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.1.
|
|
2
|
+
* @andrewcaires/api v3.1.2
|
|
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,Next as n,Session as s,Argument as o,Context as d,Post as a,Middleware as u,Body as c,App as l,Get as p,Controller as g,Extends as h,Status as m,Delete as y,Put as _,Params as f,Query as v}from"@andrewcaires/express";import{toBool as I,parseMs as P,dateFormat as A,noop as E,loop as O,uuidv4 as S,sleep as T,toArray as w,EventEmitter as R,cache as N,Validation as b,isDef as F,uniqueID as D,isArray as x,isString as q,isNull as B,forEachSeries as k}from"@andrewcaires/utils.js";import L from"ws";import{Sequelize as C,DataTypes as j,Model as K,Op as H}from"sequelize";import{config as M}from"dotenv";import{existsSync as U,readFileSync as G,statSync as z,readdirSync as X,mkdirSync as Y,lstatSync as W,rmSync as Z}from"fs";import{Store as J}from"express-session";import{verify as $,sign as V}from"jsonwebtoken";import Q from"multer";import{join as ee}from"path";import{SHA256 as te}from"crypto-js";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,M();class oe{static getBool(e,t){return I(oe.getString(e,t.toString()))}static getInt(e,t){return parseInt(oe.getString(e,t.toString()))}static getMs(e,t){return P(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_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=process.env.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 C(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 C("sqlite::memory:",{logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_mysql(e){return new C(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 C(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 C({dialect:"sqlite",storage:e.database,logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}}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 K{}ue.init({secret:j.STRING,logout:j.DATE,useragent:j.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends K{}ce.init({token:j.STRING,timestamp:j.BIGINT,state:j.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends K{}le.init({name:j.STRING,description:j.TEXT,state:j.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class pe extends K{}pe.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),pe.removeAttribute("id");class ge extends K{}ge.init({token:j.STRING,state:j.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends K{}he.init({name:j.STRING,description:j.TEXT,state:j.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class me extends K{}me.init({name:j.STRING,email:j.STRING,username:j.STRING,password:j.STRING,avatar:j.STRING,date:j.DATEONLY,description:j.TEXT,state:j.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class ye extends K{}ye.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),ye.removeAttribute("id");class _e extends K{}_e.init({key:j.STRING,value:j.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),_e.removeAttribute("id");class fe extends K{}fe.init({type:j.STRING,source:j.STRING,message:j.TEXT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class ve extends K{}var Ie;ve.init({session:j.STRING,json:j.TEXT,expired:j.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),function(e){e.ERROR="[31m",e.INFO="[36m",e.NONE="[37m",e.SUCCESS="[32m",e.WARNING="[33m"}(Ie||(Ie={}));class Pe{static write(e,t,r){return se(this,void 0,void 0,(function*(){yield Pe.writeRaw(Ie.NONE,"",e,t,r)}))}static error(e,t,r){return se(this,void 0,void 0,(function*(){yield Pe.writeRaw(Ie.ERROR,"error",e,t,r)}))}static info(e,t,r){return se(this,void 0,void 0,(function*(){yield Pe.writeRaw(Ie.INFO,"info",e,t,r)}))}static success(e,t,r){return se(this,void 0,void 0,(function*(){yield Pe.writeRaw(Ie.ERROR,"success",e,t,r)}))}static warning(e,t,r){return se(this,void 0,void 0,(function*(){yield Pe.writeRaw(Ie.WARNING,"warning",e,t,r)}))}static writeConsole(e,t,r){const i=A(new Date,"%H:%M:%S");console.log(">",e,t+" ".repeat(10-t.length),"[37m","|",i,"|",r)}static writeRaw(e,t,r,i,n){return se(this,void 0,void 0,(function*(){n&&Pe.writeConsole(e,t,r),ae&&(yield fe.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Ae=e=>U(e)?G(e):void 0,Ee={http:Ae(oe.API_HTTP_CRT),token:Ae(oe.API_TOKEN_CRT)},Oe={http:Ae(oe.API_HTTP_KEY),token:Ae(oe.API_TOKEN_KEY)};class Se extends J{constructor(){super(),this.all=e=>se(this,void 0,void 0,(function*(){e=e||E;const t=yield ve.findAll({attributes:["session"],where:{expired:{[H.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(E),e&&e()})),this.destroy=(e,t)=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{session:e}}).catch(E),t&&t()})),this.expired=()=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{expired:{[H.lt]:Date.now()}}}).catch(E)})),this.get=(e,t)=>se(this,void 0,void 0,(function*(){t=t||E;const r=yield ve.findOne({where:{session:e,expired:{[H.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(E),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(E))||0)})),this.set=(e,t,r)=>se(this,void 0,void 0,(function*(){r=r||E;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(E))||[];s&&(o||(s.json=n,s.expired=i,yield s.save().catch(E))),r()})),this.loop=O(this.expired,3e4),this.loop.start()}}class Te{static create(e){return se(this,void 0,void 0,(function*(){if(!Oe.token)return{error:"Key not found"};const{id:t}=e,r=S(),i=yield ue.create({secret:r,userId:t}).catch(Te.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:V({id:t,secret:r},Oe.token,Te.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){Pe.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(!Oe.token)return{error:"Key not found"};const{error:t,decode:r}=Te.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(Te.error);if(r){const i=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Te.error);if(i&&!i.logout){i.secret=S(),yield i.save().catch(Te.error);return{auth:i,token:V({id:e,secret:i.secret},Oe.token,Te.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return se(this,void 0,void 0,(function*(){const{error:t,decode:r}=Te.verify(e);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(Te.error);if(r){const e=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Te.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ee.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:$(e,Ee.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class we extends e{constructor(e){super(e,{cert:Ee.http,cross:oe.API_HTTP_CROSS,hybrid:oe.API_HTTP_HYBRID,key:Oe.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 Se,name:oe.API_SESSION_NAME,secret:oe.API_SESSION_SECRET,cookie:{maxAge:oe.API_SESSION_LIFETIME},genid:S}})}error(e,t){Pe.info(e.message,t,oe.API_CONSOLE_ERROR)}log(e,t){Pe.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 L.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 Te.user(n.toString());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 T(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class Re{static all(){return se(this,void 0,void 0,(function*(){const e=yield _e.findAll().catch(Re.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(Re.error))||0)>0}))}static error(e){Pe.error(e.message,"api.config",oe.API_CONSOLE_ERROR)}static get(e,t=""){return se(this,void 0,void 0,(function*(){const r=yield _e.findOne({where:{key:e}}).catch(Re.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(Re.error))||[];r&&(r.value=t,yield r.save().catch(Re.error))}))}}const Ne=t((({req:e})=>e.auth)),be=t((({req:e})=>w(e.files))),Fe=t((({req:e})=>e.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=>{Pe.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 xe extends R{constructor(){super(...arguments),this._uploads=N()}auth(e,t,r,i){return se(this,void 0,void 0,(function*(){const{auth:n,error:s,user:o}=yield Te.user(t);return s?e.error(s):n&&o?n.useragent!=r?e.error("Invalid token"):(e.req.auth=n,e.req.user=o,void i()):e.error("Internal Server Error")}))}session(e,t,r){return se(this,void 0,void 0,(function*(){t.auth&&t.user&&(t.useragent?t.useragent!=e&&t.regenerate(E):(t.useragent=e,t.save(E))),r()}))}error(e){Pe.error(e.message,"api.controller",oe.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r,i){return se(this,void 0,void 0,(function*(){if(!i)return e.unauthorized("Access denied");(yield De.is(i,r))?t():e.unauthorized("Access denied")}))}read(e,t,r,i){return se(this,void 0,void 0,(function*(){yield this.permission(e,t,(r||this.name())+".read",i)}))}upload(e,t,r){const i=this._uploads(r);i.upload||(i.upload=this.uploadMiddleware(r)),i.upload(e.req,e.res,(r=>{var i;if(r)return e.error(r.message),void(null===(i=e.res.socket)||void 0===i||i.destroy(r));t()}))}uploadFile(e,t){const r=S()+"."+t;return U(ee(e,r))?this.uploadFile(e,t):r}uploadMiddleware(e){const t=(null==e?void 0:e.path)||oe.API_UPLOAD_TEMP,r=Q.diskStorage({destination:(e,r,i)=>i(null,t),filename:(e,r,i)=>se(this,void 0,void 0,(function*(){return i(null,this.uploadFile(t,r.originalname.split(".").pop()||"bin"))}))}),i=(null==e?void 0:e.types)||[],n=Q({storage:r,fileFilter(e,t,r){return se(this,void 0,void 0,(function*(){if(i.length){const e=t.originalname.split(".").pop()||"bin";return-1!=i.indexOf(t.mimetype)||-1!=i.indexOf(e)?r(null,!0):r(new Error("File not allowed"))}return r(null,!0)}))},limits:{fileSize:1e6*((null==e?void 0:e.size)||oe.API_UPLOAD_SIZE)}});return n.array((null==e?void 0:e.field)||oe.API_UPLOAD_FIELD,(null==e?void 0:e.count)||oe.API_UPLOAD_COUNT)}validation(e,t,r){return se(this,void 0,void 0,(function*(){const{error:i,value:n}=yield b.object(r).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=n,t()}))}write(e,t,r,i){return se(this,void 0,void 0,(function*(){yield this.permission(e,t,(r||this.name())+".write",i)}))}}re([ie(0,r()),ie(1,i(oe.API_TOKEN_HEADER)),ie(2,i("user-agent")),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[d,String,String,Function]),ne("design:returntype",Promise)],xe.prototype,"auth",null),re([ie(0,i("user-agent")),ie(1,s()),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[String,Object,Function]),ne("design:returntype",Promise)],xe.prototype,"session",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ie(3,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,Function,String,me]),ne("design:returntype",Promise)],xe.prototype,"permission",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ie(3,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,Function,String,me]),ne("design:returntype",Promise)],xe.prototype,"read",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ne("design:type",Function),ne("design:paramtypes",[d,Function,Object]),ne("design:returntype",void 0)],xe.prototype,"upload",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ne("design:type",Function),ne("design:paramtypes",[d,Function,Object]),ne("design:returntype",Promise)],xe.prototype,"validation",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ie(3,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,Function,String,me]),ne("design:returntype",Promise)],xe.prototype,"write",null);let qe=class extends xe{login(e,t,r,i,n){return se(this,void 0,void 0,(function*(){yield T(oe.API_SLEEP_AUTH);const s=r,o=yield me.findOne({where:{[H.or]:[{email:s},{username:r}],[H.and]:[{password:te(i).toString()}]}}).catch(this.error);if(!o)return e.notFound("Invalid username or password"),e.destroy(),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"),e.destroy(),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"),e.destroy(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const{auth:a,error:u,token:c}=yield Te.create(o);return u?(e.error(u),e.destroy(),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.data({token:c}),e.destroy(),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"),e.destroy(),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 Te.destroy(t))return e.success("Disconcerted"),e.destroy(),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 Te.renew(r);return s?e.error(s):n?(n.useragent=t,yield n.save().catch(this.error),e.data({token:o}),e.destroy(),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.data(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};re([a("/login"),u("validation",{username:b.string().min(3).required(),password:b.string().min(5).required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,c("username")),ie(3,c("password")),ie(4,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,String,String,we]),ne("design:returntype",Promise)],qe.prototype,"login",null),re([p("/logout"),u("auth"),ie(0,r()),ie(1,Ne()),ie(2,Fe()),ie(3,l()),ne("design:type",Function),ne("design:paramtypes",[d,ue,me,we]),ne("design:returntype",Promise)],qe.prototype,"logout",null),re([a("/renew"),u("validation",{token:b.string().required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,c("token")),ie(3,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,String,we]),ne("design:returntype",Promise)],qe.prototype,"renew",null),re([p(),u("auth"),ie(0,r()),ie(1,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,me]),ne("design:returntype",Promise)],qe.prototype,"user",null),qe=re([g("/auth"),h(xe)],qe);let Be=class extends xe{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=ee(this.directory(),t);if(!U(r)||!z(r).isDirectory())return e.status(m.NOT_FOUND),{message:"Path not Found"};let i=[];return i=X(r),i=i.map((e=>this.info(ee(r,e)))),i=i.filter(F),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r,i){return se(this,void 0,void 0,(function*(){yield this.permission(e,t,"files_"+this.name()+"."+r,i)}))}info(e){if(!U(e))return null;const t=z(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()}}};re([p("/path/?*"),u("auth"),u("access","list"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Be.prototype,"files",null),re([ie(0,r()),ie(1,n()),ie(2,o()),ie(3,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,Function,String,me]),ne("design:returntype",Promise)],Be.prototype,"access",null),Be=re([g("/files"),h(xe)],Be);let ke=class extends xe{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=D(),yield r.save(),e.data({token:r.token})}))}forgot(e,t,r){return se(this,void 0,void 0,(function*(){yield T(oe.API_SLEEP_FORGOT);const i=t,n=yield me.findOne({where:{[H.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=D(),o=Date.now()+6e4*oe.API_TOKEN_FORGOT,d=yield ce.create({token:s,timestamp:o,state:!0,userId:n.id});e.success("OK"),e.destroy(),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=te(r).toString(),yield n.user.save().catch(this.error),e.success("OK"),e.destroy(),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"),u("validation",{token:b.string().required()}),ie(0,r()),ie(1,c("token")),ne("design:type",Function),ne("design:paramtypes",[d,String]),ne("design:returntype",Promise)],ke.prototype,"check",null),re([a(),u("validation",{username:b.string().min(4).required()}),ie(0,r()),ie(1,c("username")),ie(2,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,we]),ne("design:returntype",Promise)],ke.prototype,"forgot",null),re([a("/reset"),u("validation",{token:b.string().required(),password:b.string().min(5).required()}),ie(0,r()),ie(1,c("token")),ie(2,c("password")),ie(3,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,String,we]),ne("design:returntype",Promise)],ke.prototype,"reset",null),ke=re([g("/forgot"),h(xe)],ke);let Le=class extends xe{constructor(){super(...arguments),this._columns=[]}_add({ctx:e,options:t,body:r}){return se(this,void 0,void 0,(function*(){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.data({[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all({ctx:e,options:t,callback:r}){var i,n,s,o,d;return se(this,void 0,void 0,(function*(){const a=this.model(),u=Object.assign({},t||{});u.where=Object.assign({},u.where||{});const c=null===(i=e.req.query.limit)||void 0===i?void 0:i.toString();c&&(u.limit=parseInt(c));const l=null===(n=e.req.query.offset)||void 0===n?void 0:n.toString();l&&(u.offset=parseInt(l));const p=this.columns(),g=[],h=null===(s=e.req.query.asc)||void 0===s?void 0:s.toString();h&&h.length&&h.split(",").forEach((e=>{p.indexOf(e)>=0&&g.push([e,"ASC"])}));const m=null===(o=e.req.query.desc)||void 0===o?void 0:o.toString();m&&m.length&&m.split(",").forEach((e=>{p.indexOf(e)>=0&&g.push([e,"DESC"])})),g.length&&(u.order=g);const y=[],_=x(u.attributes)?u.attributes:p,f=null===(d=e.req.query.search)||void 0===d?void 0:d.toString();_.forEach((t=>{var r;if(q(t)&&(f&&f.length&&y.push({[t]:{[H.like]:`%${f}%`}}),"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&&y.push({[t]:{[H.like]:`%${i}%`}})}})),y.length&&(u.where=Object.assign(Object.assign({},u.where),{[H.or]:[...y]}));const v=(yield a.count(Object.assign(Object.assign({},u),{col:p[0]})).catch(this.error))||0,I=yield a.findAll(u).catch(this.error);return I?(e.data({count:v,records:r?yield r(I):I}),[I,v]):(e.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del({ctx:e,options:t}){return se(this,void 0,void 0,(function*(){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?Pe.error(e.message+"\n"+e.sql,"api.controller.sql",oe.API_CONSOLE_ERROR):super.error(e)}_get({ctx:e,options:t,callback:r}){return se(this,void 0,void 0,(function*(){const i=this.key(),{[i]:n}=e.req.params,s=yield this.model().findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:n})})).catch(this.error);if(s)return e.data(r?yield r(s):s.toJSON()),s;null!==s?e.error("Internal Server Error"):e.notFound("Record not found")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}_set({ctx:e,options:t,body:r}){return se(this,void 0,void 0,(function*(){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)}))}};Le=re([h(xe)],Le);let Ce=class extends Le{create(){return{}}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})}))}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,t){return se(this,void 0,void 0,(function*(){yield this.validation(e,t,this.create())}))}validationSet(e,t){return se(this,void 0,void 0,(function*(){yield this.validation(e,t,this.update())}))}};re([a(),u("auth"),u("write"),u("validationAdd"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ce.prototype,"add",null),re([p(),u("auth"),u("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ce.prototype,"all",null),re([y("/:id"),u("auth"),u("write"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ce.prototype,"del",null),re([p("/:id"),u("auth"),u("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ce.prototype,"get",null),re([_("/:id"),u("auth"),u("write"),u("validationSet"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ce.prototype,"set",null),re([ie(0,r()),ie(1,n()),ne("design:type",Function),ne("design:paramtypes",[d,Function]),ne("design:returntype",Promise)],Ce.prototype,"validationAdd",null),re([ie(0,r()),ie(1,n()),ne("design:type",Function),ne("design:paramtypes",[d,Function]),ne("design:returntype",Promise)],Ce.prototype,"validationSet",null),Ce=re([h(Le)],Ce);let je=class extends Ce{model(){return le}create(){return{name:b.string().required(),description:b.string().empty(""),state:b.boolean().parse().required()}}update(){return{name:b.string().empty(),description:b.string().empty(),state:b.boolean().parse().empty()}}};je=re([g("/groups"),h(Ce)],je);let Ke=class extends Le{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"),u("auth"),u("read","groups"),ie(0,r()),ie(1,f("id")),ne("design:type",Function),ne("design:paramtypes",[d,String]),ne("design:returntype",Promise)],Ke.prototype,"all",null),re([_("/:id/routes"),u("auth"),u("write","groups"),u("validation",{routes:b.array(b.number().parse())}),ie(0,r()),ie(1,f("id")),ie(2,c("routes")),ne("design:type",Function),ne("design:paramtypes",[d,String,Array]),ne("design:returntype",Promise)],Ke.prototype,"set",null),Ke=re([g("/groups"),h(Le)],Ke);let He=class extends Le{model(){return fe}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(),u("auth"),u("read"),ie(0,r()),ie(1,v("type")),ie(2,v("source")),ne("design:type",Function),ne("design:paramtypes",[d,String,String]),ne("design:returntype",Promise)],He.prototype,"all",null),He=re([g("/logs"),h(Le)],He);let Me=class extends xe{register(e,t,r){return se(this,void 0,void 0,(function*(){yield T(oe.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=te(d).toString();if(yield me.count({where:{[H.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=te(a).toString())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"),e.destroy(),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"),e.destroy(),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:{[H.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),e.destroy(),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=S();return(yield ge.count({where:{token:e}}))?this.getId():e}))}};re([a(),u("validation",{name:b.string().required(),date:b.string().date().required(),email:b.string().email().required(),username:b.string().min(4).empty(),password:b.string().min(5).required(),confirm:b.string().min(5).required()}),ie(0,r()),ie(1,c()),ie(2,l()),ne("design:type",Function),ne("design:paramtypes",[d,Object,we]),ne("design:returntype",Promise)],Me.prototype,"register",null),re([a("/confirm"),u("validation",{token:b.string().required()}),ie(0,r()),ie(1,c("token")),ie(2,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,we]),ne("design:returntype",Promise)],Me.prototype,"confirm",null),re([a("/send"),u("validation",{username:b.string().min(4).required()}),ie(0,r()),ie(1,c("username")),ie(2,l()),ne("design:type",Function),ne("design:paramtypes",[d,String,we]),ne("design:returntype",Promise)],Me.prototype,"send",null),Me=re([g("/register"),h(xe)],Me);let Ue=class extends Ce{model(){return he}create(){return{name:b.string().required(),description:b.string().empty(""),state:b.boolean().parse().required()}}update(){return{name:b.string().empty(),description:b.string().empty(),state:b.boolean().parse().empty()}}};Ue=re([g("/routes"),h(Ce)],Ue);let Ge=class extends xe{setup(e){return se(this,void 0,void 0,(function*(){if(0==(yield me.count())){const e={description:"",state:!0},t=yield me.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),r=yield le.create(Object.assign({name:"admin"},e));yield ye.create({userId:t.id,groupId:r.id});const i=["read","write"],n=["users","groups","routes"];yield k(n,(t=>se(this,void 0,void 0,(function*(){yield k(i,(i=>se(this,void 0,void 0,(function*(){const n=t+"."+i,s=yield he.create(Object.assign({name:n},e));yield pe.create({groupId:r.id,routeId:s.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield k(s,(t=>se(this,void 0,void 0,(function*(){const i="files_api."+t,n=yield he.create(Object.assign({name:i},e));yield pe.create({groupId:r.id,routeId:n.id})}))));const o=yield he.create(Object.assign({name:"logs.read"},e));yield pe.create({groupId:r.id,routeId:o.id})}e.success("OK")}))}};re([p(),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],Ge.prototype,"setup",null),Ge=re([g("/setup"),h(xe)],Ge);let ze=class extends Le{model(){return me}constructor(){super(),this.dir=oe.API_HTTP_PUBLIC+"/avatar",oe.API_HTTP_PUBLIC&&U(oe.API_HTTP_PUBLIC)&&!U(this.dir)&&Y(this.dir)}avatar(e,t){return se(this,void 0,void 0,(function*(){if(x(e.req.files)&&e.req.files.length){const r=e.req.files[0].filename||"";if(r){const i=oe.API_HTTP_PUBLIC+"/avatar/";if(U(i+t.avatar)&&W(i+t.avatar).isFile()&&Z(i+t.avatar),t.avatar=r,yield t.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,i){return se(this,void 0,void 0,(function*(){const n=yield me.scope("password").findOne({where:{id:i.id,password:te(t).toString(),state:!0}}).catch(this.error);return n?(n.password=te(r).toString(),(yield n.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return se(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:te(t).toString()}})}))}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*(){yield this._set({ctx:e,body:t?{password:te(t).toString()}:{}})}))}};re([a("/avatar"),u("auth"),u("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:20}))),ie(0,r()),ie(1,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,me]),ne("design:returntype",Promise)],ze.prototype,"avatar",null),re([a("/password"),u("auth"),u("validation",{oldPassword:b.string().min(5).required(),newPassword:b.string().min(5).required()}),ie(0,r()),ie(1,c("oldPassword")),ie(2,c("newPassword")),ie(3,Fe()),ne("design:type",Function),ne("design:paramtypes",[d,String,String,me]),ne("design:returntype",Promise)],ze.prototype,"password",null),re([a(),u("auth"),u("write"),u("validation",{name:b.string().required(),email:b.string().email().required(),username:b.string().min(4).required(),password:b.string().min(5).required(),description:b.string().empty(""),state:b.boolean().parse().required()}),ie(0,r()),ie(1,c("password")),ne("design:type",Function),ne("design:paramtypes",[d,String]),ne("design:returntype",Promise)],ze.prototype,"add",null),re([p(),u("auth"),u("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],ze.prototype,"all",null),re([y("/:id"),u("auth"),u("write"),ie(0,r()),ie(1,Fe()),ie(2,f("id")),ne("design:type",Function),ne("design:paramtypes",[d,me,String]),ne("design:returntype",Promise)],ze.prototype,"del",null),re([p("/:id"),u("auth"),u("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[d]),ne("design:returntype",Promise)],ze.prototype,"get",null),re([_("/:id"),u("auth"),u("write"),u("validation",{name:b.string().empty(),email:b.string().email().empty(),username:b.string().min(4).empty(),password:b.string().min(5).empty().filter(""),description:b.string().empty(),state:b.boolean().parse().empty()}),ie(0,r()),ie(1,c("password")),ne("design:type",Function),ne("design:paramtypes",[d,String]),ne("design:returntype",Promise)],ze.prototype,"set",null),ze=re([g("/users"),h(Le),ne("design:paramtypes",[])],ze);let Xe=class extends Le{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"),u("auth"),u("read","users"),ie(0,r()),ie(1,f("id")),ne("design:type",Function),ne("design:paramtypes",[d,String]),ne("design:returntype",Promise)],Xe.prototype,"all",null),re([_("/:id/groups"),u("auth"),u("write","users"),u("validation",{groups:b.array(b.number().parse())}),ie(0,r()),ie(1,f("id")),ie(2,c("groups")),ne("design:type",Function),ne("design:paramtypes",[d,String,Array]),ne("design:returntype",Promise)],Xe.prototype,"set",null),Xe=re([g("/users"),h(Le)],Xe);export{we as Application,ue as Auth,qe as AuthController,Re as Config,_e as Configs,xe as ControllerBase,Ce as CrudController,de as Database,oe as Env,Be as FilesController,ce as Forgot,ke as ForgotController,le as Group,pe as GroupRoute,je as GroupsController,Ke as GroupsRoutesController,fe as Log,Pe as Logs,Ie as LogsColor,He as LogsController,Le as ModelController,De as Permission,ge as Register,Me as RegisterController,Ne as ReqAuth,be as ReqFiles,Fe as ReqUser,he as Route,Ue as RoutesController,ve as Session,Ge as SetupController,Te as Token,me as User,ye as UserGroup,ze as UsersController,Xe as UsersGroupsController,Ee as crt,Oe as key,ae as sequelize};
|
|
7
|
+
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,Session as n,Argument as s,Context as o,Post as d,Middleware as a,Body as u,App as c,Get as l,Controller as p,Extends as g,Status as h,Delete as m,Put as y,Params as _,Query as f}from"@andrewcaires/express";import{toBool as I,parseMs as v,noop as P,loop as A,uuidv4 as E,sleep as S,toArray as O,EventEmitter as T,cache as w,Validation as R,isDef as b,uniqueID as N,isArray as D,isString as x,isNull as F,forEachSeries as q}from"@andrewcaires/utils.js";import B from"ws";import{Sequelize as k,DataTypes as L,Model as j,Op as C}from"sequelize";import{config as K}from"dotenv";import{LogColor as H,Log as M}from"@andrewcaires/node";import{existsSync as U,readFileSync as G,statSync as z,readdirSync as X,mkdirSync as Y,lstatSync as W,rmSync as Z}from"fs";import{Store as J}from"express-session";import{verify as $,sign as V}from"jsonwebtoken";import Q from"multer";import{join as ee}from"path";import{SHA256 as te}from"crypto-js";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,K();class oe{static getBool(e,t){return I(oe.getString(e,t.toString()))}static getInt(e,t){return parseInt(oe.getString(e,t.toString()))}static getMs(e,t){return v(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_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=process.env.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 k(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 k("sqlite::memory:",{logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_mysql(e){return new k(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 k(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 k({dialect:"sqlite",storage:e.database,logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}}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 j{}ue.init({secret:L.STRING,logout:L.DATE,useragent:L.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends j{}ce.init({token:L.STRING,timestamp:L.BIGINT,state:L.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends j{}le.init({name:L.STRING,description:L.TEXT,state:L.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class pe extends j{}pe.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),pe.removeAttribute("id");class ge extends j{}ge.init({token:L.STRING,state:L.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends j{}he.init({name:L.STRING,description:L.TEXT,state:L.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class me extends j{}me.init({name:L.STRING,email:L.STRING,username:L.STRING,password:L.STRING,avatar:L.STRING,date:L.DATEONLY,description:L.TEXT,state:L.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class ye extends j{}ye.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),ye.removeAttribute("id");class _e extends j{}_e.init({key:L.STRING,value:L.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),_e.removeAttribute("id");class fe extends j{}fe.init({type:L.STRING,source:L.STRING,message:L.TEXT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class Ie extends j{}Ie.init({session:L.STRING,json:L.TEXT,expired:L.BIGINT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),Ie.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 ve{static write(e,t,r){return se(this,void 0,void 0,(function*(){yield ve.writeRaw(H.White,"",e,t,r)}))}static error(e,t,r){return se(this,void 0,void 0,(function*(){yield ve.writeRaw(H.Red,"error",e,t,r)}))}static info(e,t,r){return se(this,void 0,void 0,(function*(){yield ve.writeRaw(H.Cyan,"info",e,t,r)}))}static success(e,t,r){return se(this,void 0,void 0,(function*(){yield ve.writeRaw(H.Green,"success",e,t,r)}))}static warning(e,t,r){return se(this,void 0,void 0,(function*(){yield ve.writeRaw(H.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return se(this,void 0,void 0,(function*(){n&&M.console(e,t,r),ae&&(yield fe.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Pe=e=>U(e)?G(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 Se extends J{constructor(){super(),this.all=e=>se(this,void 0,void 0,(function*(){e=e||P;const t=yield Ie.findAll({attributes:["session"],where:{expired:{[C.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 Ie.destroy().catch(P),e&&e()})),this.destroy=(e,t)=>se(this,void 0,void 0,(function*(){yield Ie.destroy({where:{session:e}}).catch(P),t&&t()})),this.expired=()=>se(this,void 0,void 0,(function*(){yield Ie.destroy({where:{expired:{[C.lt]:Date.now()}}}).catch(P)})),this.get=(e,t)=>se(this,void 0,void 0,(function*(){t=t||P;const r=yield Ie.findOne({where:{session:e,expired:{[C.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(P),void t(null)}t(null,e)}else t(null)})),this.length=e=>se(this,void 0,void 0,(function*(){e&&e(null,(yield Ie.count().catch(P))||0)})),this.set=(e,t,r)=>se(this,void 0,void 0,(function*(){r=r||P;const i=Date.now()+oe.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield Ie.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(P))||[];s&&(o||(s.json=n,s.expired=i,yield s.save().catch(P))),r()})),this.loop=A(this.expired,3e4),this.loop.start()}}class Oe{static create(e){return se(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{id:t}=e,r=E(),i=yield ue.create({secret:r,userId:t}).catch(Oe.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:V({id:t,secret:r},Ee.token,Oe.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){ve.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}=Oe.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(Oe.error);if(r){const i=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Oe.error);if(i&&!i.logout){i.secret=E(),yield i.save().catch(Oe.error);return{auth:i,token:V({id:e,secret:i.secret},Ee.token,Oe.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return se(this,void 0,void 0,(function*(){const{error:t,decode:r}=Oe.verify(e);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(Oe.error);if(r){const e=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Oe.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:$(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 Se,name:oe.API_SESSION_NAME,secret:oe.API_SESSION_SECRET,cookie:{maxAge:oe.API_SESSION_LIFETIME},genid:E}})}error(e,t){ve.info(e.message,t,oe.API_CONSOLE_ERROR)}log(e,t){ve.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 B.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 Oe.user(n.toString());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 S(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){ve.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.findOne({where:{key:e}}).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((({req:e})=>e.auth)),be=t((({req:e})=>O(e.files))),Ne=t((({req:e})=>e.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=>{ve.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 xe extends T{constructor(){super(...arguments),this._uploads=w()}auth(e,t,r){return se(this,void 0,void 0,(function*(){const{auth:i,error:n,user:s}=yield Oe.user(t);return n?(e.error(n),e.close()):i&&s?i.useragent!=r?(e.error("Invalid token"),e.close()):(e.req.auth=i,e.req.user=s,void e.next()):(e.error("Internal Server Error"),e.close())}))}session(e,t,r){return se(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(P):(r.useragent=t,r.save(P))),e.next()}))}error(e){ve.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():(e.unauthorized("Access denied"),void e.close()):(e.unauthorized("Access denied"),e.close())}))}read(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){const r=this._uploads(t);r.upload||(r.upload=this.uploadMiddleware(t)),r.upload(e.req,e.res,(t=>{if(t)return e.destroy(t);e.next()}))}uploadFile(e,t){const r=E()+"."+t;return U(ee(e,r))?this.uploadFile(e,t):r}uploadMiddleware(e){const t=(null==e?void 0:e.path)||oe.API_UPLOAD_TEMP,r=Q.diskStorage({destination:(e,r,i)=>i(null,t),filename:(e,r,i)=>se(this,void 0,void 0,(function*(){return i(null,this.uploadFile(t,r.originalname.split(".").pop()||"bin"))}))}),i=(null==e?void 0:e.types)||[],n=Q({storage:r,fileFilter(e,t,r){return se(this,void 0,void 0,(function*(){if(i.length){const e=t.originalname.split(".").pop()||"bin";return-1!=i.indexOf(t.mimetype)||-1!=i.indexOf(e)?r(null,!0):r(new Error("File not allowed"))}return r(null,!0)}))},limits:{fileSize:1e6*((null==e?void 0:e.size)||oe.API_UPLOAD_SIZE)}});return n.array((null==e?void 0:e.field)||oe.API_UPLOAD_FIELD,(null==e?void 0:e.count)||oe.API_UPLOAD_COUNT)}validation(e,t){return se(this,void 0,void 0,(function*(){const{error:r,value:i}=yield R.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r),e.close();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_TOKEN_HEADER)),ie(2,i("user-agent")),ne("design:type",Function),ne("design:paramtypes",[o,String,String]),ne("design:returntype",Promise)],xe.prototype,"auth",null),re([ie(0,r()),ie(1,i("user-agent")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[o,String,Object]),ne("design:returntype",Promise)],xe.prototype,"session",null),re([ie(0,r()),ie(1,s()),ie(2,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,String,me]),ne("design:returntype",Promise)],xe.prototype,"permission",null),re([ie(0,r()),ie(1,s()),ie(2,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,String,me]),ne("design:returntype",Promise)],xe.prototype,"read",null),re([ie(0,r()),ie(1,s()),ne("design:type",Function),ne("design:paramtypes",[o,Object]),ne("design:returntype",void 0)],xe.prototype,"upload",null),re([ie(0,r()),ie(1,s()),ne("design:type",Function),ne("design:paramtypes",[o,Object]),ne("design:returntype",Promise)],xe.prototype,"validation",null),re([ie(0,r()),ie(1,s()),ie(2,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,String,me]),ne("design:returntype",Promise)],xe.prototype,"write",null);let Fe=class extends xe{login(e,t,r,i,n){return se(this,void 0,void 0,(function*(){yield S(oe.API_SLEEP_AUTH);const s=r,o=yield me.findOne({where:{[C.or]:[{email:s},{username:r}],[C.and]:[{password:te(i).toString()}]}}).catch(this.error);if(!o)return e.notFound("Invalid username or password"),e.close(),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"),e.close(),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"),e.close(),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const{auth:a,error:u,token:c}=yield Oe.create(o);return u?(e.error(u),e.close(),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}),e.close(),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"),e.close(),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 Oe.destroy(t))return e.success("Disconcerted"),e.close(),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 Oe.renew(r);return s?e.error(s):n?(n.useragent=t,yield n.save().catch(this.error),e.json({token:o}),e.close(),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([d("/login"),a("validation",{username:R.string().min(3).required(),password:R.string().min(5).required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,u("username")),ie(3,u("password")),ie(4,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,String,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"login",null),re([l("/logout"),a("auth"),ie(0,r()),ie(1,Re()),ie(2,Ne()),ie(3,c()),ne("design:type",Function),ne("design:paramtypes",[o,ue,me,Te]),ne("design:returntype",Promise)],Fe.prototype,"logout",null),re([d("/renew"),a("validation",{token:R.string().required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,u("token")),ie(3,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"renew",null),re([l(),a("auth"),ie(0,r()),ie(1,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,me]),ne("design:returntype",Promise)],Fe.prototype,"user",null),Fe=re([p("/auth"),g(xe)],Fe);let qe=class extends xe{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=ee(this.directory(),t);if(!U(r)||!z(r).isDirectory())return e.status(h.NOT_FOUND),{message:"Path not Found"};let i=[];return i=X(r),i=i.map((e=>this.info(ee(r,e)))),i=i.filter(b),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,"files_"+this.name()+"."+t,r)}))}info(e){if(!U(e))return null;const t=z(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()}}};re([l("/path/?*"),a("auth"),a("access","list"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],qe.prototype,"files",null),re([ie(0,r()),ie(1,s()),ie(2,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,String,me]),ne("design:returntype",Promise)],qe.prototype,"access",null),qe=re([p("/files"),g(xe)],qe);let Be=class extends xe{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=N(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return se(this,void 0,void 0,(function*(){yield S(oe.API_SLEEP_FORGOT);const i=t,n=yield me.findOne({where:{[C.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=N(),o=Date.now()+6e4*oe.API_TOKEN_FORGOT,d=yield ce.create({token:s,timestamp:o,state:!0,userId:n.id});e.success("OK"),e.close(),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=te(r).toString(),yield n.user.save().catch(this.error),e.success("OK"),e.close(),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([l("/check"),a("validation",{token:R.string().required()}),ie(0,r()),ie(1,u("token")),ne("design:type",Function),ne("design:paramtypes",[o,String]),ne("design:returntype",Promise)],Be.prototype,"check",null),re([d(),a("validation",{username:R.string().min(4).required()}),ie(0,r()),ie(1,u("username")),ie(2,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,Te]),ne("design:returntype",Promise)],Be.prototype,"forgot",null),re([d("/reset"),a("validation",{token:R.string().required(),password:R.string().min(5).required()}),ie(0,r()),ie(1,u("token")),ie(2,u("password")),ie(3,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,String,Te]),ne("design:returntype",Promise)],Be.prototype,"reset",null),Be=re([p("/forgot"),g(xe)],Be);let ke=class extends xe{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.json({[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}){var i,n,s,o,d;const a=this.model(),u=Object.assign({},t||{});u.where=Object.assign({},u.where||{});const c=null===(i=e.req.query.limit)||void 0===i?void 0:i.toString();c&&(u.limit=parseInt(c));const l=null===(n=e.req.query.offset)||void 0===n?void 0:n.toString();l&&(u.offset=parseInt(l));const p=this.columns(),g=[],h=null===(s=e.req.query.asc)||void 0===s?void 0:s.toString();h&&h.length&&h.split(",").forEach((e=>{p.indexOf(e)>=0&&g.push([e,"ASC"])}));const m=null===(o=e.req.query.desc)||void 0===o?void 0:o.toString();m&&m.length&&m.split(",").forEach((e=>{p.indexOf(e)>=0&&g.push([e,"DESC"])})),g.length&&(u.order=g);const y=[],_=D(u.attributes)?u.attributes:p,f=null===(d=e.req.query.search)||void 0===d?void 0:d.toString();_.forEach((t=>{var r;if(x(t)&&(f&&f.length&&y.push({[t]:{[C.like]:`%${f}%`}}),"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&&y.push({[t]:{[C.like]:`%${i}%`}})}})),y.length&&(u.where=Object.assign(Object.assign({},u.where),{[C.or]:[...y]}));const I=(yield a.count(Object.assign(Object.assign({},u),{col:p[0]})).catch(this.error))||0,v=yield a.findAll(u).catch(this.error);return v?(e.json({count:I,records:r?yield r(v):v}),[v,I]):(e.error("Internal Server Error"),[])}))}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?ve.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}){const i=this.key(),{[i]:n}=e.req.params,s=yield this.model().findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:n})})).catch(this.error);return s?(e.json(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}_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)}))}};ke=re([g(xe)],ke);let Le=class extends ke{create(){return{}}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})}))}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([d(),a("auth"),a("write"),a("validationAdd"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"add",null),re([l(),a("auth"),a("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"all",null),re([m("/:id"),a("auth"),a("write"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"del",null),re([l("/:id"),a("auth"),a("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"get",null),re([y("/:id"),a("auth"),a("write"),a("validationSet"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"set",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"validationAdd",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Le.prototype,"validationSet",null),Le=re([g(ke)],Le);let je=class extends Le{model(){return le}create(){return{name:R.string().required(),description:R.string().empty(""),state:R.boolean().parse().required()}}update(){return{name:R.string().empty(),description:R.string().empty(),state:R.boolean().parse().empty()}}};je=re([p("/groups"),g(Le)],je);let Ce=class extends ke{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(F(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([l("/:id/routes"),a("auth"),a("read","groups"),ie(0,r()),ie(1,_("id")),ne("design:type",Function),ne("design:paramtypes",[o,String]),ne("design:returntype",Promise)],Ce.prototype,"all",null),re([y("/:id/routes"),a("auth"),a("write","groups"),a("validation",{routes:R.array(R.number().parse())}),ie(0,r()),ie(1,_("id")),ie(2,u("routes")),ne("design:type",Function),ne("design:paramtypes",[o,String,Array]),ne("design:returntype",Promise)],Ce.prototype,"set",null),Ce=re([p("/groups"),g(ke)],Ce);let Ke=class extends ke{model(){return fe}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([l(),a("auth"),a("read"),ie(0,r()),ie(1,f("type")),ie(2,f("source")),ne("design:type",Function),ne("design:paramtypes",[o,String,String]),ne("design:returntype",Promise)],Ke.prototype,"all",null),Ke=re([p("/logs"),g(ke)],Ke);let He=class extends xe{register(e,t,r){return se(this,void 0,void 0,(function*(){yield S(oe.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=te(d).toString();if(yield me.count({where:{[C.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=te(a).toString())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"),e.close(),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"),e.close(),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:{[C.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),e.close(),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=E();return(yield ge.count({where:{token:e}}))?this.getId():e}))}};re([d(),a("validation",{name:R.string().required(),date:R.string().date().required(),email:R.string().email().required(),username:R.string().min(4).empty(),password:R.string().min(5).required(),confirm:R.string().min(5).required()}),ie(0,r()),ie(1,u()),ie(2,c()),ne("design:type",Function),ne("design:paramtypes",[o,Object,Te]),ne("design:returntype",Promise)],He.prototype,"register",null),re([d("/confirm"),a("validation",{token:R.string().required()}),ie(0,r()),ie(1,u("token")),ie(2,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,Te]),ne("design:returntype",Promise)],He.prototype,"confirm",null),re([d("/send"),a("validation",{username:R.string().min(4).required()}),ie(0,r()),ie(1,u("username")),ie(2,c()),ne("design:type",Function),ne("design:paramtypes",[o,String,Te]),ne("design:returntype",Promise)],He.prototype,"send",null),He=re([p("/register"),g(xe)],He);let Me=class extends Le{model(){return he}create(){return{name:R.string().required(),description:R.string().empty(""),state:R.boolean().parse().required()}}update(){return{name:R.string().empty(),description:R.string().empty(),state:R.boolean().parse().empty()}}};Me=re([p("/routes"),g(Le)],Me);let Ue=class extends xe{setup(e){return se(this,void 0,void 0,(function*(){if(0==(yield me.count())){const e={description:"",state:!0},t=yield me.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),r=yield le.create(Object.assign({name:"admin"},e));yield ye.create({userId:t.id,groupId:r.id});const i=["read","write"],n=["users","groups","routes"];yield q(n,(t=>se(this,void 0,void 0,(function*(){yield q(i,(i=>se(this,void 0,void 0,(function*(){const n=t+"."+i,s=yield he.create(Object.assign({name:n},e));yield pe.create({groupId:r.id,routeId:s.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield q(s,(t=>se(this,void 0,void 0,(function*(){const i="files_api."+t,n=yield he.create(Object.assign({name:i},e));yield pe.create({groupId:r.id,routeId:n.id})}))));const o=yield he.create(Object.assign({name:"logs.read"},e));yield pe.create({groupId:r.id,routeId:o.id})}e.success("OK")}))}};re([l(),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Ue.prototype,"setup",null),Ue=re([p("/setup"),g(xe)],Ue);let Ge=class extends ke{model(){return me}constructor(){super(),this.dir=oe.API_HTTP_PUBLIC+"/avatar",oe.API_HTTP_PUBLIC&&U(oe.API_HTTP_PUBLIC)&&!U(this.dir)&&Y(this.dir)}avatar(e,t){return se(this,void 0,void 0,(function*(){if(D(e.req.files)&&e.req.files.length){const r=e.req.files[0].filename||"";if(r){const i=oe.API_HTTP_PUBLIC+"/avatar/";if(U(i+t.avatar)&&W(i+t.avatar).isFile()&&Z(i+t.avatar),t.avatar=r,yield t.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,i){return se(this,void 0,void 0,(function*(){const n=yield me.scope("password").findOne({where:{id:i.id,password:te(t).toString(),state:!0}}).catch(this.error);return n?(n.password=te(r).toString(),(yield n.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return se(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:te(t).toString()}})}))}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*(){yield this._set({ctx:e,body:t?{password:te(t).toString()}:{}})}))}};re([d("/avatar"),a("auth"),a("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:20}))),ie(0,r()),ie(1,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,me]),ne("design:returntype",Promise)],Ge.prototype,"avatar",null),re([d("/password"),a("auth"),a("validation",{oldPassword:R.string().min(5).required(),newPassword:R.string().min(5).required()}),ie(0,r()),ie(1,u("oldPassword")),ie(2,u("newPassword")),ie(3,Ne()),ne("design:type",Function),ne("design:paramtypes",[o,String,String,me]),ne("design:returntype",Promise)],Ge.prototype,"password",null),re([d(),a("auth"),a("write"),a("validation",{name:R.string().required(),email:R.string().email().required(),username:R.string().min(4).required(),password:R.string().min(5).required(),description:R.string().empty(""),state:R.boolean().parse().required()}),ie(0,r()),ie(1,u("password")),ne("design:type",Function),ne("design:paramtypes",[o,String]),ne("design:returntype",Promise)],Ge.prototype,"add",null),re([l(),a("auth"),a("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Ge.prototype,"all",null),re([m("/:id"),a("auth"),a("write"),ie(0,r()),ie(1,Ne()),ie(2,_("id")),ne("design:type",Function),ne("design:paramtypes",[o,me,String]),ne("design:returntype",Promise)],Ge.prototype,"del",null),re([l("/:id"),a("auth"),a("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[o]),ne("design:returntype",Promise)],Ge.prototype,"get",null),re([y("/:id"),a("auth"),a("write"),a("validation",{name:R.string().empty(),email:R.string().email().empty(),username:R.string().min(4).empty(),password:R.string().min(5).empty().filter(""),description:R.string().empty(),state:R.boolean().parse().empty()}),ie(0,r()),ie(1,u("password")),ne("design:type",Function),ne("design:paramtypes",[o,String]),ne("design:returntype",Promise)],Ge.prototype,"set",null),Ge=re([p("/users"),g(ke),ne("design:paramtypes",[])],Ge);let ze=class extends ke{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(F(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([l("/:id/groups"),a("auth"),a("read","users"),ie(0,r()),ie(1,_("id")),ne("design:type",Function),ne("design:paramtypes",[o,String]),ne("design:returntype",Promise)],ze.prototype,"all",null),re([y("/:id/groups"),a("auth"),a("write","users"),a("validation",{groups:R.array(R.number().parse())}),ie(0,r()),ie(1,_("id")),ie(2,u("groups")),ne("design:type",Function),ne("design:paramtypes",[o,String,Array]),ne("design:returntype",Promise)],ze.prototype,"set",null),ze=re([p("/users"),g(ke)],ze);export{Te as Application,ue as Auth,Fe as AuthController,we as Config,_e as Configs,xe as ControllerBase,Le as CrudController,de as Database,oe as Env,qe as FilesController,ce as Forgot,Be as ForgotController,le as Group,pe as GroupRoute,je as GroupsController,Ce as GroupsRoutesController,fe as Log,ve as Logs,Ke as LogsController,ke as ModelController,De as Permission,ge as Register,He as RegisterController,Re as ReqAuth,be as ReqFiles,Ne as ReqUser,he as Route,Me as RoutesController,Ie as Session,Ue as SetupController,Oe as Token,me as User,ye as UserGroup,Ge as UsersController,ze as UsersGroupsController,Ae as crt,Ee as key,ae as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.2",
|
|
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",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
],
|
|
20
20
|
"scripts": {
|
|
21
21
|
"build": "rollup --bundleConfigAsCjs -c rollup.config.js",
|
|
22
|
-
"dev": "ts-node-dev
|
|
22
|
+
"dev": "ts-node-dev ./src/dev.ts"
|
|
23
23
|
},
|
|
24
24
|
"repository": {
|
|
25
25
|
"type": "git",
|
|
@@ -45,8 +45,9 @@
|
|
|
45
45
|
},
|
|
46
46
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@andrewcaires/express": "^1.1.
|
|
49
|
-
"@andrewcaires/
|
|
48
|
+
"@andrewcaires/express": "^1.1.9",
|
|
49
|
+
"@andrewcaires/node": "^1.1.0",
|
|
50
|
+
"@andrewcaires/utils.js": "^0.3.1",
|
|
50
51
|
"cors": "^2.8.5",
|
|
51
52
|
"crypto-js": "^4.2.0",
|
|
52
53
|
"dotenv": "^16.4.5",
|
|
@@ -55,9 +56,9 @@
|
|
|
55
56
|
"jsonwebtoken": "^9.0.2",
|
|
56
57
|
"mariadb": "^3.3.1",
|
|
57
58
|
"multer": "^1.4.5-lts.1",
|
|
58
|
-
"mysql2": "^3.10.
|
|
59
|
+
"mysql2": "^3.10.1",
|
|
59
60
|
"sequelize": "^6.37.3",
|
|
60
|
-
"ws": "^8.17.
|
|
61
|
+
"ws": "^8.17.1"
|
|
61
62
|
},
|
|
62
63
|
"devDependencies": {
|
|
63
64
|
"@rollup/plugin-commonjs": "^26.0.1",
|
|
@@ -71,12 +72,10 @@
|
|
|
71
72
|
"@types/multer": "^1.4.11",
|
|
72
73
|
"@types/node": "^20.14.2",
|
|
73
74
|
"@types/ws": "^8.5.10",
|
|
74
|
-
"
|
|
75
|
-
"@typescript-eslint/parser": "^7.13.0",
|
|
76
|
-
"eslint": "^8.57.0",
|
|
75
|
+
"eslint": "^9.5.0",
|
|
77
76
|
"rollup": "^4.18.0",
|
|
78
77
|
"rollup-plugin-dts": "^6.1.1",
|
|
79
|
-
"
|
|
80
|
-
"
|
|
78
|
+
"tslib": "^2.6.3",
|
|
79
|
+
"typescript-eslint": "^8.0.0-alpha.30"
|
|
81
80
|
}
|
|
82
|
-
}
|
|
81
|
+
}
|