@andrewcaires/api 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.ts +56 -78
- package/dist/index.esm.js +2 -2
- package/package.json +11 -18
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.
|
|
2
|
+
* @andrewcaires/api v3.2.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/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 _=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 x extends o.Model{}x.init({secret:o.DataTypes.STRING,logout:o.DataTypes.DATE,useragent:o.DataTypes.STRING},{sequelize:_,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:_,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:_,modelName:h.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class P extends o.Model{}P.init({},{sequelize:_,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:_,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:_,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:_,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:_,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:_,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:_,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:_,modelName:h.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),T.removeAttribute("id"),C.hasMany(x),x.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),_&&(yield O.create({type:t,source:o,message:r}).catch((()=>null)))}))}}const D=e=>s.existsSync(e)?s.readFileSync(e):void 0,M={http:D(h.API_HTTP_CRT),token:D(h.API_TOKEN_CRT)},N={http:D(h.API_HTTP_KEY),token:D(h.API_TOKEN_KEY)};class b 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 F{static create(e){return y(this,void 0,void 0,(function*(){if(!N.token)return{error:"Key not found"};const{id:r}=e,o=t.uuidv4(),i=yield x.create({secret:o,userId:r}).catch(F.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:d.sign({id:r,secret:o},N.token,F.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(!N.token)return{error:"Key not found"};const{error:r,decode:o}=F.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(F.error);if(o){const i=yield x.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:d.sign({id:e,secret:i.secret},N.token,F.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}=F.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(F.error);if(r){const e=yield x.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:d.verify(e,M.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class q extends e.Application{constructor(e){super(e,{cert:M.http,cross:h.API_HTTP_CROSS,hybrid:h.API_HTTP_HYBRID,key:N.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 b,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 _.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 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 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 j{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 j.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return y(this,void 0,void 0,(function*(){const r=yield j.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 y(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 y(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",h.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return y(this,void 0,void 0,(function*(){return r?(yield j.is(r,t))?e.next():(e.unauthorized("Access denied"),void e.close()):(e.unauthorized("Access denied"),e.close())}))}read(e,t,r){return y(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 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){return y(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 y(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}c([p(0,e.Ctx()),p(1,e.Headers(h.API_TOKEN_HEADER)),p(2,e.Headers("user-agent")),g("design:type",Function),g("design:paramtypes",[e.Context,String,String]),g("design:returntype",Promise)],U.prototype,"auth",null),c([p(0,e.Ctx()),p(1,e.Headers("user-agent")),p(2,e.Session()),g("design:type",Function),g("design:paramtypes",[e.Context,String,Object]),g("design:returntype",Promise)],U.prototype,"session",null),c([p(0,e.Ctx()),p(1,e.Argument()),p(2,G()),g("design:type",Function),g("design:paramtypes",[e.Context,String,C]),g("design:returntype",Promise)],U.prototype,"permission",null),c([p(0,e.Ctx()),p(1,e.Argument()),p(2,G()),g("design:type",Function),g("design:paramtypes",[e.Context,String,C]),g("design:returntype",Promise)],U.prototype,"read",null),c([p(0,e.Ctx()),p(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",void 0)],U.prototype,"upload",null),c([p(0,e.Ctx()),p(1,e.Argument()),g("design:type",Function),g("design:paramtypes",[e.Context,Object]),g("design:returntype",Promise)],U.prototype,"validation",null),c([p(0,e.Ctx()),p(1,e.Argument()),p(2,G()),g("design:type",Function),g("design:paramtypes",[e.Context,String,C]),g("design:returntype",Promise)],U.prototype,"write",null),exports.AuthController=class extends U{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.close(),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.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:c,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})):c&&g?(c.useragent=r,yield c.save().catch(this.error),e.json({token:g}),e.close(),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.close(),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 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 y(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 y(this,void 0,void 0,(function*(){const r=yield j.all(t);if(!r)return e.error("Internal Server Error");e.json(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,x,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(U)],exports.AuthController),exports.FilesController=class extends U{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){return y(this,void 0,void 0,(function*(){yield this.permission(e,"files_"+this.name()+"."+t,r)}))}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.Argument()),p(2,G()),g("design:type",Function),g("design:paramtypes",[e.Context,String,C]),g("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=c([e.Controller("/files"),e.Extends(U)],exports.FilesController),exports.ForgotController=class extends U{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.json({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.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 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.close(),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(U)],exports.ForgotController),exports.ModelController=class extends U{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.json({[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 _=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,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&&x.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&&x.push({[r]:{[o.Op.like]:`%${t}%`}})}})),x.length&&(c.where=Object.assign(Object.assign({},c.where),{[o.Op.or]:[...x]}));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.json({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);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({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(U)],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){return y(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return y(this,void 0,void 0,(function*(){yield this.validation(e,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()),g("design:type",Function),g("design:paramtypes",[e.Context]),g("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),c([p(0,e.Ctx()),g("design:type",Function),g("design:paramtypes",[e.Context]),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 U{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.close(),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.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 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.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 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(U)],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 U{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(U)],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=x,exports.Config=B,exports.Configs=E,exports.ControllerBase=U,exports.Database=m,exports.Env=h,exports.Forgot=v,exports.Group=I,exports.GroupRoute=P,exports.Log=O,exports.Logs=R,exports.Permission=j,exports.Register=f,exports.ReqAuth=L,exports.ReqFiles=k,exports.ReqUser=G,exports.Route=A,exports.Session=T,exports.Token=F,exports.User=C,exports.UserGroup=S,exports.crt=M,exports.key=N,exports.sequelize=_;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/utils.js"),r=require("ws"),i=require("sequelize"),o=require("dotenv"),s=require("@andrewcaires/node"),n=require("fs"),d=require("express-session"),a=require("jsonwebtoken"),l=require("path");function u(e,t,r,i){var o,s=arguments.length,n=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,i);else for(var d=e.length-1;d>=0;d--)(o=e[d])&&(n=(s<3?o(n):s>3?o(t,r,n):o(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function c(e,t){return function(r,i){t(r,i,e)}}function p(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function g(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(e){try{a(i.next(e))}catch(e){s(e)}}function d(e){try{a(i.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,d)}a((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,o.config();class y{static getBool(e,r){return t.toBool(y.getString(e,r.toString()))}static getInt(e,t){return parseInt(y.getString(e,t.toString()))}static getMs(e,r){return t.parseMs(y.getString(e,r))}static getString(e,t){return e in process.env?process.env[e]||"":t}}y.API_CONSOLE_ERROR=y.getBool("API_CONSOLE_ERROR",!1),y.API_DEFAULT_PATH=y.getString("API_DEFAULT_PATH","/api"),y.API_DB_DATABASE=y.getString("API_DB_DATABASE",""),y.API_DB_HOST=y.getString("API_DB_HOST","127.0.0.1"),y.API_DB_PASSWORD=y.getString("API_DB_PASSWORD",""),y.API_DB_PORT=y.getInt("API_DB_PORT",3306),y.API_DB_TYPE=y.getString("API_DB_TYPE",""),y.API_DB_USERNAME=y.getString("API_DB_USERNAME","root"),y.API_DB_LOG=y.getBool("API_DB_LOG",!1),y.API_DB_PREFIX=y.getString("API_DB_PREFIX",""),y.API_DB_TIMEZONE=y.getString("API_DB_TIMEZONE","+00:00"),y.API_HTTP_CRT=y.getString("API_HTTP_CRT",""),y.API_HTTP_KEY=y.getString("API_HTTP_KEY",""),y.API_HTTP_PORT=y.getInt("API_HTTP_PORT",3e3),y.API_HTTP_PUBLIC=y.getString("API_HTTP_PUBLIC",""),y.API_HTTP_CROSS=y.getBool("API_HTTP_CROSS",!1),y.API_HTTP_HYBRID=y.getBool("API_HTTP_HYBRID",!1),y.API_HTTP_REDIRECT=y.getString("API_HTTP_REDIRECT",""),y.API_NOTFOUND_REDIRECT=y.getString("API_NOTFOUND_REDIRECT",""),y.API_SLEEP_AUTH=y.getMs("API_SLEEP_AUTH","2s"),y.API_SLEEP_FORGOT=y.getMs("API_SLEEP_FORGOT","5s"),y.API_SLEEP_REGISTRY=y.getMs("API_SLEEP_REGISTRY","5s"),y.API_SESSION_NAME=y.getString("API_SESSION_NAME","session.id"),y.API_SESSION_LIFETIME=y.getMs("API_SESSION_LIFETIME","1d"),y.API_SESSION_SECRET=y.getString("API_SESSION_SECRET","yoursecret"),y.API_TOKEN_CRT=y.getString("API_TOKEN_CRT",""),y.API_TOKEN_KEY=y.getString("API_TOKEN_KEY",""),y.API_TOKEN_FORGOT=y.getMs("API_TOKEN_LIFETIME","1d"),y.API_TOKEN_HEADER=y.getString("API_TOKEN_HEADER","authorization"),y.API_TOKEN_LIFETIME=y.getMs("API_TOKEN_LIFETIME","1d"),y.API_TOKEN_RENEW=y.getMs("API_TOKEN_RENEW","1d"),y.API_UPLOAD_COUNT=y.getInt("API_UPLOAD_COUNT",1),y.API_UPLOAD_FIELD=process.env.API_UPLOAD_FIELD||"upload",y.API_UPLOAD_SIZE=y.getInt("API_UPLOAD_SIZE",2),y.API_UPLOAD_TEMP=y.getString("API_UPLOAD_TEMP","./temp"),y.API_WEBSOCKET_START=y.getBool("API_WEBSOCKET_START",!1);class h{static connect(e){const t="connect_"+y.API_DB_TYPE.toLowerCase();if(t in h)return h[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new i.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mariadb",logging:y.API_DB_LOG,define:{timestamps:!1},timezone:y.API_DB_TIMEZONE})}static connect_memory(){return new i.Sequelize("sqlite::memory:",{logging:y.API_DB_LOG,define:{timestamps:!1},timezone:y.API_DB_TIMEZONE})}static connect_mysql(e){return new i.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mysql",logging:y.API_DB_LOG,define:{timestamps:!1},timezone:y.API_DB_TIMEZONE})}static connect_postgres(e){return new i.Sequelize(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"postgres",logging:y.API_DB_LOG,define:{timestamps:!1},timezone:y.API_DB_TIMEZONE})}static connect_sqlite(e){return new i.Sequelize({dialect:"sqlite",storage:e.database,logging:y.API_DB_LOG,define:{timestamps:!1},timezone:y.API_DB_TIMEZONE})}}const m=h.connect({database:y.API_DB_DATABASE,username:y.API_DB_USERNAME,password:y.API_DB_PASSWORD,hostname:y.API_DB_HOST,hostport:y.API_DB_PORT});class _ extends i.Model{}_.init({secret:i.DataTypes.STRING,logout:i.DataTypes.DATE,useragent:i.DataTypes.STRING},{sequelize:m,modelName:y.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class x extends i.Model{}x.init({token:i.DataTypes.STRING,timestamp:i.DataTypes.BIGINT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:y.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class P extends i.Model{}P.init({name:i.DataTypes.STRING,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:y.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class I extends i.Model{}I.init({},{sequelize:m,modelName:y.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),I.removeAttribute("id");class v extends i.Model{}v.init({token:i.DataTypes.STRING,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:y.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class f extends i.Model{}f.init({name:i.DataTypes.STRING,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:y.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class A extends i.Model{}A.init({name:i.DataTypes.STRING,email:i.DataTypes.STRING,username:i.DataTypes.STRING,password:i.DataTypes.STRING,avatar:i.DataTypes.STRING,date:i.DataTypes.DATEONLY,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:y.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class C extends i.Model{}C.init({},{sequelize:m,modelName:y.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),C.removeAttribute("id");class E extends i.Model{}E.init({key:i.DataTypes.STRING,value:i.DataTypes.STRING},{sequelize:m,modelName:y.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),E.removeAttribute("id");class S extends i.Model{}S.init({type:i.DataTypes.STRING,source:i.DataTypes.STRING,message:i.DataTypes.TEXT},{sequelize:m,modelName:y.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class T extends i.Model{}T.init({session:i.DataTypes.STRING,json:i.DataTypes.TEXT,expired:i.DataTypes.BIGINT},{sequelize:m,modelName:y.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),T.removeAttribute("id"),A.hasMany(_),_.belongsTo(A),A.hasMany(x),x.belongsTo(A),A.hasMany(v),v.belongsTo(A),P.hasMany(I),I.belongsTo(P),f.hasMany(I),I.belongsTo(f),A.hasMany(C),C.belongsTo(A),P.hasMany(C),C.belongsTo(P);class O{static write(e,t,r){return g(this,void 0,void 0,(function*(){yield O.writeRaw(s.LogColor.White,"",e,t,r)}))}static error(e,t,r){return g(this,void 0,void 0,(function*(){yield O.writeRaw(s.LogColor.Red,"error",e,t,r)}))}static info(e,t,r){return g(this,void 0,void 0,(function*(){yield O.writeRaw(s.LogColor.Cyan,"info",e,t,r)}))}static success(e,t,r){return g(this,void 0,void 0,(function*(){yield O.writeRaw(s.LogColor.Green,"success",e,t,r)}))}static warning(e,t,r){return g(this,void 0,void 0,(function*(){yield O.writeRaw(s.LogColor.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,o){return g(this,void 0,void 0,(function*(){o&&s.Log.console(e,t,r),m&&(yield S.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const w=e=>n.existsSync(e)?n.readFileSync(e):void 0,R={http:w(y.API_HTTP_CRT),token:w(y.API_TOKEN_CRT)},D={http:w(y.API_HTTP_KEY),token:w(y.API_TOKEN_KEY)};class M extends d.Store{constructor(){super(),this.all=e=>g(this,void 0,void 0,(function*(){e=e||t.noop;const r=yield T.findAll({attributes:["session"],where:{expired:{[i.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));r&&e(null,r.map((e=>e.session))),e()})),this.clear=e=>g(this,void 0,void 0,(function*(){yield T.destroy().catch(t.noop),e&&e()})),this.destroy=(e,r)=>g(this,void 0,void 0,(function*(){yield T.destroy({where:{session:e}}).catch(t.noop),r&&r()})),this.expired=()=>g(this,void 0,void 0,(function*(){yield T.destroy({where:{expired:{[i.Op.lt]:Date.now()}}}).catch(t.noop)})),this.get=(e,r)=>g(this,void 0,void 0,(function*(){r=r||t.noop;const o=yield T.findOne({where:{session:e,expired:{[i.Op.gte]:Date.now()}}}).catch((e=>(r(e),null)));if(o){const e=JSON.parse(o.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(t.noop),void r(null)}r(null,e)}else r(null)})),this.length=e=>g(this,void 0,void 0,(function*(){e&&e(null,(yield T.count().catch(t.noop))||0)})),this.set=(e,r,i)=>g(this,void 0,void 0,(function*(){i=i||t.noop;const o=Date.now()+y.API_SESSION_LIFETIME,s=JSON.stringify(r),[n,d]=(yield T.findOrCreate({where:{session:e},defaults:{session:e,json:s,expired:o}}).catch(t.noop))||[];n&&(d||(n.json=s,n.expired=o,yield n.save().catch(t.noop))),i()})),this.loop=t.loop(this.expired,3e4),this.loop.start()}}class b{static create(e){return g(this,void 0,void 0,(function*(){if(!D.token)return{error:"Key not found"};const{id:r}=e,i=t.uuidv4(),o=yield _.create({secret:i,userId:r}).catch(b.error);if(!o)return{error:"Internal Server Error"};return{auth:o,token:a.sign({id:r,secret:i},D.token,b.options())}}))}static destroy(e){return g(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){O.error(e.message,"api.token",y.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:y.API_TOKEN_LIFETIME+"ms"}}static renew(e){return g(this,void 0,void 0,(function*(){if(!D.token)return{error:"Key not found"};const{error:r,decode:i}=b.verify(e,y.API_TOKEN_RENEW/1e3);if(r)return{error:r};if(i){const{id:e,secret:r}=i;if(e&&r){const i=yield A.findOne({where:{id:e,state:!0}}).catch(b.error);if(i){const o=yield _.findOne({where:{secret:r,userId:i.id}}).catch(b.error);if(o&&!o.logout){o.secret=t.uuidv4(),yield o.save().catch(b.error);return{auth:o,token:a.sign({id:e,secret:o.secret},D.token,b.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return g(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 A.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(!R.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:a.verify(e,R.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class F extends e.Application{constructor(e){super(e,{cert:R.http,cross:y.API_HTTP_CROSS,hybrid:y.API_HTTP_HYBRID,key:D.http,notfound:y.API_NOTFOUND_REDIRECT,path:y.API_DEFAULT_PATH,port:y.API_HTTP_PORT,public:y.API_HTTP_PUBLIC,redirect:y.API_HTTP_REDIRECT,session:{store:new M,name:y.API_SESSION_NAME,secret:y.API_SESSION_SECRET,cookie:{maxAge:y.API_SESSION_LIFETIME},genid:t.uuidv4}})}error(e,t){O.info(e.message,t,y.API_CONSOLE_ERROR)}log(e,t){O.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return g(this,void 0,void 0,(function*(){yield m.sync(),yield e.listen.call(this),y.API_WEBSOCKET_START&&this.server&&(this._webSocket=new r.Server({server:this.server,verifyClient:(e,t)=>t(y.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,r)=>g(this,void 0,void 0,(function*(){r.url||(r.url="");const i=r.url.length<=1?"":r.url.replace(/\//g,".");let o;e.on("message",(t=>g(this,void 0,void 0,(function*(){if(o)try{const s=JSON.parse(t);this.emit("ws.message"+i,{data:s,message:t,req:r,user:o,ws:e})}catch(s){this.emit("ws.message"+i,{message:t,req:r,user:o,ws:e})}else{const{user:s}=yield b.user(t.toString());s&&(o=s,this.emit("ws.connection"+i,{req:r,user:o,ws:e}))}o||e.close()})))),e.on("close",(()=>{o&&this.emit("ws.close"+i,{user:o,ws:e})})),yield t.sleep(2e3),o||e.close()})))))}))}websocket(){return this._webSocket}}class N{static all(){return g(this,void 0,void 0,(function*(){const e=yield E.findAll().catch(N.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return g(this,void 0,void 0,(function*(){return((yield E.destroy({where:{key:e}}).catch(N.error))||0)>0}))}static error(e){O.error(e.message,"api.config",y.API_CONSOLE_ERROR)}static get(e){return g(this,arguments,void 0,(function*(e,t=""){const r=yield E.findOne({where:{key:e}}).catch(N.error);return r?r.value:t}))}static set(e,t){return g(this,void 0,void 0,(function*(){const[r]=(yield E.findOrCreate({where:{key:e}}).catch(N.error))||[];r&&(r.value=t,yield r.save().catch(N.error))}))}}const q=e.parameterFactory((({ctx:e})=>e.req.auth)),B=e.parameterFactory((({ctx:e})=>e.req.user));class L{static all(e,t){return g(this,void 0,void 0,(function*(){return yield f.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:I,required:!0,include:[{model:P,required:!0,where:{state:!0},include:[{model:C,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{O.error(e.message,"api.permission",y.API_CONSOLE_ERROR)}))}))}static get(e){return g(this,void 0,void 0,(function*(){const t=yield L.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return g(this,void 0,void 0,(function*(){const r=yield L.all(e,{name:t});return!!r&&r.length>0}))}}class k extends t.EventEmitter{auth(e,t,r){return g(this,void 0,void 0,(function*(){const{auth:i,error:o,user:s}=yield b.user(t);return o?e.error(o):i&&s?i.useragent!=r?e.error("Invalid token"):(e.req.auth=i,e.req.user=s,void e.next()):e.error("Internal Server Error")}))}session(e,r,i){return g(this,void 0,void 0,(function*(){i.auth&&i.user&&(i.useragent?i.useragent!=r&&i.regenerate(t.noop):(i.useragent=r,i.save(t.noop))),e.next()}))}error(e){O.error(e.message,"api.controller",y.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return g(this,void 0,void 0,(function*(){return r?(yield L.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(t,r){r.path||(r.path=y.API_UPLOAD_TEMP),r.size||(r.size=y.API_UPLOAD_SIZE),r.field||(r.field=y.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}validation(e,r){return g(this,void 0,void 0,(function*(){const{error:i,value:o}=yield t.Validation.object(r).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=o,e.next()}))}write(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}u([c(0,e.Ctx()),c(1,e.Headers(y.API_TOKEN_HEADER)),c(2,e.Headers("user-agent")),p("design:type",Function),p("design:paramtypes",[e.Context,String,String]),p("design:returntype",Promise)],k.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),p("design:type",Function),p("design:paramtypes",[e.Context,String,Object]),p("design:returntype",Promise)],k.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,B()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],k.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,B()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],k.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",void 0)],k.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",Promise)],k.prototype,"validation",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,B()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],k.prototype,"write",null),exports.AuthController=class extends k{login(e,r,o,n,d){return g(this,void 0,void 0,(function*(){yield t.sleep(y.API_SLEEP_AUTH);const a=o,l=yield A.findOne({where:{[i.Op.or]:[{email:a},{username:o}],[i.Op.and]:[{password:s.sha256(n)}]}}).catch(this.error);if(!l)return e.notFound("Invalid username or password"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const u=yield v.findOne({where:{state:!0,userId:l.id}}).catch(this.error);if(u)return e.error("Activation required"),d.emit("auth.activation",{ctx:e,register:u,user:l}),void this.emit("auth.activation",{ctx:e,register:u,user:l});if(!l.state)return e.notFound("Invalid username or password"),d.emit("auth.failure",{ctx:e,user:l}),void this.emit("auth.failure",{ctx:e,user:l});const{auth:c,error:p,token:g}=yield b.create(l);return p?(e.error(p),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):c&&g?(c.useragent=r,yield c.save().catch(this.error),e.json({token:g}),d.emit("auth.login",{auth:c,ctx:e,user:l}),void this.emit("auth.login",{auth:c,ctx:e,user:l})):(e.error("Internal Server Error"),d.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return g(this,void 0,void 0,(function*(){if(yield b.destroy(t))return e.success("Disconcerted"),i.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,i){return g(this,void 0,void 0,(function*(){const{auth:o,error:s,token:n}=yield b.renew(r);return s?e.error(s):o?(o.useragent=t,yield o.save().catch(this.error),e.json({token:n}),i.emit("auth.renew",{auth:o,ctx:e}),void this.emit("auth.renew",{auth:o,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return g(this,void 0,void 0,(function*(){const r=yield L.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},u([e.Post("/login"),e.Middleware("validation",{username:t.Validation.string().min(3).required(),password:t.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,String,F]),p("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,q()),c(2,B()),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,_,A,F]),p("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),u([e.Post("/renew"),e.Middleware("validation",{token:t.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,F]),p("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,B()),p("design:type",Function),p("design:paramtypes",[e.Context,A]),p("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(k)],exports.AuthController),exports.FilesController=class extends k{directory(){return y.API_HTTP_PUBLIC||"./"}files(e){return g(this,void 0,void 0,(function*(){let{path:r}=e.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=l.join(this.directory(),r);if(!n.existsSync(i)||!n.statSync(i).isDirectory())return e.notFound("Path not Found");let o=[];return o=n.readdirSync(i),o=o.map((e=>this.info(l.join(i,e)))),o=o.filter(t.isDef),Object.assign(Object.assign({},this.info(i)),{files:o})}))}access(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const i=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:i?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:i,symlink:t.isSymbolicLink()}}name(){return"files"}},u([e.Get("/path/?*"),e.Middleware("auth"),e.Middleware("access","list"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.FilesController.prototype,"files",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,B()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(k)],exports.FilesController),exports.ForgotController=class extends k{check(e,r){return g(this,void 0,void 0,(function*(){const i=yield this.find(r);if(!i||!i.user)return e.notFound("User not found");i.token=t.uniqueID(),yield i.save(),e.json({token:i.token})}))}forgot(e,r,o){return g(this,void 0,void 0,(function*(){yield t.sleep(y.API_SLEEP_FORGOT);const s=r,n=yield A.findOne({where:{[i.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*y.API_TOKEN_FORGOT,l=yield x.create({token:d,timestamp:a,state:!0,userId:n.id});e.success("OK"),o.emit("forgot.send",{ctx:e,forgot:l,user:n}),this.emit("forgot.send",{ctx:e,forgot:l,user:n})}))}reset(e,t,r,i){return g(this,void 0,void 0,(function*(){const o=yield this.find(t);if(!o)return e.notFound("User not found");o.state=!1,yield o.save().catch(this.error),o.user.password=s.sha256(r),yield o.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:o.user}),this.emit("forgot.reset",{ctx:e,user:o.user})}))}find(e){return g(this,void 0,void 0,(function*(){return yield x.findOne({where:{token:e,state:!0},include:[{model:A,required:!0}]}).catch(this.error)}))}},u([e.Get("/check"),e.Middleware("validation",{token:t.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),u([e.Post(),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),u([e.Post("/reset"),e.Middleware("validation",{token:t.Validation.string().required(),password:t.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,F]),p("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(k)],exports.ForgotController),exports.ModelController=class extends k{constructor(){super(...arguments),this._columns=[]}_add(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,body:i}){const o=yield this.model().create(Object.assign(Object.assign({},t.req.body),i||{}),r||{}).catch(this.error);if(o){const r=this.key();return t.prepare(e.Status.OK,{[r]:o.getDataValue(r)}),o}t.error("Internal Server Error")}))}_all(r){return g(this,arguments,void 0,(function*({ctx:r,options:o,callback:s}){var n,d,a,l,u;const c=this.model(),p=Object.assign({},o||{});p.where=Object.assign({},p.where||{});const g=null===(n=r.req.query.limit)||void 0===n?void 0:n.toString();g&&(p.limit=parseInt(g));const y=null===(d=r.req.query.offset)||void 0===d?void 0:d.toString();y&&(p.offset=parseInt(y));const h=this.columns(),m=[],_=null===(a=r.req.query.asc)||void 0===a?void 0:a.toString();_&&_.length&&_.split(",").forEach((e=>{h.indexOf(e)>=0&&m.push([e,"ASC"])}));const x=null===(l=r.req.query.desc)||void 0===l?void 0:l.toString();x&&x.length&&x.split(",").forEach((e=>{h.indexOf(e)>=0&&m.push([e,"DESC"])})),m.length&&(p.order=m);const P=[],I=t.isArray(p.attributes)?p.attributes:h,v=null===(u=r.req.query.search)||void 0===u?void 0:u.toString();I.forEach((e=>{var o;if(t.isString(e)&&(v&&v.length&&P.push({[e]:{[i.Op.like]:`%${v}%`}}),"search_"+e in r.req.query)){const t=null===(o=r.req.query["search_"+e])||void 0===o?void 0:o.toString();t&&t.length&&P.push({[e]:{[i.Op.like]:`%${t}%`}})}})),P.length&&(p.where=Object.assign(Object.assign({},p.where),{[i.Op.or]:[...P]}));const f=(yield c.count(Object.assign(Object.assign({},p),{col:h[0]})).catch(this.error))||0,A=yield c.findAll(p).catch(this.error);return A?(r.prepare(e.Status.OK,{count:f,records:s?yield s(A):A}),[A,f]):(r.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return g(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:i}=e.req.params;if(!i)return e.error("Internal Server Error"),0;const o=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i})})).catch(this.error);return o?(e.success("OK"),o):(e.notFound("Record not found"),0)}))}error(e){e.sql?O.error(e.message+"\n"+e.sql,"api.controller.sql",y.API_CONSOLE_ERROR):super.error(e)}_get(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,callback:i}){const o=this.key(),{[o]:s}=t.req.params,n=yield this.model().findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[o]:s})})).catch(this.error);return n?(t.prepare(e.Status.OK,i?yield i(n):n.toJSON()),n):null===n?t.notFound("Record not found"):void t.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}_set(e){return g(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=this.key(),{[i]:o}=e.req.params,[s]=(yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:o})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=u([e.Extends(k)],exports.ModelController),exports.CrudController=class extends exports.ModelController{create(){return{}}add(e){return g(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return g(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return g(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return g(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return g(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return g(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}},u([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationAdd"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validationSet"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"set",null),u([c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"validationAdd",null),u([c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.CrudController.prototype,"validationSet",null),exports.CrudController=u([e.Extends(exports.ModelController)],exports.CrudController),exports.GroupsController=class extends exports.CrudController{model(){return P}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=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return I}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:f,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,r,i){return g(this,void 0,void 0,(function*(){const o=yield P.findByPk(r,{attributes:["id"]}).catch(this.error);if(o){const t=o.id;if(yield I.destroy({where:{groupId:t}}),i){let e=0;for(let r=0;r<i.length;r++)e=yield f.count({where:{id:i[r]}}),e&&(yield I.create({groupId:t,routeId:i[r]}))}return e.success("OK")}if(t.isNull(o))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),u([e.Put("/:id/routes"),e.Middleware("auth"),e.Middleware("write","groups"),e.Middleware("validation",{routes:t.Validation.array(t.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("routes")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return S}all(e,t,r){return g(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.source=r),yield this._all({ctx:e,options:{where:i,order:[["created","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),p("design:type",Function),p("design:paramtypes",[e.Context,String,String]),p("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends k{register(e,r,o){return g(this,void 0,void 0,(function*(){yield t.sleep(y.API_SLEEP_REGISTRY);const{name:n,date:d,email:a,username:l,password:u,confirm:c}=r,p=l||a,g=s.sha256(u);if(yield A.count({where:{[i.Op.or]:[{email:a},{username:p}]}}).catch(this.error))return e.validation("Invalid email or username");if(g!=s.sha256(c))return e.error("Invalid password");const h=yield A.create({name:n,email:a,username:p,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!h)return e.error("Internal Server Error");const m=yield v.create({token:yield this.getId(),userId:h.id,state:!0}).catch(this.error);if(!m)return h.destroy(),e.error("Internal Server Error");e.success("OK"),o.emit("register.user",{ctx:e,register:m,user:h}),this.emit("register.user",{ctx:e,register:m,user:h})}))}confirm(e,t,r){return g(this,void 0,void 0,(function*(){const i=yield v.findOne({where:{token:t,state:!0},include:[{model:A,required:!0}]}).catch(this.error);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})}))}send(e,t,r){return g(this,void 0,void 0,(function*(){const o=t,s=yield v.findOne({where:{state:!0},include:[{model:A,required:!0,where:{[i.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})}))}getId(){return g(this,void 0,void 0,(function*(){const e=t.uuidv4();return(yield v.count({where:{token:e}}))?this.getId():e}))}},u([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()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,Object,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),u([e.Post("/confirm"),e.Middleware("validation",{token:t.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),u([e.Post("/send"),e.Middleware("validation",{username:t.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(k)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return f}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=u([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends k{setup(e){return g(this,void 0,void 0,(function*(){if(0==(yield A.count())){const e={description:"API CORE",state:!0},r=yield A.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),i=yield P.create(Object.assign({name:"admin"},e));yield C.create({userId:r.id,groupId:i.id});const o=["read","write"],s=["users","groups","routes"];yield t.forEachSeries(s,(r=>g(this,void 0,void 0,(function*(){yield t.forEachSeries(o,(t=>g(this,void 0,void 0,(function*(){const o=r+"."+t,s=yield f.create(Object.assign({name:o},e));yield I.create({groupId:i.id,routeId:s.id})}))))}))));const n=[...o,"delete","list","rename","upload"];yield t.forEachSeries(n,(t=>g(this,void 0,void 0,(function*(){const r="files."+t,o=yield f.create(Object.assign({name:r},e));yield I.create({groupId:i.id,routeId:o.id})}))));const d=yield f.create(Object.assign({name:"logs.read"},e));yield I.create({groupId:i.id,routeId:d.id})}e.success("OK")}))}},u([e.Get(),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=u([e.Controller("/setup"),e.Extends(k)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return A}constructor(){super(),this.dir=y.API_HTTP_PUBLIC+"/avatar",y.API_HTTP_PUBLIC&&n.existsSync(y.API_HTTP_PUBLIC)&&!n.existsSync(this.dir)&&n.mkdirSync(this.dir)}avatar(e,t,r){return g(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=i,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,i){return g(this,void 0,void 0,(function*(){const o=yield A.scope("password").findOne({where:{id:i.id,password:s.sha256(t),state:!0}}).catch(this.error);return o?(o.password=s.sha256(r),(yield o.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return g(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:s.sha256(t)}})}))}all(e){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return g(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return g(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return g(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:t?{password:s.sha256(t)}:{}})}))}},u([e.Post("/avatar"),e.Middleware("auth"),e.Middleware("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),c(0,e.Ctx()),c(1,e.Files()),c(2,B()),p("design:type",Function),p("design:paramtypes",[e.Context,Array,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:t.Validation.string().min(5).required(),newPassword:t.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,B()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([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()}),c(0,e.Ctx()),c(1,e.Body("password")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,B()),c(2,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,A,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name: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()}),c(0,e.Ctx()),c(1,e.Body("password")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),p("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return C}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:P,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,r,i){return g(this,void 0,void 0,(function*(){const o=yield A.findByPk(r,{attributes:["id"]}).catch(this.error);if(o){if(yield C.destroy({where:{userId:o.id}}),i){let e=0;for(let t=0;t<i.length;t++)e=yield P.count({where:{id:i[t]}}),e&&(yield C.create({userId:o.id,groupId:i[t]}))}return e.success("OK")}if(t.isNull(o))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("write","users"),e.Middleware("validation",{groups:t.Validation.array(t.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=F,exports.Auth=_,exports.Config=N,exports.Configs=E,exports.ControllerBase=k,exports.Database=h,exports.Env=y,exports.Forgot=x,exports.Group=P,exports.GroupRoute=I,exports.Log=S,exports.Logs=O,exports.Permission=L,exports.Register=v,exports.ReqAuth=q,exports.ReqUser=B,exports.Route=f,exports.Session=T,exports.Token=b,exports.User=A,exports.UserGroup=C,exports.crt=R,exports.key=D,exports.sequelize=m;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.
|
|
2
|
+
* @andrewcaires/api v3.2.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import { Context, IStore, Application as Application$1 } from '@andrewcaires/express';
|
|
7
|
+
import { Context, IStore, IUpload, Application as Application$1, IFile } from '@andrewcaires/express';
|
|
8
8
|
import WebSocket from 'ws';
|
|
9
|
-
import {
|
|
9
|
+
import { EventEmitter, TypeObject, ValidationBase, TypeObjectString, TypeObjectAny } 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 {
|
|
@@ -96,6 +96,57 @@ declare class Session extends Model {
|
|
|
96
96
|
expired: number;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
declare abstract class ControllerBase extends EventEmitter {
|
|
100
|
+
auth(ctx: Context, token: string, useragent: string): Promise<void>;
|
|
101
|
+
session(ctx: Context, useragent: string, store: IStore): Promise<void>;
|
|
102
|
+
error(error: any): void;
|
|
103
|
+
name(): string;
|
|
104
|
+
permission(ctx: Context, name: string, user: User): Promise<void>;
|
|
105
|
+
read(ctx: Context, name: string, user: User): Promise<void>;
|
|
106
|
+
upload(ctx: Context, options: IUpload): void;
|
|
107
|
+
validation(ctx: Context, options: TypeObject<ValidationBase>): Promise<void>;
|
|
108
|
+
write(ctx: Context, name: string, user: User): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
declare class Application extends Application$1 {
|
|
112
|
+
private _webSocket?;
|
|
113
|
+
constructor(controllers: Array<ControllerBase>);
|
|
114
|
+
error(error: any, source?: string): void;
|
|
115
|
+
log(message: string, source?: string): void;
|
|
116
|
+
listen(): Promise<void>;
|
|
117
|
+
websocket(): WebSocket.Server | undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
declare class Config {
|
|
121
|
+
static all(): Promise<TypeObjectString>;
|
|
122
|
+
static del(key: string): Promise<boolean>;
|
|
123
|
+
private static error;
|
|
124
|
+
static get(key: string, value?: string): Promise<string>;
|
|
125
|
+
static set(key: string, value: string): Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
declare class AuthController extends ControllerBase {
|
|
129
|
+
protected login(ctx: Context, useragent: string, username: string, password: string, app: Application): Promise<void>;
|
|
130
|
+
protected logout(ctx: Context, auth: Auth, user: User, app: Application): Promise<void>;
|
|
131
|
+
protected renew(ctx: Context, useragent: string, old: string, app: Application): Promise<void>;
|
|
132
|
+
protected user(ctx: Context, user: User): Promise<void>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
declare class FilesController extends ControllerBase {
|
|
136
|
+
directory(): string;
|
|
137
|
+
files(ctx: Context): Promise<TypeObjectAny | void>;
|
|
138
|
+
access(ctx: Context, name: string, user: User): Promise<void>;
|
|
139
|
+
private info;
|
|
140
|
+
name(): string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
declare class ForgotController extends ControllerBase {
|
|
144
|
+
check(ctx: Context, token: string): Promise<void>;
|
|
145
|
+
forgot(ctx: Context, username: string, app: Application): Promise<void>;
|
|
146
|
+
reset(ctx: Context, token: string, password: string, app: Application): Promise<void>;
|
|
147
|
+
private find;
|
|
148
|
+
}
|
|
149
|
+
|
|
99
150
|
interface ArgumentsModelAdd<M extends Model<M>> {
|
|
100
151
|
ctx: Context;
|
|
101
152
|
options?: CreateOptions<Attributes<M>>;
|
|
@@ -146,77 +197,6 @@ interface ITokenParameters {
|
|
|
146
197
|
user?: User;
|
|
147
198
|
}
|
|
148
199
|
|
|
149
|
-
interface IUploadOptions {
|
|
150
|
-
count?: number;
|
|
151
|
-
field?: string;
|
|
152
|
-
path?: string;
|
|
153
|
-
size?: number;
|
|
154
|
-
types?: Array<string>;
|
|
155
|
-
}
|
|
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
|
-
declare abstract class ControllerBase extends EventEmitter {
|
|
168
|
-
private _uploads;
|
|
169
|
-
auth(ctx: Context, token: string, useragent: string): Promise<void>;
|
|
170
|
-
session(ctx: Context, useragent: string, store: IStore): Promise<void>;
|
|
171
|
-
error(error: any): void;
|
|
172
|
-
name(): string;
|
|
173
|
-
permission(ctx: Context, name: string, user: User): Promise<void>;
|
|
174
|
-
read(ctx: Context, name: string, user: User): Promise<void>;
|
|
175
|
-
upload(ctx: Context, options: IUploadOptions): void;
|
|
176
|
-
private uploadFile;
|
|
177
|
-
private uploadMiddleware;
|
|
178
|
-
validation(ctx: Context, options: TypeObject<ValidationBase>): Promise<void>;
|
|
179
|
-
write(ctx: Context, name: string, user: User): Promise<void>;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
declare class Application extends Application$1 {
|
|
183
|
-
private _webSocket?;
|
|
184
|
-
constructor(controllers: Array<ControllerBase>);
|
|
185
|
-
error(error: any, source?: string): void;
|
|
186
|
-
log(message: string, source?: string): void;
|
|
187
|
-
listen(): Promise<void>;
|
|
188
|
-
websocket(): WebSocket.Server | undefined;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
declare class Config {
|
|
192
|
-
static all(): Promise<TypeObjectString>;
|
|
193
|
-
static del(key: string): Promise<boolean>;
|
|
194
|
-
private static error;
|
|
195
|
-
static get(key: string, value?: string): Promise<string>;
|
|
196
|
-
static set(key: string, value: string): Promise<void>;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
declare class AuthController extends ControllerBase {
|
|
200
|
-
protected login(ctx: Context, useragent: string, username: string, password: string, app: Application): Promise<void>;
|
|
201
|
-
protected logout(ctx: Context, auth: Auth, user: User, app: Application): Promise<void>;
|
|
202
|
-
protected renew(ctx: Context, useragent: string, old: string, app: Application): Promise<void>;
|
|
203
|
-
protected user(ctx: Context, user: User): Promise<void>;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
declare class FilesController extends ControllerBase {
|
|
207
|
-
directory(): string;
|
|
208
|
-
files(ctx: Context): Promise<TypeObjectAny>;
|
|
209
|
-
access(ctx: Context, name: string, user: User): Promise<void>;
|
|
210
|
-
private info;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
declare class ForgotController extends ControllerBase {
|
|
214
|
-
check(ctx: Context, token: string): Promise<void>;
|
|
215
|
-
forgot(ctx: Context, username: string, app: Application): Promise<void>;
|
|
216
|
-
reset(ctx: Context, token: string, password: string, app: Application): Promise<void>;
|
|
217
|
-
private find;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
200
|
declare abstract class ModelController<M extends Model<M>> extends ControllerBase {
|
|
221
201
|
private _columns;
|
|
222
202
|
protected _add({ ctx, options, body }: ArgumentsModelAdd<M>): Promise<M | void>;
|
|
@@ -281,7 +261,7 @@ declare class UsersController extends ModelController<User> {
|
|
|
281
261
|
dir: string;
|
|
282
262
|
model(): typeof User;
|
|
283
263
|
constructor();
|
|
284
|
-
avatar(ctx: Context, user: User): Promise<void>;
|
|
264
|
+
avatar(ctx: Context, files: Array<IFile>, user: User): Promise<void>;
|
|
285
265
|
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User): Promise<void>;
|
|
286
266
|
add(ctx: Context, password: string): Promise<void>;
|
|
287
267
|
protected all(ctx: Context): Promise<void>;
|
|
@@ -350,7 +330,6 @@ declare class Env {
|
|
|
350
330
|
}
|
|
351
331
|
|
|
352
332
|
declare const ReqAuth: (key?: string | undefined) => ParameterDecorator;
|
|
353
|
-
declare const ReqFiles: (key?: string | undefined) => ParameterDecorator;
|
|
354
333
|
declare const ReqUser: (key?: string | undefined) => ParameterDecorator;
|
|
355
334
|
declare global {
|
|
356
335
|
namespace Express {
|
|
@@ -367,7 +346,6 @@ declare class Logs {
|
|
|
367
346
|
static info(message: string, source?: string, console?: boolean): Promise<void>;
|
|
368
347
|
static success(message: string, source?: string, console?: boolean): Promise<void>;
|
|
369
348
|
static warning(message: string, source?: string, console?: boolean): Promise<void>;
|
|
370
|
-
private static writeConsole;
|
|
371
349
|
private static writeRaw;
|
|
372
350
|
}
|
|
373
351
|
|
|
@@ -396,4 +374,4 @@ declare class Token {
|
|
|
396
374
|
private static verify;
|
|
397
375
|
}
|
|
398
376
|
|
|
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,
|
|
377
|
+
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, Log, Logs, LogsController, ModelController, Permission, Register, RegisterController, ReqAuth, 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.
|
|
2
|
+
* @andrewcaires/api v3.2.0
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,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 v,parseMs as I,dateFormat as P,noop as A,loop as E,uuidv4 as O,sleep as S,toArray as T,EventEmitter as w,cache as R,Validation as N,isDef as b,uniqueID as D,isArray as x,isString as F,isNull as q,forEachSeries as B}from"@andrewcaires/utils.js";import k from"ws";import{Sequelize as L,DataTypes as j,Model as C,Op as K}from"sequelize";import{config as H}from"dotenv";import{existsSync as M,readFileSync as U,statSync as G,readdirSync as z,mkdirSync as X,lstatSync as Y,rmSync as W}from"fs";import{Store as Z}from"express-session";import{verify as J,sign as $}from"jsonwebtoken";import V from"multer";import{join as Q}from"path";import{SHA256 as ee}from"crypto-js";function te(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 re(e,t){return function(r,i){t(r,i,e)}}function ie(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function ne(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,H();class se{static getBool(e,t){return v(se.getString(e,t.toString()))}static getInt(e,t){return parseInt(se.getString(e,t.toString()))}static getMs(e,t){return I(se.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}se.API_CONSOLE_ERROR=se.getBool("API_CONSOLE_ERROR",!1),se.API_DEFAULT_PATH=se.getString("API_DEFAULT_PATH","/api"),se.API_DB_DATABASE=se.getString("API_DB_DATABASE",""),se.API_DB_HOST=se.getString("API_DB_HOST","127.0.0.1"),se.API_DB_PASSWORD=se.getString("API_DB_PASSWORD",""),se.API_DB_PORT=se.getInt("API_DB_PORT",3306),se.API_DB_TYPE=se.getString("API_DB_TYPE",""),se.API_DB_USERNAME=se.getString("API_DB_USERNAME","root"),se.API_DB_LOG=se.getBool("API_DB_LOG",!1),se.API_DB_PREFIX=se.getString("API_DB_PREFIX",""),se.API_DB_TIMEZONE=se.getString("API_DB_TIMEZONE","+00:00"),se.API_HTTP_CRT=se.getString("API_HTTP_CRT",""),se.API_HTTP_KEY=se.getString("API_HTTP_KEY",""),se.API_HTTP_PORT=se.getInt("API_HTTP_PORT",3e3),se.API_HTTP_PUBLIC=se.getString("API_HTTP_PUBLIC",""),se.API_HTTP_CROSS=se.getBool("API_HTTP_CROSS",!1),se.API_HTTP_HYBRID=se.getBool("API_HTTP_HYBRID",!1),se.API_HTTP_REDIRECT=se.getString("API_HTTP_REDIRECT",""),se.API_NOTFOUND_REDIRECT=se.getString("API_NOTFOUND_REDIRECT",""),se.API_SLEEP_AUTH=se.getMs("API_SLEEP_AUTH","2s"),se.API_SLEEP_FORGOT=se.getMs("API_SLEEP_FORGOT","5s"),se.API_SLEEP_REGISTRY=se.getMs("API_SLEEP_REGISTRY","5s"),se.API_SESSION_NAME=se.getString("API_SESSION_NAME","session.id"),se.API_SESSION_LIFETIME=se.getMs("API_SESSION_LIFETIME","1d"),se.API_SESSION_SECRET=se.getString("API_SESSION_SECRET","yoursecret"),se.API_TOKEN_CRT=se.getString("API_TOKEN_CRT",""),se.API_TOKEN_KEY=se.getString("API_TOKEN_KEY",""),se.API_TOKEN_FORGOT=se.getMs("API_TOKEN_LIFETIME","1d"),se.API_TOKEN_HEADER=se.getString("API_TOKEN_HEADER","authorization"),se.API_TOKEN_LIFETIME=se.getMs("API_TOKEN_LIFETIME","1d"),se.API_TOKEN_RENEW=se.getMs("API_TOKEN_RENEW","1d"),se.API_UPLOAD_COUNT=se.getInt("API_UPLOAD_COUNT",1),se.API_UPLOAD_FIELD=process.env.API_UPLOAD_FIELD||"upload",se.API_UPLOAD_SIZE=se.getInt("API_UPLOAD_SIZE",2),se.API_UPLOAD_TEMP=se.getString("API_UPLOAD_TEMP","./temp"),se.API_WEBSOCKET_START=se.getBool("API_WEBSOCKET_START",!1);class oe{static connect(e){const t="connect_"+se.API_DB_TYPE.toLowerCase();if(t in oe)return oe[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new L(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mariadb",logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_memory(){return new L("sqlite::memory:",{logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_mysql(e){return new L(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mysql",logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_postgres(e){return new L(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"postgres",logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_sqlite(e){return new L({dialect:"sqlite",storage:e.database,logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}}const de=oe.connect({database:se.API_DB_DATABASE,username:se.API_DB_USERNAME,password:se.API_DB_PASSWORD,hostname:se.API_DB_HOST,hostport:se.API_DB_PORT});class ae extends C{}ae.init({secret:j.STRING,logout:j.DATE,useragent:j.STRING},{sequelize:de,modelName:se.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ue extends C{}ue.init({token:j.STRING,timestamp:j.BIGINT,state:j.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends C{}ce.init({name:j.STRING,description:j.TEXT,state:j.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends C{}le.init({},{sequelize:de,modelName:se.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),le.removeAttribute("id");class pe extends C{}pe.init({token:j.STRING,state:j.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ge extends C{}ge.init({name:j.STRING,description:j.TEXT,state:j.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends C{}he.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:de,modelName:se.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class me extends C{}me.init({},{sequelize:de,modelName:se.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),me.removeAttribute("id");class ye extends C{}ye.init({key:j.STRING,value:j.STRING},{sequelize:de,modelName:se.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),ye.removeAttribute("id");class _e extends C{}_e.init({type:j.STRING,source:j.STRING,message:j.TEXT},{sequelize:de,modelName:se.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class fe extends C{}var ve;fe.init({session:j.STRING,json:j.TEXT,expired:j.BIGINT},{sequelize:de,modelName:se.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),fe.removeAttribute("id"),he.hasMany(ae),ae.belongsTo(he),he.hasMany(ue),ue.belongsTo(he),he.hasMany(pe),pe.belongsTo(he),ce.hasMany(le),le.belongsTo(ce),ge.hasMany(le),le.belongsTo(ge),he.hasMany(me),me.belongsTo(he),ce.hasMany(me),me.belongsTo(ce),function(e){e.ERROR="[31m",e.INFO="[36m",e.NONE="[37m",e.SUCCESS="[32m",e.WARNING="[33m"}(ve||(ve={}));class Ie{static write(e,t,r){return ne(this,void 0,void 0,(function*(){yield Ie.writeRaw(ve.NONE,"",e,t,r)}))}static error(e,t,r){return ne(this,void 0,void 0,(function*(){yield Ie.writeRaw(ve.ERROR,"error",e,t,r)}))}static info(e,t,r){return ne(this,void 0,void 0,(function*(){yield Ie.writeRaw(ve.INFO,"info",e,t,r)}))}static success(e,t,r){return ne(this,void 0,void 0,(function*(){yield Ie.writeRaw(ve.ERROR,"success",e,t,r)}))}static warning(e,t,r){return ne(this,void 0,void 0,(function*(){yield Ie.writeRaw(ve.WARNING,"warning",e,t,r)}))}static writeConsole(e,t,r){const i=P(new Date,"%H:%M:%S");console.log(">",e,t+" ".repeat(10-t.length),"[37m","|",i,"|",r)}static writeRaw(e,t,r,i,n){return ne(this,void 0,void 0,(function*(){n&&Ie.writeConsole(e,t,r),de&&(yield _e.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Pe=e=>M(e)?U(e):void 0,Ae={http:Pe(se.API_HTTP_CRT),token:Pe(se.API_TOKEN_CRT)},Ee={http:Pe(se.API_HTTP_KEY),token:Pe(se.API_TOKEN_KEY)};class Oe extends Z{constructor(){super(),this.all=e=>ne(this,void 0,void 0,(function*(){e=e||A;const t=yield fe.findAll({attributes:["session"],where:{expired:{[K.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>ne(this,void 0,void 0,(function*(){yield fe.destroy().catch(A),e&&e()})),this.destroy=(e,t)=>ne(this,void 0,void 0,(function*(){yield fe.destroy({where:{session:e}}).catch(A),t&&t()})),this.expired=()=>ne(this,void 0,void 0,(function*(){yield fe.destroy({where:{expired:{[K.lt]:Date.now()}}}).catch(A)})),this.get=(e,t)=>ne(this,void 0,void 0,(function*(){t=t||A;const r=yield fe.findOne({where:{session:e,expired:{[K.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(A),void t(null)}t(null,e)}else t(null)})),this.length=e=>ne(this,void 0,void 0,(function*(){e&&e(null,(yield fe.count().catch(A))||0)})),this.set=(e,t,r)=>ne(this,void 0,void 0,(function*(){r=r||A;const i=Date.now()+se.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield fe.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(A))||[];s&&(o||(s.json=n,s.expired=i,yield s.save().catch(A))),r()})),this.loop=E(this.expired,3e4),this.loop.start()}}class Se{static create(e){return ne(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{id:t}=e,r=O(),i=yield ae.create({secret:r,userId:t}).catch(Se.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:$({id:t,secret:r},Ee.token,Se.options())}}))}static destroy(e){return ne(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){Ie.error(e.message,"api.token",se.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:se.API_TOKEN_LIFETIME+"ms"}}static renew(e){return ne(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{error:t,decode:r}=Se.verify(e,se.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield he.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const i=yield ae.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(i&&!i.logout){i.secret=O(),yield i.save().catch(Se.error);return{auth:i,token:$({id:e,secret:i.secret},Ee.token,Se.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return ne(this,void 0,void 0,(function*(){const{error:t,decode:r}=Se.verify(e);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield he.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const e=yield ae.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ae.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:J(e,Ae.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class Te extends e{constructor(e){super(e,{cert:Ae.http,cross:se.API_HTTP_CROSS,hybrid:se.API_HTTP_HYBRID,key:Ee.http,notfound:se.API_NOTFOUND_REDIRECT,path:se.API_DEFAULT_PATH,port:se.API_HTTP_PORT,public:se.API_HTTP_PUBLIC,redirect:se.API_HTTP_REDIRECT,session:{store:new Oe,name:se.API_SESSION_NAME,secret:se.API_SESSION_SECRET,cookie:{maxAge:se.API_SESSION_LIFETIME},genid:O}})}error(e,t){Ie.info(e.message,t,se.API_CONSOLE_ERROR)}log(e,t){Ie.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return ne(this,void 0,void 0,(function*(){yield de.sync(),yield e.listen.call(this),se.API_WEBSOCKET_START&&this.server&&(this._webSocket=new k.Server({server:this.server,verifyClient:(e,t)=>t(se.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>ne(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=>ne(this,void 0,void 0,(function*(){if(i)try{const s=JSON.parse(n);this.emit("ws.message"+r,{data:s,message:n,req:t,user:i,ws:e})}catch(s){this.emit("ws.message"+r,{message:n,req:t,user:i,ws:e})}else{const{user:s}=yield Se.user(n.toString());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 ne(this,void 0,void 0,(function*(){const e=yield ye.findAll().catch(we.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return ne(this,void 0,void 0,(function*(){return((yield ye.destroy({where:{key:e}}).catch(we.error))||0)>0}))}static error(e){Ie.error(e.message,"api.config",se.API_CONSOLE_ERROR)}static get(e,t=""){return ne(this,void 0,void 0,(function*(){const r=yield ye.findOne({where:{key:e}}).catch(we.error);return r?r.value:t}))}static set(e,t){return ne(this,void 0,void 0,(function*(){const[r]=(yield ye.findOrCreate({where:{key:e}}).catch(we.error))||[];r&&(r.value=t,yield r.save().catch(we.error))}))}}const Re=t((({req:e})=>e.auth)),Ne=t((({req:e})=>T(e.files))),be=t((({req:e})=>e.user));class De{static all(e,t){return ne(this,void 0,void 0,(function*(){return yield ge.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:le,required:!0,include:[{model:ce,required:!0,where:{state:!0},include:[{model:me,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{Ie.error(e.message,"api.permission",se.API_CONSOLE_ERROR)}))}))}static get(e){return ne(this,void 0,void 0,(function*(){const t=yield De.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return ne(this,void 0,void 0,(function*(){const r=yield De.all(e,{name:t});return!!r&&r.length>0}))}}class xe extends w{constructor(){super(...arguments),this._uploads=R()}auth(e,t,r){return ne(this,void 0,void 0,(function*(){const{auth:i,error:n,user:s}=yield Se.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 ne(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(A):(r.useragent=t,r.save(A))),e.next()}))}error(e){Ie.error(e.message,"api.controller",se.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return ne(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 ne(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=O()+"."+t;return M(Q(e,r))?this.uploadFile(e,t):r}uploadMiddleware(e){const t=(null==e?void 0:e.path)||se.API_UPLOAD_TEMP,r=V.diskStorage({destination:(e,r,i)=>i(null,t),filename:(e,r,i)=>ne(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=V({storage:r,fileFilter(e,t,r){return ne(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)||se.API_UPLOAD_SIZE)}});return n.array((null==e?void 0:e.field)||se.API_UPLOAD_FIELD,(null==e?void 0:e.count)||se.API_UPLOAD_COUNT)}validation(e,t){return ne(this,void 0,void 0,(function*(){const{error:r,value:i}=yield N.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r),e.close();e.req.body=i,e.next()}))}write(e,t,r){return ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}te([re(0,r()),re(1,i(se.API_TOKEN_HEADER)),re(2,i("user-agent")),ie("design:type",Function),ie("design:paramtypes",[o,String,String]),ie("design:returntype",Promise)],xe.prototype,"auth",null),te([re(0,r()),re(1,i("user-agent")),re(2,n()),ie("design:type",Function),ie("design:paramtypes",[o,String,Object]),ie("design:returntype",Promise)],xe.prototype,"session",null),te([re(0,r()),re(1,s()),re(2,be()),ie("design:type",Function),ie("design:paramtypes",[o,String,he]),ie("design:returntype",Promise)],xe.prototype,"permission",null),te([re(0,r()),re(1,s()),re(2,be()),ie("design:type",Function),ie("design:paramtypes",[o,String,he]),ie("design:returntype",Promise)],xe.prototype,"read",null),te([re(0,r()),re(1,s()),ie("design:type",Function),ie("design:paramtypes",[o,Object]),ie("design:returntype",void 0)],xe.prototype,"upload",null),te([re(0,r()),re(1,s()),ie("design:type",Function),ie("design:paramtypes",[o,Object]),ie("design:returntype",Promise)],xe.prototype,"validation",null),te([re(0,r()),re(1,s()),re(2,be()),ie("design:type",Function),ie("design:paramtypes",[o,String,he]),ie("design:returntype",Promise)],xe.prototype,"write",null);let Fe=class extends xe{login(e,t,r,i,n){return ne(this,void 0,void 0,(function*(){yield S(se.API_SLEEP_AUTH);const s=r,o=yield he.findOne({where:{[K.or]:[{email:s},{username:r}],[K.and]:[{password:ee(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 pe.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 Se.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 ne(this,void 0,void 0,(function*(){if(yield Se.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 ne(this,void 0,void 0,(function*(){const{auth:n,error:s,token:o}=yield Se.renew(r);return s?e.error(s):n?(n.useragent=t,yield n.save().catch(this.error),e.json({token:o}),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 ne(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))}))}))}};te([d("/login"),a("validation",{username:N.string().min(3).required(),password:N.string().min(5).required()}),re(0,r()),re(1,i("user-agent")),re(2,u("username")),re(3,u("password")),re(4,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,String,String,Te]),ie("design:returntype",Promise)],Fe.prototype,"login",null),te([l("/logout"),a("auth"),re(0,r()),re(1,Re()),re(2,be()),re(3,c()),ie("design:type",Function),ie("design:paramtypes",[o,ae,he,Te]),ie("design:returntype",Promise)],Fe.prototype,"logout",null),te([d("/renew"),a("validation",{token:N.string().required()}),re(0,r()),re(1,i("user-agent")),re(2,u("token")),re(3,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,String,Te]),ie("design:returntype",Promise)],Fe.prototype,"renew",null),te([l(),a("auth"),re(0,r()),re(1,be()),ie("design:type",Function),ie("design:paramtypes",[o,he]),ie("design:returntype",Promise)],Fe.prototype,"user",null),Fe=te([p("/auth"),g(xe)],Fe);let qe=class extends xe{directory(){return se.API_HTTP_PUBLIC||"./"}files(e){return ne(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=Q(this.directory(),t);if(!M(r)||!G(r).isDirectory())return e.status(h.NOT_FOUND),{message:"Path not Found"};let i=[];return i=z(r),i=i.map((e=>this.info(Q(r,e)))),i=i.filter(b),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r){return ne(this,void 0,void 0,(function*(){yield this.permission(e,"files_"+this.name()+"."+t,r)}))}info(e){if(!M(e))return null;const t=G(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()}}};te([l("/path/?*"),a("auth"),a("access","list"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],qe.prototype,"files",null),te([re(0,r()),re(1,s()),re(2,be()),ie("design:type",Function),ie("design:paramtypes",[o,String,he]),ie("design:returntype",Promise)],qe.prototype,"access",null),qe=te([p("/files"),g(xe)],qe);let Be=class extends xe{check(e,t){return ne(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.json({token:r.token})}))}forgot(e,t,r){return ne(this,void 0,void 0,(function*(){yield S(se.API_SLEEP_FORGOT);const i=t,n=yield he.findOne({where:{[K.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=D(),o=Date.now()+6e4*se.API_TOKEN_FORGOT,d=yield ue.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 ne(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=ee(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 ne(this,void 0,void 0,(function*(){return yield ue.findOne({where:{token:e,state:!0},include:[{model:he,required:!0}]}).catch(this.error)}))}};te([l("/check"),a("validation",{token:N.string().required()}),re(0,r()),re(1,u("token")),ie("design:type",Function),ie("design:paramtypes",[o,String]),ie("design:returntype",Promise)],Be.prototype,"check",null),te([d(),a("validation",{username:N.string().min(4).required()}),re(0,r()),re(1,u("username")),re(2,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,Te]),ie("design:returntype",Promise)],Be.prototype,"forgot",null),te([d("/reset"),a("validation",{token:N.string().required(),password:N.string().min(5).required()}),re(0,r()),re(1,u("token")),re(2,u("password")),re(3,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,String,Te]),ie("design:returntype",Promise)],Be.prototype,"reset",null),Be=te([p("/forgot"),g(xe)],Be);let ke=class extends xe{constructor(){super(...arguments),this._columns=[]}_add({ctx:e,options:t,body:r}){return ne(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.json({[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all({ctx:e,options:t,callback:r}){var i,n,s,o,d;return ne(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(F(t)&&(f&&f.length&&y.push({[t]:{[K.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]:{[K.like]:`%${i}%`}})}})),y.length&&(u.where=Object.assign(Object.assign({},u.where),{[K.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.json({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 ne(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?Ie.error(e.message+"\n"+e.sql,"api.controller.sql",se.API_CONSOLE_ERROR):super.error(e)}_get({ctx:e,options:t,callback:r}){return ne(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);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({ctx:e,options:t,body:r}){return ne(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)}))}};ke=te([g(xe)],ke);let Le=class extends ke{create(){return{}}add(e){return ne(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return ne(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return ne(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return ne(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return ne(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}};te([d(),a("auth"),a("write"),a("validationAdd"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"add",null),te([l(),a("auth"),a("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"all",null),te([m("/:id"),a("auth"),a("write"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"del",null),te([l("/:id"),a("auth"),a("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"get",null),te([y("/:id"),a("auth"),a("write"),a("validationSet"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"set",null),te([re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"validationAdd",null),te([re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Le.prototype,"validationSet",null),Le=te([g(ke)],Le);let je=class extends Le{model(){return ce}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};je=te([p("/groups"),g(Le)],je);let Ce=class extends ke{model(){return le}all(e,t){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:ge,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r){return ne(this,void 0,void 0,(function*(){const i=yield ce.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield le.destroy({where:{groupId:t}}),r){let e=0;for(let i=0;i<r.length;i++)e=yield ge.count({where:{id:r[i]}}),e&&(yield le.create({groupId:t,routeId:r[i]}))}return e.success("OK")}if(q(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};te([l("/:id/routes"),a("auth"),a("read","groups"),re(0,r()),re(1,_("id")),ie("design:type",Function),ie("design:paramtypes",[o,String]),ie("design:returntype",Promise)],Ce.prototype,"all",null),te([y("/:id/routes"),a("auth"),a("write","groups"),a("validation",{routes:N.array(N.number().parse())}),re(0,r()),re(1,_("id")),re(2,u("routes")),ie("design:type",Function),ie("design:paramtypes",[o,String,Array]),ie("design:returntype",Promise)],Ce.prototype,"set",null),Ce=te([p("/groups"),g(ke)],Ce);let Ke=class extends ke{model(){return _e}all(e,t,r){return ne(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"]]}})}))}};te([l(),a("auth"),a("read"),re(0,r()),re(1,f("type")),re(2,f("source")),ie("design:type",Function),ie("design:paramtypes",[o,String,String]),ie("design:returntype",Promise)],Ke.prototype,"all",null),Ke=te([p("/logs"),g(ke)],Ke);let He=class extends xe{register(e,t,r){return ne(this,void 0,void 0,(function*(){yield S(se.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=ee(d).toString();if(yield he.count({where:{[K.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=ee(a).toString())return e.error("Invalid password");const l=yield he.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 pe.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 ne(this,void 0,void 0,(function*(){const i=yield pe.findOne({where:{token:t,state:!0},include:[{model:he,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 ne(this,void 0,void 0,(function*(){const i=t,n=yield pe.findOne({where:{state:!0},include:[{model:he,required:!0,where:{[K.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 ne(this,void 0,void 0,(function*(){const e=O();return(yield pe.count({where:{token:e}}))?this.getId():e}))}};te([d(),a("validation",{name:N.string().required(),date:N.string().date().required(),email:N.string().email().required(),username:N.string().min(4).empty(),password:N.string().min(5).required(),confirm:N.string().min(5).required()}),re(0,r()),re(1,u()),re(2,c()),ie("design:type",Function),ie("design:paramtypes",[o,Object,Te]),ie("design:returntype",Promise)],He.prototype,"register",null),te([d("/confirm"),a("validation",{token:N.string().required()}),re(0,r()),re(1,u("token")),re(2,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,Te]),ie("design:returntype",Promise)],He.prototype,"confirm",null),te([d("/send"),a("validation",{username:N.string().min(4).required()}),re(0,r()),re(1,u("username")),re(2,c()),ie("design:type",Function),ie("design:paramtypes",[o,String,Te]),ie("design:returntype",Promise)],He.prototype,"send",null),He=te([p("/register"),g(xe)],He);let Me=class extends Le{model(){return ge}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};Me=te([p("/routes"),g(Le)],Me);let Ue=class extends xe{setup(e){return ne(this,void 0,void 0,(function*(){if(0==(yield he.count())){const e={description:"",state:!0},t=yield he.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),r=yield ce.create(Object.assign({name:"admin"},e));yield me.create({userId:t.id,groupId:r.id});const i=["read","write"],n=["users","groups","routes"];yield B(n,(t=>ne(this,void 0,void 0,(function*(){yield B(i,(i=>ne(this,void 0,void 0,(function*(){const n=t+"."+i,s=yield ge.create(Object.assign({name:n},e));yield le.create({groupId:r.id,routeId:s.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield B(s,(t=>ne(this,void 0,void 0,(function*(){const i="files_api."+t,n=yield ge.create(Object.assign({name:i},e));yield le.create({groupId:r.id,routeId:n.id})}))));const o=yield ge.create(Object.assign({name:"logs.read"},e));yield le.create({groupId:r.id,routeId:o.id})}e.success("OK")}))}};te([l(),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Ue.prototype,"setup",null),Ue=te([p("/setup"),g(xe)],Ue);let Ge=class extends ke{model(){return he}constructor(){super(),this.dir=se.API_HTTP_PUBLIC+"/avatar",se.API_HTTP_PUBLIC&&M(se.API_HTTP_PUBLIC)&&!M(this.dir)&&X(this.dir)}avatar(e,t){return ne(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=se.API_HTTP_PUBLIC+"/avatar/";if(M(i+t.avatar)&&Y(i+t.avatar).isFile()&&W(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 ne(this,void 0,void 0,(function*(){const n=yield he.scope("password").findOne({where:{id:i.id,password:ee(t).toString(),state:!0}}).catch(this.error);return n?(n.password=ee(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 ne(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:ee(t).toString()}})}))}all(e){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return ne(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return ne(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:t?{password:ee(t).toString()}:{}})}))}};te([d("/avatar"),a("auth"),a("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:20}))),re(0,r()),re(1,be()),ie("design:type",Function),ie("design:paramtypes",[o,he]),ie("design:returntype",Promise)],Ge.prototype,"avatar",null),te([d("/password"),a("auth"),a("validation",{oldPassword:N.string().min(5).required(),newPassword:N.string().min(5).required()}),re(0,r()),re(1,u("oldPassword")),re(2,u("newPassword")),re(3,be()),ie("design:type",Function),ie("design:paramtypes",[o,String,String,he]),ie("design:returntype",Promise)],Ge.prototype,"password",null),te([d(),a("auth"),a("write"),a("validation",{name:N.string().required(),email:N.string().email().required(),username:N.string().min(4).required(),password:N.string().min(5).required(),description:N.string().empty(""),state:N.boolean().parse().required()}),re(0,r()),re(1,u("password")),ie("design:type",Function),ie("design:paramtypes",[o,String]),ie("design:returntype",Promise)],Ge.prototype,"add",null),te([l(),a("auth"),a("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Ge.prototype,"all",null),te([m("/:id"),a("auth"),a("write"),re(0,r()),re(1,be()),re(2,_("id")),ie("design:type",Function),ie("design:paramtypes",[o,he,String]),ie("design:returntype",Promise)],Ge.prototype,"del",null),te([l("/:id"),a("auth"),a("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[o]),ie("design:returntype",Promise)],Ge.prototype,"get",null),te([y("/:id"),a("auth"),a("write"),a("validation",{name:N.string().empty(),email:N.string().email().empty(),username:N.string().min(4).empty(),password:N.string().min(5).empty().filter(""),description:N.string().empty(),state:N.boolean().parse().empty()}),re(0,r()),re(1,u("password")),ie("design:type",Function),ie("design:paramtypes",[o,String]),ie("design:returntype",Promise)],Ge.prototype,"set",null),Ge=te([p("/users"),g(ke),ie("design:paramtypes",[])],Ge);let ze=class extends ke{model(){return me}all(e,t){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:ce,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r){return ne(this,void 0,void 0,(function*(){const i=yield he.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield me.destroy({where:{userId:i.id}}),r){let e=0;for(let t=0;t<r.length;t++)e=yield ce.count({where:{id:r[t]}}),e&&(yield me.create({userId:i.id,groupId:r[t]}))}return e.success("OK")}if(q(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};te([l("/:id/groups"),a("auth"),a("read","users"),re(0,r()),re(1,_("id")),ie("design:type",Function),ie("design:paramtypes",[o,String]),ie("design:returntype",Promise)],ze.prototype,"all",null),te([y("/:id/groups"),a("auth"),a("write","users"),a("validation",{groups:N.array(N.number().parse())}),re(0,r()),re(1,_("id")),re(2,u("groups")),ie("design:type",Function),ie("design:paramtypes",[o,String,Array]),ie("design:returntype",Promise)],ze.prototype,"set",null),ze=te([p("/users"),g(ke)],ze);export{Te as Application,ae as Auth,Fe as AuthController,we as Config,ye as Configs,xe as ControllerBase,Le as CrudController,oe as Database,se as Env,qe as FilesController,ue as Forgot,Be as ForgotController,ce as Group,le as GroupRoute,je as GroupsController,Ce as GroupsRoutesController,_e as Log,Ie as Logs,ve as LogsColor,Ke as LogsController,ke as ModelController,De as Permission,pe as Register,He as RegisterController,Re as ReqAuth,Ne as ReqFiles,be as ReqUser,ge as Route,Me as RoutesController,fe as Session,Ue as SetupController,Se as Token,he as User,me as UserGroup,Ge as UsersController,ze as UsersGroupsController,Ae as crt,Ee as key,de as sequelize};
|
|
7
|
+
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,Session as n,Argument as s,Upload 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 I,Query as f,Files as v}from"@andrewcaires/express";import{toBool as P,parseMs as A,noop as E,loop as O,uuidv4 as S,sleep as T,EventEmitter 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,sha256 as U}from"@andrewcaires/node";import{existsSync as G,readFileSync as z,statSync as X,readdirSync as Y,mkdirSync as W,lstatSync as Z,rmSync as J}from"fs";import{Store as $}from"express-session";import{verify as V,sign as Q}from"jsonwebtoken";import{join as ee}from"path";function te(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 re(e,t){return function(r,i){t(r,i,e)}}function ie(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function ne(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 se{static getBool(e,t){return P(se.getString(e,t.toString()))}static getInt(e,t){return parseInt(se.getString(e,t.toString()))}static getMs(e,t){return A(se.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}se.API_CONSOLE_ERROR=se.getBool("API_CONSOLE_ERROR",!1),se.API_DEFAULT_PATH=se.getString("API_DEFAULT_PATH","/api"),se.API_DB_DATABASE=se.getString("API_DB_DATABASE",""),se.API_DB_HOST=se.getString("API_DB_HOST","127.0.0.1"),se.API_DB_PASSWORD=se.getString("API_DB_PASSWORD",""),se.API_DB_PORT=se.getInt("API_DB_PORT",3306),se.API_DB_TYPE=se.getString("API_DB_TYPE",""),se.API_DB_USERNAME=se.getString("API_DB_USERNAME","root"),se.API_DB_LOG=se.getBool("API_DB_LOG",!1),se.API_DB_PREFIX=se.getString("API_DB_PREFIX",""),se.API_DB_TIMEZONE=se.getString("API_DB_TIMEZONE","+00:00"),se.API_HTTP_CRT=se.getString("API_HTTP_CRT",""),se.API_HTTP_KEY=se.getString("API_HTTP_KEY",""),se.API_HTTP_PORT=se.getInt("API_HTTP_PORT",3e3),se.API_HTTP_PUBLIC=se.getString("API_HTTP_PUBLIC",""),se.API_HTTP_CROSS=se.getBool("API_HTTP_CROSS",!1),se.API_HTTP_HYBRID=se.getBool("API_HTTP_HYBRID",!1),se.API_HTTP_REDIRECT=se.getString("API_HTTP_REDIRECT",""),se.API_NOTFOUND_REDIRECT=se.getString("API_NOTFOUND_REDIRECT",""),se.API_SLEEP_AUTH=se.getMs("API_SLEEP_AUTH","2s"),se.API_SLEEP_FORGOT=se.getMs("API_SLEEP_FORGOT","5s"),se.API_SLEEP_REGISTRY=se.getMs("API_SLEEP_REGISTRY","5s"),se.API_SESSION_NAME=se.getString("API_SESSION_NAME","session.id"),se.API_SESSION_LIFETIME=se.getMs("API_SESSION_LIFETIME","1d"),se.API_SESSION_SECRET=se.getString("API_SESSION_SECRET","yoursecret"),se.API_TOKEN_CRT=se.getString("API_TOKEN_CRT",""),se.API_TOKEN_KEY=se.getString("API_TOKEN_KEY",""),se.API_TOKEN_FORGOT=se.getMs("API_TOKEN_LIFETIME","1d"),se.API_TOKEN_HEADER=se.getString("API_TOKEN_HEADER","authorization"),se.API_TOKEN_LIFETIME=se.getMs("API_TOKEN_LIFETIME","1d"),se.API_TOKEN_RENEW=se.getMs("API_TOKEN_RENEW","1d"),se.API_UPLOAD_COUNT=se.getInt("API_UPLOAD_COUNT",1),se.API_UPLOAD_FIELD=process.env.API_UPLOAD_FIELD||"upload",se.API_UPLOAD_SIZE=se.getInt("API_UPLOAD_SIZE",2),se.API_UPLOAD_TEMP=se.getString("API_UPLOAD_TEMP","./temp"),se.API_WEBSOCKET_START=se.getBool("API_WEBSOCKET_START",!1);class oe{static connect(e){const t="connect_"+se.API_DB_TYPE.toLowerCase();if(t in oe)return oe[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:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_memory(){return new k("sqlite::memory:",{logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.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:se.API_DB_LOG,define:{timestamps:!1},timezone:se.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:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}static connect_sqlite(e){return new k({dialect:"sqlite",storage:e.database,logging:se.API_DB_LOG,define:{timestamps:!1},timezone:se.API_DB_TIMEZONE})}}const de=oe.connect({database:se.API_DB_DATABASE,username:se.API_DB_USERNAME,password:se.API_DB_PASSWORD,hostname:se.API_DB_HOST,hostport:se.API_DB_PORT});class ae extends j{}ae.init({secret:L.STRING,logout:L.DATE,useragent:L.STRING},{sequelize:de,modelName:se.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ue extends j{}ue.init({token:L.STRING,timestamp:L.BIGINT,state:L.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends j{}ce.init({name:L.STRING,description:L.TEXT,state:L.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends j{}le.init({},{sequelize:de,modelName:se.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),le.removeAttribute("id");class pe extends j{}pe.init({token:L.STRING,state:L.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ge extends j{}ge.init({name:L.STRING,description:L.TEXT,state:L.BOOLEAN},{sequelize:de,modelName:se.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends j{}he.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:de,modelName:se.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password"]}},scopes:{password:{attributes:{include:["password"]}}}});class me extends j{}me.init({},{sequelize:de,modelName:se.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),me.removeAttribute("id");class ye extends j{}ye.init({key:L.STRING,value:L.STRING},{sequelize:de,modelName:se.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),ye.removeAttribute("id");class _e extends j{}_e.init({type:L.STRING,source:L.STRING,message:L.TEXT},{sequelize:de,modelName:se.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:de,modelName:se.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),Ie.removeAttribute("id"),he.hasMany(ae),ae.belongsTo(he),he.hasMany(ue),ue.belongsTo(he),he.hasMany(pe),pe.belongsTo(he),ce.hasMany(le),le.belongsTo(ce),ge.hasMany(le),le.belongsTo(ge),he.hasMany(me),me.belongsTo(he),ce.hasMany(me),me.belongsTo(ce);class fe{static write(e,t,r){return ne(this,void 0,void 0,(function*(){yield fe.writeRaw(H.White,"",e,t,r)}))}static error(e,t,r){return ne(this,void 0,void 0,(function*(){yield fe.writeRaw(H.Red,"error",e,t,r)}))}static info(e,t,r){return ne(this,void 0,void 0,(function*(){yield fe.writeRaw(H.Cyan,"info",e,t,r)}))}static success(e,t,r){return ne(this,void 0,void 0,(function*(){yield fe.writeRaw(H.Green,"success",e,t,r)}))}static warning(e,t,r){return ne(this,void 0,void 0,(function*(){yield fe.writeRaw(H.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return ne(this,void 0,void 0,(function*(){n&&M.console(e,t,r),de&&(yield _e.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const ve=e=>G(e)?z(e):void 0,Pe={http:ve(se.API_HTTP_CRT),token:ve(se.API_TOKEN_CRT)},Ae={http:ve(se.API_HTTP_KEY),token:ve(se.API_TOKEN_KEY)};class Ee extends ${constructor(){super(),this.all=e=>ne(this,void 0,void 0,(function*(){e=e||E;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=>ne(this,void 0,void 0,(function*(){yield Ie.destroy().catch(E),e&&e()})),this.destroy=(e,t)=>ne(this,void 0,void 0,(function*(){yield Ie.destroy({where:{session:e}}).catch(E),t&&t()})),this.expired=()=>ne(this,void 0,void 0,(function*(){yield Ie.destroy({where:{expired:{[C.lt]:Date.now()}}}).catch(E)})),this.get=(e,t)=>ne(this,void 0,void 0,(function*(){t=t||E;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(E),void t(null)}t(null,e)}else t(null)})),this.length=e=>ne(this,void 0,void 0,(function*(){e&&e(null,(yield Ie.count().catch(E))||0)})),this.set=(e,t,r)=>ne(this,void 0,void 0,(function*(){r=r||E;const i=Date.now()+se.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield Ie.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 Oe{static create(e){return ne(this,void 0,void 0,(function*(){if(!Ae.token)return{error:"Key not found"};const{id:t}=e,r=S(),i=yield ae.create({secret:r,userId:t}).catch(Oe.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:Q({id:t,secret:r},Ae.token,Oe.options())}}))}static destroy(e){return ne(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){fe.error(e.message,"api.token",se.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:se.API_TOKEN_LIFETIME+"ms"}}static renew(e){return ne(this,void 0,void 0,(function*(){if(!Ae.token)return{error:"Key not found"};const{error:t,decode:r}=Oe.verify(e,se.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield he.findOne({where:{id:e,state:!0}}).catch(Oe.error);if(r){const i=yield ae.findOne({where:{secret:t,userId:r.id}}).catch(Oe.error);if(i&&!i.logout){i.secret=S(),yield i.save().catch(Oe.error);return{auth:i,token:Q({id:e,secret:i.secret},Ae.token,Oe.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e){return ne(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 he.findOne({where:{id:e,state:!0}}).catch(Oe.error);if(r){const e=yield ae.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(!Pe.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:V(e,Pe.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class Se extends e{constructor(e){super(e,{cert:Pe.http,cross:se.API_HTTP_CROSS,hybrid:se.API_HTTP_HYBRID,key:Ae.http,notfound:se.API_NOTFOUND_REDIRECT,path:se.API_DEFAULT_PATH,port:se.API_HTTP_PORT,public:se.API_HTTP_PUBLIC,redirect:se.API_HTTP_REDIRECT,session:{store:new Ee,name:se.API_SESSION_NAME,secret:se.API_SESSION_SECRET,cookie:{maxAge:se.API_SESSION_LIFETIME},genid:S}})}error(e,t){fe.info(e.message,t,se.API_CONSOLE_ERROR)}log(e,t){fe.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return ne(this,void 0,void 0,(function*(){yield de.sync(),yield e.listen.call(this),se.API_WEBSOCKET_START&&this.server&&(this._webSocket=new B.Server({server:this.server,verifyClient:(e,t)=>t(se.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>ne(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=>ne(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 T(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class Te{static all(){return ne(this,void 0,void 0,(function*(){const e=yield ye.findAll().catch(Te.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return ne(this,void 0,void 0,(function*(){return((yield ye.destroy({where:{key:e}}).catch(Te.error))||0)>0}))}static error(e){fe.error(e.message,"api.config",se.API_CONSOLE_ERROR)}static get(e){return ne(this,arguments,void 0,(function*(e,t=""){const r=yield ye.findOne({where:{key:e}}).catch(Te.error);return r?r.value:t}))}static set(e,t){return ne(this,void 0,void 0,(function*(){const[r]=(yield ye.findOrCreate({where:{key:e}}).catch(Te.error))||[];r&&(r.value=t,yield r.save().catch(Te.error))}))}}const we=t((({ctx:e})=>e.req.auth)),Re=t((({ctx:e})=>e.req.user));class be{static all(e,t){return ne(this,void 0,void 0,(function*(){return yield ge.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:le,required:!0,include:[{model:ce,required:!0,where:{state:!0},include:[{model:me,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{fe.error(e.message,"api.permission",se.API_CONSOLE_ERROR)}))}))}static get(e){return ne(this,void 0,void 0,(function*(){const t=yield be.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return ne(this,void 0,void 0,(function*(){const r=yield be.all(e,{name:t});return!!r&&r.length>0}))}}class Ne extends w{auth(e,t,r){return ne(this,void 0,void 0,(function*(){const{auth:i,error:n,user:s}=yield Oe.user(t);return n?e.error(n):i&&s?i.useragent!=r?e.error("Invalid token"):(e.req.auth=i,e.req.user=s,void e.next()):e.error("Internal Server Error")}))}session(e,t,r){return ne(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(E):(r.useragent=t,r.save(E))),e.next()}))}error(e){fe.error(e.message,"api.controller",se.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return ne(this,void 0,void 0,(function*(){return r?(yield be.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){t.path||(t.path=se.API_UPLOAD_TEMP),t.size||(t.size=se.API_UPLOAD_SIZE),t.field||(t.field=se.API_UPLOAD_FIELD),o.middleware(e,t)}validation(e,t){return ne(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.req.body=i,e.next()}))}write(e,t,r){return ne(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}te([re(0,r()),re(1,i(se.API_TOKEN_HEADER)),re(2,i("user-agent")),ie("design:type",Function),ie("design:paramtypes",[d,String,String]),ie("design:returntype",Promise)],Ne.prototype,"auth",null),te([re(0,r()),re(1,i("user-agent")),re(2,n()),ie("design:type",Function),ie("design:paramtypes",[d,String,Object]),ie("design:returntype",Promise)],Ne.prototype,"session",null),te([re(0,r()),re(1,s()),re(2,Re()),ie("design:type",Function),ie("design:paramtypes",[d,String,he]),ie("design:returntype",Promise)],Ne.prototype,"permission",null),te([re(0,r()),re(1,s()),re(2,Re()),ie("design:type",Function),ie("design:paramtypes",[d,String,he]),ie("design:returntype",Promise)],Ne.prototype,"read",null),te([re(0,r()),re(1,s()),ie("design:type",Function),ie("design:paramtypes",[d,Object]),ie("design:returntype",void 0)],Ne.prototype,"upload",null),te([re(0,r()),re(1,s()),ie("design:type",Function),ie("design:paramtypes",[d,Object]),ie("design:returntype",Promise)],Ne.prototype,"validation",null),te([re(0,r()),re(1,s()),re(2,Re()),ie("design:type",Function),ie("design:paramtypes",[d,String,he]),ie("design:returntype",Promise)],Ne.prototype,"write",null);let De=class extends Ne{login(e,t,r,i,n){return ne(this,void 0,void 0,(function*(){yield T(se.API_SLEEP_AUTH);const s=r,o=yield he.findOne({where:{[C.or]:[{email:s},{username:r}],[C.and]:[{password:U(i)}]}}).catch(this.error);if(!o)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const d=yield pe.findOne({where:{state:!0,userId:o.id}}).catch(this.error);if(d)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:d,user:o}),void this.emit("auth.activation",{ctx:e,register:d,user:o});if(!o.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:c}=yield Oe.create(o);return u?(e.error(u),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&c?(a.useragent=t,yield a.save().catch(this.error),e.json({token:c}),n.emit("auth.login",{auth:a,ctx:e,user:o}),void this.emit("auth.login",{auth:a,ctx:e,user:o})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return ne(this,void 0,void 0,(function*(){if(yield Oe.destroy(t))return e.success("Disconcerted"),i.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,i){return ne(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}),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 ne(this,void 0,void 0,(function*(){const r=yield be.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};te([a("/login"),u("validation",{username:R.string().min(3).required(),password:R.string().min(5).required()}),re(0,r()),re(1,i("user-agent")),re(2,c("username")),re(3,c("password")),re(4,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,String,String,Se]),ie("design:returntype",Promise)],De.prototype,"login",null),te([p("/logout"),u("auth"),re(0,r()),re(1,we()),re(2,Re()),re(3,l()),ie("design:type",Function),ie("design:paramtypes",[d,ae,he,Se]),ie("design:returntype",Promise)],De.prototype,"logout",null),te([a("/renew"),u("validation",{token:R.string().required()}),re(0,r()),re(1,i("user-agent")),re(2,c("token")),re(3,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,String,Se]),ie("design:returntype",Promise)],De.prototype,"renew",null),te([p(),u("auth"),re(0,r()),re(1,Re()),ie("design:type",Function),ie("design:paramtypes",[d,he]),ie("design:returntype",Promise)],De.prototype,"user",null),De=te([g("/auth"),h(Ne)],De);let xe=class extends Ne{directory(){return se.API_HTTP_PUBLIC||"./"}files(e){return ne(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(!G(r)||!X(r).isDirectory())return e.notFound("Path not Found");let i=[];return i=Y(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 ne(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!G(e))return null;const t=X(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const i=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:i?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:i,symlink:t.isSymbolicLink()}}name(){return"files"}};te([p("/path/?*"),u("auth"),u("access","list"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],xe.prototype,"files",null),te([re(0,r()),re(1,s()),re(2,Re()),ie("design:type",Function),ie("design:paramtypes",[d,String,he]),ie("design:returntype",Promise)],xe.prototype,"access",null),xe=te([g("/files"),h(Ne)],xe);let Fe=class extends Ne{check(e,t){return ne(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 ne(this,void 0,void 0,(function*(){yield T(se.API_SLEEP_FORGOT);const i=t,n=yield he.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*se.API_TOKEN_FORGOT,d=yield ue.create({token:s,timestamp:o,state:!0,userId:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})}))}reset(e,t,r,i){return ne(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=U(r),yield n.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})}))}find(e){return ne(this,void 0,void 0,(function*(){return yield ue.findOne({where:{token:e,state:!0},include:[{model:he,required:!0}]}).catch(this.error)}))}};te([p("/check"),u("validation",{token:R.string().required()}),re(0,r()),re(1,c("token")),ie("design:type",Function),ie("design:paramtypes",[d,String]),ie("design:returntype",Promise)],Fe.prototype,"check",null),te([a(),u("validation",{username:R.string().min(4).required()}),re(0,r()),re(1,c("username")),re(2,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,Se]),ie("design:returntype",Promise)],Fe.prototype,"forgot",null),te([a("/reset"),u("validation",{token:R.string().required(),password:R.string().min(5).required()}),re(0,r()),re(1,c("token")),re(2,c("password")),re(3,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,String,Se]),ie("design:returntype",Promise)],Fe.prototype,"reset",null),Fe=te([g("/forgot"),h(Ne)],Fe);let qe=class extends Ne{constructor(){super(...arguments),this._columns=[]}_add(e){return ne(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),t||{}).catch(this.error);if(i){const t=this.key();return e.prepare(m.OK,{[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all(e){return ne(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 y=null===(o=e.req.query.desc)||void 0===o?void 0:o.toString();y&&y.length&&y.split(",").forEach((e=>{p.indexOf(e)>=0&&g.push([e,"DESC"])})),g.length&&(u.order=g);const _=[],I=D(u.attributes)?u.attributes:p,f=null===(d=e.req.query.search)||void 0===d?void 0:d.toString();I.forEach((t=>{var r;if(x(t)&&(f&&f.length&&_.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&&_.push({[t]:{[C.like]:`%${i}%`}})}})),_.length&&(u.where=Object.assign(Object.assign({},u.where),{[C.or]:[..._]}));const v=(yield a.count(Object.assign(Object.assign({},u),{col:p[0]})).catch(this.error))||0,P=yield a.findAll(u).catch(this.error);return P?(e.prepare(m.OK,{count:v,records:r?yield r(P):P}),[P,v]):(e.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return ne(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:i}=e.req.params;if(!i)return e.error("Internal Server Error"),0;const n=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i})})).catch(this.error);return n?(e.success("OK"),n):(e.notFound("Record not found"),0)}))}error(e){e.sql?fe.error(e.message+"\n"+e.sql,"api.controller.sql",se.API_CONSOLE_ERROR):super.error(e)}_get(e){return ne(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.prepare(m.OK,r?yield r(s):s.toJSON()),s):null===s?e.notFound("Record not found"):void e.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}_set(e){return ne(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=this.key(),{[i]:n}=e.req.params,[s]=(yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:n})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};qe=te([h(Ne)],qe);let Be=class extends qe{create(){return{}}add(e){return ne(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return ne(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return ne(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return ne(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return ne(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}};te([a(),u("auth"),u("write"),u("validationAdd"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"add",null),te([p(),u("auth"),u("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"all",null),te([y("/:id"),u("auth"),u("write"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"del",null),te([p("/:id"),u("auth"),u("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"get",null),te([_("/:id"),u("auth"),u("write"),u("validationSet"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"set",null),te([re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"validationAdd",null),te([re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Be.prototype,"validationSet",null),Be=te([h(qe)],Be);let ke=class extends Be{model(){return ce}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()}}};ke=te([g("/groups"),h(Be)],ke);let Le=class extends qe{model(){return le}all(e,t){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:ge,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r){return ne(this,void 0,void 0,(function*(){const i=yield ce.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield le.destroy({where:{groupId:t}}),r){let e=0;for(let i=0;i<r.length;i++)e=yield ge.count({where:{id:r[i]}}),e&&(yield le.create({groupId:t,routeId:r[i]}))}return e.success("OK")}if(F(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};te([p("/:id/routes"),u("auth"),u("read","groups"),re(0,r()),re(1,I("id")),ie("design:type",Function),ie("design:paramtypes",[d,String]),ie("design:returntype",Promise)],Le.prototype,"all",null),te([_("/:id/routes"),u("auth"),u("write","groups"),u("validation",{routes:R.array(R.number().parse())}),re(0,r()),re(1,I("id")),re(2,c("routes")),ie("design:type",Function),ie("design:paramtypes",[d,String,Array]),ie("design:returntype",Promise)],Le.prototype,"set",null),Le=te([g("/groups"),h(qe)],Le);let je=class extends qe{model(){return _e}all(e,t,r){return ne(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"]]}})}))}};te([p(),u("auth"),u("read"),re(0,r()),re(1,f("type")),re(2,f("source")),ie("design:type",Function),ie("design:paramtypes",[d,String,String]),ie("design:returntype",Promise)],je.prototype,"all",null),je=te([g("/logs"),h(qe)],je);let Ce=class extends Ne{register(e,t,r){return ne(this,void 0,void 0,(function*(){yield T(se.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=U(d);if(yield he.count({where:{[C.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=U(a))return e.error("Invalid password");const l=yield he.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 pe.create({token:yield this.getId(),userId:l.id,state:!0}).catch(this.error);if(!p)return l.destroy(),e.error("Internal Server Error");e.success("OK"),r.emit("register.user",{ctx:e,register:p,user:l}),this.emit("register.user",{ctx:e,register:p,user:l})}))}confirm(e,t,r){return ne(this,void 0,void 0,(function*(){const i=yield pe.findOne({where:{token:t,state:!0},include:[{model:he,required:!0}]}).catch(this.error);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})}))}send(e,t,r){return ne(this,void 0,void 0,(function*(){const i=t,n=yield pe.findOne({where:{state:!0},include:[{model:he,required:!0,where:{[C.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})}))}getId(){return ne(this,void 0,void 0,(function*(){const e=S();return(yield pe.count({where:{token:e}}))?this.getId():e}))}};te([a(),u("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()}),re(0,r()),re(1,c()),re(2,l()),ie("design:type",Function),ie("design:paramtypes",[d,Object,Se]),ie("design:returntype",Promise)],Ce.prototype,"register",null),te([a("/confirm"),u("validation",{token:R.string().required()}),re(0,r()),re(1,c("token")),re(2,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,Se]),ie("design:returntype",Promise)],Ce.prototype,"confirm",null),te([a("/send"),u("validation",{username:R.string().min(4).required()}),re(0,r()),re(1,c("username")),re(2,l()),ie("design:type",Function),ie("design:paramtypes",[d,String,Se]),ie("design:returntype",Promise)],Ce.prototype,"send",null),Ce=te([g("/register"),h(Ne)],Ce);let Ke=class extends Be{model(){return ge}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()}}};Ke=te([g("/routes"),h(Be)],Ke);let He=class extends Ne{setup(e){return ne(this,void 0,void 0,(function*(){if(0==(yield he.count())){const e={description:"API CORE",state:!0},t=yield he.create(Object.assign({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",avatar:""},e)),r=yield ce.create(Object.assign({name:"admin"},e));yield me.create({userId:t.id,groupId:r.id});const i=["read","write"],n=["users","groups","routes"];yield q(n,(t=>ne(this,void 0,void 0,(function*(){yield q(i,(i=>ne(this,void 0,void 0,(function*(){const n=t+"."+i,s=yield ge.create(Object.assign({name:n},e));yield le.create({groupId:r.id,routeId:s.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield q(s,(t=>ne(this,void 0,void 0,(function*(){const i="files."+t,n=yield ge.create(Object.assign({name:i},e));yield le.create({groupId:r.id,routeId:n.id})}))));const o=yield ge.create(Object.assign({name:"logs.read"},e));yield le.create({groupId:r.id,routeId:o.id})}e.success("OK")}))}};te([p(),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],He.prototype,"setup",null),He=te([g("/setup"),h(Ne)],He);let Me=class extends qe{model(){return he}constructor(){super(),this.dir=se.API_HTTP_PUBLIC+"/avatar",se.API_HTTP_PUBLIC&&G(se.API_HTTP_PUBLIC)&&!G(this.dir)&&W(this.dir)}avatar(e,t,r){return ne(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;if(G(t)&&Z(t).isFile()&&J(t),r.avatar=i,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}password(e,t,r,i){return ne(this,void 0,void 0,(function*(){const n=yield he.scope("password").findOne({where:{id:i.id,password:U(t),state:!0}}).catch(this.error);return n?(n.password=U(r),(yield n.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}add(e,t){return ne(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:U(t)}})}))}all(e){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return ne(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return ne(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return ne(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:t?{password:U(t)}:{}})}))}};te([a("/avatar"),u("auth"),u("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),re(0,r()),re(1,v()),re(2,Re()),ie("design:type",Function),ie("design:paramtypes",[d,Array,he]),ie("design:returntype",Promise)],Me.prototype,"avatar",null),te([a("/password"),u("auth"),u("validation",{oldPassword:R.string().min(5).required(),newPassword:R.string().min(5).required()}),re(0,r()),re(1,c("oldPassword")),re(2,c("newPassword")),re(3,Re()),ie("design:type",Function),ie("design:paramtypes",[d,String,String,he]),ie("design:returntype",Promise)],Me.prototype,"password",null),te([a(),u("auth"),u("write"),u("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()}),re(0,r()),re(1,c("password")),ie("design:type",Function),ie("design:paramtypes",[d,String]),ie("design:returntype",Promise)],Me.prototype,"add",null),te([p(),u("auth"),u("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Me.prototype,"all",null),te([y("/:id"),u("auth"),u("write"),re(0,r()),re(1,Re()),re(2,I("id")),ie("design:type",Function),ie("design:paramtypes",[d,he,String]),ie("design:returntype",Promise)],Me.prototype,"del",null),te([p("/:id"),u("auth"),u("read"),re(0,r()),ie("design:type",Function),ie("design:paramtypes",[d]),ie("design:returntype",Promise)],Me.prototype,"get",null),te([_("/:id"),u("auth"),u("write"),u("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()}),re(0,r()),re(1,c("password")),ie("design:type",Function),ie("design:paramtypes",[d,String]),ie("design:returntype",Promise)],Me.prototype,"set",null),Me=te([g("/users"),h(qe),ie("design:paramtypes",[])],Me);let Ue=class extends qe{model(){return me}all(e,t){return ne(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:ce,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r){return ne(this,void 0,void 0,(function*(){const i=yield he.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield me.destroy({where:{userId:i.id}}),r){let e=0;for(let t=0;t<r.length;t++)e=yield ce.count({where:{id:r[t]}}),e&&(yield me.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")}))}};te([p("/:id/groups"),u("auth"),u("read","users"),re(0,r()),re(1,I("id")),ie("design:type",Function),ie("design:paramtypes",[d,String]),ie("design:returntype",Promise)],Ue.prototype,"all",null),te([_("/:id/groups"),u("auth"),u("write","users"),u("validation",{groups:R.array(R.number().parse())}),re(0,r()),re(1,I("id")),re(2,c("groups")),ie("design:type",Function),ie("design:paramtypes",[d,String,Array]),ie("design:returntype",Promise)],Ue.prototype,"set",null),Ue=te([g("/users"),h(qe)],Ue);export{Se as Application,ae as Auth,De as AuthController,Te as Config,ye as Configs,Ne as ControllerBase,Be as CrudController,oe as Database,se as Env,xe as FilesController,ue as Forgot,Fe as ForgotController,ce as Group,le as GroupRoute,ke as GroupsController,Le as GroupsRoutesController,_e as Log,fe as Logs,je as LogsController,qe as ModelController,be as Permission,pe as Register,Ce as RegisterController,we as ReqAuth,Re as ReqUser,ge as Route,Ke as RoutesController,Ie as Session,He as SetupController,Oe as Token,he as User,me as UserGroup,Me as UsersController,Ue as UsersGroupsController,Pe as crt,Ae as key,de as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"main": "./dist/index.cjs.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -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,38 +45,31 @@
|
|
|
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.10",
|
|
49
|
+
"@andrewcaires/node": "^1.1.1",
|
|
50
|
+
"@andrewcaires/utils.js": "^0.3.1",
|
|
50
51
|
"cors": "^2.8.5",
|
|
51
|
-
"crypto-js": "^4.2.0",
|
|
52
52
|
"dotenv": "^16.4.5",
|
|
53
|
-
"express": "^4.19.2",
|
|
54
53
|
"express-session": "^1.18.0",
|
|
55
54
|
"jsonwebtoken": "^9.0.2",
|
|
56
55
|
"mariadb": "^3.3.1",
|
|
57
|
-
"multer": "^1.4.5-lts.1",
|
|
58
56
|
"mysql2": "^3.10.1",
|
|
59
57
|
"sequelize": "^6.37.3",
|
|
60
|
-
"ws": "^8.17.
|
|
58
|
+
"ws": "^8.17.1"
|
|
61
59
|
},
|
|
62
60
|
"devDependencies": {
|
|
63
61
|
"@rollup/plugin-commonjs": "^26.0.1",
|
|
64
62
|
"@rollup/plugin-terser": "^0.4.4",
|
|
65
63
|
"@rollup/plugin-typescript": "^11.1.6",
|
|
66
64
|
"@types/cors": "^2.8.17",
|
|
67
|
-
"@types/crypto-js": "^4.2.2",
|
|
68
|
-
"@types/express": "^4.17.21",
|
|
69
65
|
"@types/express-session": "^1.18.0",
|
|
70
66
|
"@types/jsonwebtoken": "^9.0.6",
|
|
71
|
-
"@types/
|
|
72
|
-
"@types/node": "^20.14.2",
|
|
67
|
+
"@types/node": "^20.14.5",
|
|
73
68
|
"@types/ws": "^8.5.10",
|
|
74
|
-
"
|
|
75
|
-
"@typescript-eslint/parser": "^7.13.0",
|
|
76
|
-
"eslint": "^8.57.0",
|
|
69
|
+
"eslint": "^9.5.0",
|
|
77
70
|
"rollup": "^4.18.0",
|
|
78
71
|
"rollup-plugin-dts": "^6.1.1",
|
|
79
|
-
"
|
|
80
|
-
"
|
|
72
|
+
"tslib": "^2.6.3",
|
|
73
|
+
"typescript-eslint": "^8.0.0-alpha.30"
|
|
81
74
|
}
|
|
82
|
-
}
|
|
75
|
+
}
|