@andrewcaires/api 3.2.0 → 3.2.1
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 +21 -7
- package/dist/index.esm.js +2 -2
- package/package.json +3 -3
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.2.
|
|
2
|
+
* @andrewcaires/api v3.2.1
|
|
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"),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;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/express"),t=require("@andrewcaires/node"),r=require("@andrewcaires/utils.js"),o=require("ws"),i=require("sequelize"),n=require("dotenv"),s=require("fs"),d=require("express-session"),a=require("jsonwebtoken"),l=require("path");function u(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}function c(e,t){return function(r,o){t(r,o,e)}}function p(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function g(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{a(o.next(e))}catch(e){n(e)}}function d(e){try{a(o.throw(e))}catch(e){n(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(s,d)}a((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,n.config();class h{static getBool(e,t){return r.toBool(h.getString(e,t.toString()))}static getInt(e,t){return parseInt(h.getString(e,t.toString()))}static getMs(e,t){return r.parseMs(h.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}h.API_CONSOLE_ERROR=h.getBool("API_CONSOLE_ERROR",!1),h.API_DEFAULT_PATH=h.getString("API_DEFAULT_PATH","/api"),h.API_DB_DATABASE=h.getString("API_DB_DATABASE",""),h.API_DB_HOST=h.getString("API_DB_HOST","127.0.0.1"),h.API_DB_PASSWORD=h.getString("API_DB_PASSWORD",""),h.API_DB_PORT=h.getInt("API_DB_PORT",3306),h.API_DB_TYPE=h.getString("API_DB_TYPE",""),h.API_DB_USERNAME=h.getString("API_DB_USERNAME","root"),h.API_DB_LOG=h.getBool("API_DB_LOG",!1),h.API_DB_PREFIX=h.getString("API_DB_PREFIX",""),h.API_DB_TIMEZONE=h.getString("API_DB_TIMEZONE","+00:00"),h.API_HTTP_CRT=h.getString("API_HTTP_CRT",""),h.API_HTTP_KEY=h.getString("API_HTTP_KEY",""),h.API_HTTP_PORT=h.getInt("API_HTTP_PORT",3e3),h.API_HTTP_PUBLIC=h.getString("API_HTTP_PUBLIC",""),h.API_HTTP_CROSS=h.getBool("API_HTTP_CROSS",!1),h.API_HTTP_HYBRID=h.getBool("API_HTTP_HYBRID",!1),h.API_HTTP_REDIRECT=h.getString("API_HTTP_REDIRECT",""),h.API_KEY_HASH=h.getString("API_KEY_HASH",""),h.API_KEY_HEADER=h.getString("API_KEY_HEADER","api_key"),h.API_NOTFOUND_REDIRECT=h.getString("API_NOTFOUND_REDIRECT",""),h.API_SLEEP_AUTH=h.getMs("API_SLEEP_AUTH","2s"),h.API_SLEEP_FORGOT=h.getMs("API_SLEEP_FORGOT","5s"),h.API_SLEEP_REGISTRY=h.getMs("API_SLEEP_REGISTRY","5s"),h.API_SESSION_NAME=h.getString("API_SESSION_NAME","session.id"),h.API_SESSION_LIFETIME=h.getMs("API_SESSION_LIFETIME","1d"),h.API_SESSION_SECRET=h.getString("API_SESSION_SECRET","yoursecret"),h.API_TOKEN_CRT=h.getString("API_TOKEN_CRT",""),h.API_TOKEN_KEY=h.getString("API_TOKEN_KEY",""),h.API_TOKEN_FORGOT=h.getMs("API_TOKEN_LIFETIME","1d"),h.API_TOKEN_HEADER=h.getString("API_TOKEN_HEADER","authorization"),h.API_TOKEN_LIFETIME=h.getMs("API_TOKEN_LIFETIME","1d"),h.API_TOKEN_RENEW=h.getMs("API_TOKEN_RENEW","1d"),h.API_UPLOAD_COUNT=h.getInt("API_UPLOAD_COUNT",1),h.API_UPLOAD_FIELD=h.getString("API_UPLOAD_FIELD","upload"),h.API_UPLOAD_SIZE=h.getInt("API_UPLOAD_SIZE",2),h.API_UPLOAD_TEMP=h.getString("API_UPLOAD_TEMP","./temp"),h.API_WEBSOCKET_START=h.getBool("API_WEBSOCKET_START",!1);class y{static connect(e){const t="connect_"+h.API_DB_TYPE.toLowerCase();if(t in y)return y[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new i.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 i.Sequelize("sqlite::memory:",{logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.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:h.API_DB_LOG,define:{timestamps:!1},timezone:h.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:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}static connect_sqlite(e){return new i.Sequelize({dialect:"sqlite",storage:e.database,logging:h.API_DB_LOG,define:{timestamps:!1},timezone:h.API_DB_TIMEZONE})}}const m=y.connect({database:h.API_DB_DATABASE,username:h.API_DB_USERNAME,password:h.API_DB_PASSWORD,hostname:h.API_DB_HOST,hostport:h.API_DB_PORT});class _ extends i.Model{}_.init({secret:i.DataTypes.STRING,logout:i.DataTypes.DATE,useragent:i.DataTypes.STRING},{sequelize:m,modelName:h.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:h.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class v extends i.Model{}v.init({name:i.DataTypes.STRING,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class P extends i.Model{}P.init({},{sequelize:m,modelName:h.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),P.removeAttribute("id");class f extends i.Model{}f.init({token:i.DataTypes.STRING,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class I extends i.Model{}I.init({name:i.DataTypes.STRING,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:h.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,token:i.DataTypes.STRING,avatar:i.DataTypes.STRING,date:i.DataTypes.DATEONLY,description:i.DataTypes.TEXT,state:i.DataTypes.BOOLEAN},{sequelize:m,modelName:h.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password","token"]}},scopes:{password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password"]}}}});class C extends i.Model{}C.init({},{sequelize:m,modelName:h.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:h.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:h.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class w extends i.Model{}w.init({session:i.DataTypes.STRING,json:i.DataTypes.TEXT,expired:i.DataTypes.BIGINT},{sequelize:m,modelName:h.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),w.removeAttribute("id"),A.hasMany(_),_.belongsTo(A),A.hasMany(x),x.belongsTo(A),A.hasMany(f),f.belongsTo(A),v.hasMany(P),P.belongsTo(v),I.hasMany(P),P.belongsTo(I),A.hasMany(C),C.belongsTo(A),v.hasMany(C),C.belongsTo(v);class T{static write(e,r,o){return g(this,void 0,void 0,(function*(){yield T.writeRaw(t.LogColor.White,"",e,r,o)}))}static error(e,r,o){return g(this,void 0,void 0,(function*(){yield T.writeRaw(t.LogColor.Red,"error",e,r,o)}))}static info(e,r,o){return g(this,void 0,void 0,(function*(){yield T.writeRaw(t.LogColor.Cyan,"info",e,r,o)}))}static success(e,r,o){return g(this,void 0,void 0,(function*(){yield T.writeRaw(t.LogColor.Green,"success",e,r,o)}))}static warning(e,r,o){return g(this,void 0,void 0,(function*(){yield T.writeRaw(t.LogColor.Yellow,"warning",e,r,o)}))}static writeRaw(e,r,o,i,n){return g(this,void 0,void 0,(function*(){n&&t.Log.console(e,r,o),m&&(yield S.create({type:r,source:i,message:o}).catch((()=>null)))}))}}const O=e=>s.existsSync(e)?s.readFileSync(e):void 0,R={http:O(h.API_HTTP_CRT),token:O(h.API_TOKEN_CRT)},D={http:O(h.API_HTTP_KEY),token:O(h.API_TOKEN_KEY)};class M extends d.Store{constructor(){super(),this.all=e=>g(this,void 0,void 0,(function*(){e=e||r.noop;const t=yield w.findAll({attributes:["session"],where:{expired:{[i.Op.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>g(this,void 0,void 0,(function*(){yield w.destroy().catch(r.noop),e&&e()})),this.destroy=(e,t)=>g(this,void 0,void 0,(function*(){yield w.destroy({where:{session:e}}).catch(r.noop),t&&t()})),this.expired=()=>g(this,void 0,void 0,(function*(){yield w.destroy({where:{expired:{[i.Op.lt]:Date.now()}}}).catch(r.noop)})),this.get=(e,t)=>g(this,void 0,void 0,(function*(){t=t||r.noop;const o=yield w.findOne({where:{session:e,expired:{[i.Op.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(o){const e=JSON.parse(o.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(r.noop),void t(null)}t(null,e)}else t(null)})),this.length=e=>g(this,void 0,void 0,(function*(){e&&e(null,(yield w.count().catch(r.noop))||0)})),this.set=(e,t,o)=>g(this,void 0,void 0,(function*(){o=o||r.noop;const i=Date.now()+h.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,d]=(yield w.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(r.noop))||[];s&&(d||(s.json=n,s.expired=i,yield s.save().catch(r.noop))),o()})),this.loop=r.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:t}=e,o=r.uuidv4(),i=yield _.create({secret:o,userId:t}).catch(b.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:a.sign({id:t,secret:o},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){T.error(e.message,"api.token",h.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:h.API_TOKEN_LIFETIME+"ms"}}static renew(e){return g(this,void 0,void 0,(function*(){if(!D.token)return{error:"Key not found"};const{error:t,decode:o}=b.verify(e,h.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(o){const{id:e,secret:t}=o;if(e&&t){const o=yield A.findOne({where:{id:e,state:!0}}).catch(b.error);if(o){const i=yield _.findOne({where:{secret:t,userId:o.id}}).catch(b.error);if(i&&!i.logout){i.secret=r.uuidv4(),yield i.save().catch(b.error);return{auth:i,token:a.sign({id:e,secret:i.secret},D.token,b.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return g(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const o=yield A.findOne({where:{token:t,state:!0}}).catch(b.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield _.findOrCreate({where:{secret:t,userId:o.id},defaults:{secret:t,userId:o.id}}).catch(b.error))||[];if(r)return{auth:r,user:o}}return{error:"Access denied"}}const{error:o,decode:i}=b.verify(t);if(o)return{error:o};if(i){const{id:e,secret:t}=i;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:h.API_HTTP_CROSS,hybrid:h.API_HTTP_HYBRID,key:D.http,notfound:h.API_NOTFOUND_REDIRECT,path:h.API_DEFAULT_PATH,port:h.API_HTTP_PORT,public:h.API_HTTP_PUBLIC,redirect:h.API_HTTP_REDIRECT,session:{store:new M,name:h.API_SESSION_NAME,secret:h.API_SESSION_SECRET,cookie:{maxAge:h.API_SESSION_LIFETIME},genid:r.uuidv4}}),this.hash=new t.Hash(h.API_KEY_HASH)}error(e,t){T.error(e.message,t,h.API_CONSOLE_ERROR)}log(e,t){T.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return g(this,void 0,void 0,(function*(){yield m.sync(),yield e.listen.call(this),h.API_WEBSOCKET_START&&this.server&&(this._webSocket=new o.Server({server:this.server,verifyClient:(e,t)=>t(h.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>g(this,void 0,void 0,(function*(){t.url||(t.url="");const o=t.url.length<=1?"":t.url.replace(/\//g,".");let i;e.on("message",(r=>g(this,void 0,void 0,(function*(){if(i)try{const n=JSON.parse(r);this.emit("ws.message"+o,{data:n,message:r,req:t,user:i,ws:e})}catch(n){this.emit("ws.message"+o,{message:r,req:t,user:i,ws:e})}else{const{user:n}=yield b.user("",r.toString(),this);n&&(i=n,this.emit("ws.connection"+o,{req:t,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+o,{user:i,ws:e})})),yield r.sleep(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class k{static all(){return g(this,void 0,void 0,(function*(){const e=yield E.findAll().catch(k.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return g(this,void 0,void 0,(function*(){return((yield E.destroy({where:{key:e}}).catch(k.error))||0)>0}))}static error(e){T.error(e.message,"api.config",h.API_CONSOLE_ERROR)}static get(e){return g(this,arguments,void 0,(function*(e,t=""){const r=yield E.findOne({where:{key:e}}).catch(k.error);return r?r.value:t}))}static set(e,t){return g(this,void 0,void 0,(function*(){const[r]=(yield E.findOrCreate({where:{key:e}}).catch(k.error))||[];r&&(r.value=t,yield r.save().catch(k.error))}))}}const N=e.parameterFactory((({ctx:e})=>e.req.auth)),q=e.parameterFactory((({ctx:e})=>e.req.user));class B{static all(e,t){return g(this,void 0,void 0,(function*(){return yield I.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:P,required:!0,include:[{model:v,required:!0,where:{state:!0},include:[{model:C,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{T.error(e.message,"api.permission",h.API_CONSOLE_ERROR)}))}))}static get(e){return g(this,void 0,void 0,(function*(){const t=yield B.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return g(this,void 0,void 0,(function*(){const r=yield B.all(e,{name:t});return!!r&&r.length>0}))}}class L extends r.EventEmitter{auth(e,t,r,o,i){return g(this,void 0,void 0,(function*(){const{auth:n,error:s,user:d}=yield b.user(t,r,i);return s?e.error(s):n&&d?n.useragent&&n.useragent!=o?e.error("Invalid token"):(e.req.auth=n,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,o){return g(this,void 0,void 0,(function*(){o.auth&&o.user&&(o.useragent?o.useragent!=t&&o.regenerate(r.noop):(o.useragent=t,o.save(r.noop))),e.next()}))}error(e){T.error(e.message,"api.controller",h.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return g(this,void 0,void 0,(function*(){return r?(yield B.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(t,r){r.path||(r.path=h.API_UPLOAD_TEMP),r.size||(r.size=h.API_UPLOAD_SIZE),r.field||(r.field=h.API_UPLOAD_FIELD),e.Upload.middleware(t,r)}validation(e,t){return g(this,void 0,void 0,(function*(){const{error:o,value:i}=yield r.Validation.object(t).parse().validateAsync(e.req.body);if(o)return e.validation(o);e.req.body=i,e.next()}))}write(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}u([c(0,e.Ctx()),c(1,e.Headers(h.API_KEY_HEADER)),c(2,e.Headers(h.API_TOKEN_HEADER)),c(3,e.Headers("user-agent")),c(4,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,String,F]),p("design:returntype",Promise)],L.prototype,"auth",null),u([c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Session()),p("design:type",Function),p("design:paramtypes",[e.Context,String,Object]),p("design:returntype",Promise)],L.prototype,"session",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,q()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"permission",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,q()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"read",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",void 0)],L.prototype,"upload",null),u([c(0,e.Ctx()),c(1,e.Argument()),p("design:type",Function),p("design:paramtypes",[e.Context,Object]),p("design:returntype",Promise)],L.prototype,"validation",null),u([c(0,e.Ctx()),c(1,e.Argument()),c(2,q()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],L.prototype,"write",null),exports.AuthController=class extends L{login(e,o,n,s,d){return g(this,void 0,void 0,(function*(){yield r.sleep(h.API_SLEEP_AUTH);const a=n,l=yield A.findOne({where:{[i.Op.or]:[{email:a},{username:n}],[i.Op.and]:[{password:t.sha256(s)}]}}).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 f.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=o,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,o){return g(this,void 0,void 0,(function*(){if(yield b.destroy(t))return e.success("Disconcerted"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,o){return g(this,void 0,void 0,(function*(){const{auth:i,error:n,token:s}=yield b.renew(r);return n?e.error(n):i?(i.useragent=t,yield i.save().catch(this.error),e.json({token:s}),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 g(this,void 0,void 0,(function*(){const r=yield B.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}},u([e.Post("/login"),e.Middleware("validation",{username:r.Validation.string().min(3).required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("username")),c(3,e.Body("password")),c(4,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,String,F]),p("design:returntype",Promise)],exports.AuthController.prototype,"login",null),u([e.Get("/logout"),e.Middleware("auth"),c(0,e.Ctx()),c(1,N()),c(2,q()),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:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Headers("user-agent")),c(2,e.Body("token")),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,F]),p("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),u([e.Get(),e.Middleware("auth"),c(0,e.Ctx()),c(1,q()),p("design:type",Function),p("design:paramtypes",[e.Context,A]),p("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=u([e.Controller("/auth"),e.Extends(L)],exports.AuthController),exports.FilesController=class extends L{directory(){return h.API_HTTP_PUBLIC||"./"}files(e){return g(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=l.join(this.directory(),t);if(!s.existsSync(o)||!s.statSync(o).isDirectory())return e.notFound("Path not Found");let i=[];return i=s.readdirSync(o),i=i.map((e=>this.info(l.join(o,e)))),i=i.filter(r.isDef),Object.assign(Object.assign({},this.info(o)),{files:i})}))}access(e,t,r){return g(this,void 0,void 0,(function*(){yield this.permission(e,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()}}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,q()),p("design:type",Function),p("design:paramtypes",[e.Context,String,A]),p("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=u([e.Controller("/files"),e.Extends(L)],exports.FilesController),exports.ForgotController=class extends L{check(e,t){return g(this,void 0,void 0,(function*(){const o=yield this.find(t);if(!o||!o.user)return e.notFound("User not found");o.token=r.uniqueID(),yield o.save(),e.json({token:o.token})}))}forgot(e,t,o){return g(this,void 0,void 0,(function*(){yield r.sleep(h.API_SLEEP_FORGOT);const n=t,s=yield A.findOne({where:{[i.Op.or]:[{email:n},{username:t}]}}).catch(this.error);if(!s)return e.notFound("User not found");const d=r.uniqueID(),a=Date.now()+6e4*h.API_TOKEN_FORGOT,l=yield x.create({token:d,timestamp:a,state:!0,userId:s.id});e.success("OK"),o.emit("forgot.send",{ctx:e,forgot:l,user:s}),this.emit("forgot.send",{ctx:e,forgot:l,user:s})}))}reset(e,r,o,i){return g(this,void 0,void 0,(function*(){const n=yield this.find(r);if(!n)return e.notFound("User not found");n.state=!1,yield n.save().catch(this.error),n.user.password=t.sha256(o),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 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:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),u([e.Post(),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),u([e.Post("/reset"),e.Middleware("validation",{token:r.Validation.string().required(),password:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.Body("password")),c(3,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,F]),p("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=u([e.Controller("/forgot"),e.Extends(L)],exports.ForgotController),exports.ModelController=class extends L{constructor(){super(...arguments),this._columns=[]}_add(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,body:o}){const i=yield this.model().create(Object.assign(Object.assign({},t.req.body),o||{}),r||{}).catch(this.error);if(i){const r=this.key();return t.prepare(e.Status.OK,{[r]:i.getDataValue(r)}),i}t.error("Internal Server Error")}))}_all(t){return g(this,arguments,void 0,(function*({ctx:t,options:o,callback:n,scope:s}){var d,a,l,u,c;const p=this.scope(s),g=Object.assign({},o||{});g.where=Object.assign({},g.where||{});const h=null===(d=t.req.query.limit)||void 0===d?void 0:d.toString();h&&(g.limit=parseInt(h));const y=null===(a=t.req.query.offset)||void 0===a?void 0:a.toString();y&&(g.offset=parseInt(y));const m=this.columns(),_=[],x=null===(l=t.req.query.asc)||void 0===l?void 0:l.toString();x&&x.length&&x.split(",").forEach((e=>{m.indexOf(e)>=0&&_.push([e,"ASC"])}));const v=null===(u=t.req.query.desc)||void 0===u?void 0:u.toString();v&&v.length&&v.split(",").forEach((e=>{m.indexOf(e)>=0&&_.push([e,"DESC"])})),_.length&&(g.order=_);const P=[],f=r.isArray(g.attributes)?g.attributes:m,I=null===(c=t.req.query.search)||void 0===c?void 0:c.toString();f.forEach((e=>{var o;if(r.isString(e)&&(I&&I.length&&P.push({[e]:{[i.Op.like]:`%${I}%`}}),"search_"+e in t.req.query)){const r=null===(o=t.req.query["search_"+e])||void 0===o?void 0:o.toString();r&&r.length&&P.push({[e]:{[i.Op.like]:`%${r}%`}})}})),P.length&&(g.where=Object.assign(Object.assign({},g.where),{[i.Op.or]:[...P]}));const A=(yield p.count(Object.assign(Object.assign({},g),{col:m[0]})).catch(this.error))||0,C=yield p.findAll(g).catch(this.error);return C?(t.prepare(e.Status.OK,{count:A,records:n?yield n(C):C}),[C,A]):(t.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]: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?T.error(e.message+"\n"+e.sql,"api.controller.sql",h.API_CONSOLE_ERROR):super.error(e)}_get(t){return g(this,arguments,void 0,(function*({ctx:t,options:r,callback:o,scope:i}){const n=this.key(),{[n]:s}=t.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[n]:s})})).catch(this.error);return d?(t.prepare(e.Status.OK,o?yield o(d):d.toJSON()),d):null===d?t.notFound("Record not found"):void t.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return g(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const o=this.key(),{[o]:i}=e.req.params,[n]=(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 n?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}},exports.ModelController=u([e.Extends(L)],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 v}create(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}update(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.GroupsController=u([e.Controller("/groups"),e.Extends(exports.CrudController)],exports.GroupsController),exports.GroupsRoutesController=class extends exports.ModelController{model(){return P}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:I,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,o){return g(this,void 0,void 0,(function*(){const i=yield v.findByPk(t,{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 I.count({where:{id:o[r]}}),e&&(yield P.create({groupId:t,routeId:o[r]}))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/routes"),e.Middleware("auth"),e.Middleware("read","groups"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"all",null),u([e.Put("/:id/routes"),e.Middleware("auth"),e.Middleware("write","groups"),e.Middleware("validation",{routes:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("routes")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.GroupsRoutesController.prototype,"set",null),exports.GroupsRoutesController=u([e.Controller("/groups"),e.Extends(exports.ModelController)],exports.GroupsRoutesController),exports.LogsController=class extends exports.ModelController{model(){return S}all(e,t,r){return g(this,void 0,void 0,(function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this._all({ctx:e,options:{where:o,order:[["created","DESC"]]}})}))}},u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),c(1,e.Query("type")),c(2,e.Query("source")),p("design:type",Function),p("design:paramtypes",[e.Context,String,String]),p("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=u([e.Controller("/logs"),e.Extends(exports.ModelController)],exports.LogsController),exports.RegisterController=class extends L{register(e,o,n){return g(this,void 0,void 0,(function*(){yield r.sleep(h.API_SLEEP_REGISTRY);const{name:s,date:d,email:a,username:l,password:u,confirm:c}=o,p=l||a,g=t.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!=t.sha256(c))return e.error("Invalid password");const y=yield A.create({name:s,email:a,username:p,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!y)return e.error("Internal Server Error");const m=yield 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"),n.emit("register.user",{ctx:e,register:m,user:y}),this.emit("register.user",{ctx:e,register:m,user:y})}))}confirm(e,t,r){return g(this,void 0,void 0,(function*(){const o=yield f.findOne({where:{token:t,state:!0},include:[{model:A,required:!0}]}).catch(this.error);if(!o)return e.notFound("User not found");o.state=!1,yield o.save().catch(this.error),o.user.state=!0,yield o.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:o,user:o.user}),this.emit("register.confirm",{ctx:e,register:o,user:o.user})}))}send(e,t,r){return g(this,void 0,void 0,(function*(){const o=t,n=yield f.findOne({where:{state:!0},include:[{model:A,required:!0,where:{[i.Op.or]:[{email:o},{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 g(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield f.count({where:{token:e}}))?this.getId():e}))}},u([e.Post(),e.Middleware("validation",{name:r.Validation.string().required(),date:r.Validation.string().date().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).required(),confirm:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body()),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,Object,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),u([e.Post("/confirm"),e.Middleware("validation",{token:r.Validation.string().required()}),c(0,e.Ctx()),c(1,e.Body("token")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),u([e.Post("/send"),e.Middleware("validation",{username:r.Validation.string().min(4).required()}),c(0,e.Ctx()),c(1,e.Body("username")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=u([e.Controller("/register"),e.Extends(L)],exports.RegisterController),exports.RoutesController=class extends exports.CrudController{model(){return I}create(){return{name:r.Validation.string().required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}}update(){return{name:r.Validation.string().empty(),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}}},exports.RoutesController=u([e.Controller("/routes"),e.Extends(exports.CrudController)],exports.RoutesController),exports.SetupController=class extends L{setup(e){return g(this,void 0,void 0,(function*(){if(0==(yield A.count())){const e=yield A.create({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),t={description:"API CORE",state:!0},o=yield v.create(Object.assign({name:"admin"},t));yield C.create({userId:e.id,groupId:o.id});const i=["read","write"],n=["users","groups","routes"];yield r.forEachSeries(n,(e=>g(this,void 0,void 0,(function*(){yield r.forEachSeries(i,(r=>g(this,void 0,void 0,(function*(){const i=e+"."+r,n=yield I.create(Object.assign({name:i},t));yield P.create({groupId:o.id,routeId:n.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield r.forEachSeries(s,(e=>g(this,void 0,void 0,(function*(){const r="files."+e,i=yield I.create(Object.assign({name:r},t));yield P.create({groupId:o.id,routeId:i.id})}))));const d=yield I.create(Object.assign({name:"logs.read"},t));yield P.create({groupId:o.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(L)],exports.SetupController),exports.UsersController=class extends exports.ModelController{model(){return A}constructor(){super(),this.dir=h.API_HTTP_PUBLIC+"/avatar",h.API_HTTP_PUBLIC&&s.existsSync(h.API_HTTP_PUBLIC)&&!s.existsSync(this.dir)&&s.mkdirSync(this.dir)}avatar(e,t,r){return g(this,void 0,void 0,(function*(){if(t.length){const o=t[0].filename||"";if(o){const t=this.dir+"/"+r.avatar;if(s.existsSync(t)&&s.lstatSync(t).isFile()&&s.rmSync(t),r.avatar=o,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return g(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="",(yield t.save().catch(this.error))&&s.existsSync(r)&&s.rmSync(r),e.success("OK")}))}password(e,r,o,i){return g(this,void 0,void 0,(function*(){const n=yield this.scope("password").findOne({where:{id:i.id,password:t.sha256(r),state:!0}}).catch(this.error);return n?(n.password=t.sha256(o),(yield n.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return g(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_get(e,t,r){return g(this,void 0,void 0,(function*(){const o=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(o)return e.json({token:r.hash.decrypt(o.token)});e.notFound("Record not found")}))}token_remove(e,t){return g(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save().catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r){return g(this,void 0,void 0,(function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o){const t=yield this.token_new();return o.token=r.hash.encrypt(t),yield o.save().catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return g(this,void 0,void 0,(function*(){const e=r.uuidv4();return(yield this.model().count({where:{token:e}}))?this.token_new():e}))}add(e,r){return g(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:t.sha256(r)}})}))}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,r){return g(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:r?{password:t.sha256(r)}:{}})}))}},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,q()),p("design:type",Function),p("design:paramtypes",[e.Context,Array,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),u([e.Get("/avatar/remove"),e.Middleware("auth"),c(0,e.Ctx()),c(1,q()),p("design:type",Function),p("design:paramtypes",[e.Context,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"avatar_remove",null),u([e.Post("/password"),e.Middleware("auth"),e.Middleware("validation",{oldPassword:r.Validation.string().min(5).required(),newPassword:r.Validation.string().min(5).required()}),c(0,e.Ctx()),c(1,e.Body("oldPassword")),c(2,e.Body("newPassword")),c(3,q()),p("design:type",Function),p("design:paramtypes",[e.Context,String,String,A]),p("design:returntype",Promise)],exports.UsersController.prototype,"password",null),u([e.Get("/token"),e.Middleware("auth"),c(0,e.Ctx()),c(1,q()),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,A,F]),p("design:returntype",Promise)],exports.UsersController.prototype,"token",null),u([e.Get("/token/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),u([e.Get("/token/remove/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_remove",null),u([e.Get("/token/renew/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.App()),p("design:type",Function),p("design:paramtypes",[e.Context,String,F]),p("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),u([e.Post(),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:r.Validation.string().required(),email:r.Validation.string().email().required(),username:r.Validation.string().min(4).required(),password:r.Validation.string().min(5).required(),description:r.Validation.string().empty(""),state:r.Validation.boolean().parse().required()}),c(0,e.Ctx()),c(1,e.Body("password")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"add",null),u([e.Get(),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"all",null),u([e.Delete("/:id"),e.Middleware("auth"),e.Middleware("write"),c(0,e.Ctx()),c(1,q()),c(2,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,A,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"del",null),u([e.Get("/:id"),e.Middleware("auth"),e.Middleware("read"),c(0,e.Ctx()),p("design:type",Function),p("design:paramtypes",[e.Context]),p("design:returntype",Promise)],exports.UsersController.prototype,"get",null),u([e.Put("/:id"),e.Middleware("auth"),e.Middleware("write"),e.Middleware("validation",{name:r.Validation.string().empty(),email:r.Validation.string().email().empty(),username:r.Validation.string().min(4).empty(),password:r.Validation.string().min(5).empty().filter(""),description:r.Validation.string().empty(),state:r.Validation.boolean().parse().empty()}),c(0,e.Ctx()),c(1,e.Body("password")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=u([e.Controller("/users"),e.Extends(exports.ModelController),p("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ModelController{model(){return C}all(e,t){return g(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:v,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,o){return g(this,void 0,void 0,(function*(){const i=yield A.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){if(yield C.destroy({where:{userId:i.id}}),o){let e=0;for(let t=0;t<o.length;t++)e=yield v.count({where:{id:o[t]}}),e&&(yield C.create({userId:i.id,groupId:o[t]}))}return e.success("OK")}if(r.isNull(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}},u([e.Get("/:id/groups"),e.Middleware("auth"),e.Middleware("read","users"),c(0,e.Ctx()),c(1,e.Params("id")),p("design:type",Function),p("design:paramtypes",[e.Context,String]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),u([e.Put("/:id/groups"),e.Middleware("auth"),e.Middleware("write","users"),e.Middleware("validation",{groups:r.Validation.array(r.Validation.number().parse())}),c(0,e.Ctx()),c(1,e.Params("id")),c(2,e.Body("groups")),p("design:type",Function),p("design:paramtypes",[e.Context,String,Array]),p("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=u([e.Controller("/users"),e.Extends(exports.ModelController)],exports.UsersGroupsController),exports.Application=F,exports.Auth=_,exports.Config=k,exports.Configs=E,exports.ControllerBase=L,exports.Database=y,exports.Env=h,exports.Forgot=x,exports.Group=v,exports.GroupRoute=P,exports.Log=S,exports.Logs=T,exports.Permission=B,exports.Register=f,exports.ReqAuth=N,exports.ReqUser=q,exports.Route=I,exports.Session=w,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,10 +1,11 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.2.
|
|
2
|
+
* @andrewcaires/api v3.2.1
|
|
3
3
|
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
4
|
* (c) 2024 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
7
|
import { Context, IStore, IUpload, Application as Application$1, IFile } from '@andrewcaires/express';
|
|
8
|
+
import { Hash } from '@andrewcaires/node';
|
|
8
9
|
import WebSocket from 'ws';
|
|
9
10
|
import { EventEmitter, TypeObject, ValidationBase, TypeObjectString, TypeObjectAny } from '@andrewcaires/utils.js';
|
|
10
11
|
import { Model, CreateOptions, Attributes, FindOptions, UpdateOptions, ModelStatic, Sequelize, WhereOptions } from 'sequelize';
|
|
@@ -46,6 +47,7 @@ declare class User extends Model {
|
|
|
46
47
|
email: string;
|
|
47
48
|
username: string;
|
|
48
49
|
password: string;
|
|
50
|
+
token: string;
|
|
49
51
|
avatar: string;
|
|
50
52
|
date: string;
|
|
51
53
|
description: string;
|
|
@@ -97,7 +99,7 @@ declare class Session extends Model {
|
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
declare abstract class ControllerBase extends EventEmitter {
|
|
100
|
-
auth(ctx: Context, token: string, useragent: string): Promise<void>;
|
|
102
|
+
auth(ctx: Context, key: string, token: string, useragent: string, app: Application): Promise<void>;
|
|
101
103
|
session(ctx: Context, useragent: string, store: IStore): Promise<void>;
|
|
102
104
|
error(error: any): void;
|
|
103
105
|
name(): string;
|
|
@@ -109,6 +111,7 @@ declare abstract class ControllerBase extends EventEmitter {
|
|
|
109
111
|
}
|
|
110
112
|
|
|
111
113
|
declare class Application extends Application$1 {
|
|
114
|
+
readonly hash: Hash;
|
|
112
115
|
private _webSocket?;
|
|
113
116
|
constructor(controllers: Array<ControllerBase>);
|
|
114
117
|
error(error: any, source?: string): void;
|
|
@@ -159,6 +162,7 @@ interface ArgumentsModelAll<M extends Model<M>> {
|
|
|
159
162
|
ctx: Context;
|
|
160
163
|
options?: FindOptions<Attributes<M>>;
|
|
161
164
|
callback?: CallbackModelAll<M>;
|
|
165
|
+
scope?: string;
|
|
162
166
|
}
|
|
163
167
|
|
|
164
168
|
interface ArgumentsModelDel<M extends Model<M>> {
|
|
@@ -172,6 +176,7 @@ interface ArgumentsModelGet<M extends Model<M>> {
|
|
|
172
176
|
ctx: Context;
|
|
173
177
|
options?: FindOptions<Attributes<M>>;
|
|
174
178
|
callback?: CallbackModelGet<M>;
|
|
179
|
+
scope?: string;
|
|
175
180
|
}
|
|
176
181
|
|
|
177
182
|
interface ArgumentsModelSet<M extends Model<M>> {
|
|
@@ -200,14 +205,15 @@ interface ITokenParameters {
|
|
|
200
205
|
declare abstract class ModelController<M extends Model<M>> extends ControllerBase {
|
|
201
206
|
private _columns;
|
|
202
207
|
protected _add({ ctx, options, body }: ArgumentsModelAdd<M>): Promise<M | void>;
|
|
203
|
-
protected _all({ ctx, options, callback }: ArgumentsModelAll<M>): Promise<[Array<M>, number] | Array<void>>;
|
|
208
|
+
protected _all({ ctx, options, callback, scope }: ArgumentsModelAll<M>): Promise<[Array<M>, number] | Array<void>>;
|
|
204
209
|
protected columns(): string[];
|
|
205
210
|
protected _del({ ctx, options }: ArgumentsModelDel<M>): Promise<number>;
|
|
206
211
|
error(error: any): void;
|
|
207
|
-
protected _get({ ctx, options, callback }: ArgumentsModelGet<M>): Promise<M | void>;
|
|
212
|
+
protected _get({ ctx, options, callback, scope }: ArgumentsModelGet<M>): Promise<M | void>;
|
|
208
213
|
key(): string;
|
|
209
214
|
abstract model(): ModelStatic<M>;
|
|
210
215
|
name(): string;
|
|
216
|
+
scope(name?: string): ModelStatic<M>;
|
|
211
217
|
protected _set({ ctx, options, body }: ArgumentsModelSet<M>): Promise<boolean>;
|
|
212
218
|
}
|
|
213
219
|
|
|
@@ -261,9 +267,15 @@ declare class UsersController extends ModelController<User> {
|
|
|
261
267
|
dir: string;
|
|
262
268
|
model(): typeof User;
|
|
263
269
|
constructor();
|
|
264
|
-
avatar(ctx: Context, files: Array<IFile>, user: User): Promise<void>;
|
|
270
|
+
protected avatar(ctx: Context, files: Array<IFile>, user: User): Promise<void>;
|
|
271
|
+
protected avatar_remove(ctx: Context, user: User): Promise<void>;
|
|
265
272
|
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User): Promise<void>;
|
|
266
|
-
|
|
273
|
+
protected token(ctx: Context, user: User, app: Application): Promise<void>;
|
|
274
|
+
protected token_get(ctx: Context, id: string, app: Application): Promise<void>;
|
|
275
|
+
protected token_remove(ctx: Context, id: string): Promise<void>;
|
|
276
|
+
protected token_renew(ctx: Context, id: string, app: Application): Promise<void>;
|
|
277
|
+
private token_new;
|
|
278
|
+
protected add(ctx: Context, password: string): Promise<void>;
|
|
267
279
|
protected all(ctx: Context): Promise<void>;
|
|
268
280
|
protected del(ctx: Context, user: User, id: string): Promise<void>;
|
|
269
281
|
protected get(ctx: Context): Promise<void>;
|
|
@@ -305,6 +317,8 @@ declare class Env {
|
|
|
305
317
|
static readonly API_HTTP_CROSS: boolean;
|
|
306
318
|
static readonly API_HTTP_HYBRID: boolean;
|
|
307
319
|
static readonly API_HTTP_REDIRECT: string;
|
|
320
|
+
static readonly API_KEY_HASH: string;
|
|
321
|
+
static readonly API_KEY_HEADER: string;
|
|
308
322
|
static readonly API_NOTFOUND_REDIRECT: string;
|
|
309
323
|
static readonly API_SLEEP_AUTH: number;
|
|
310
324
|
static readonly API_SLEEP_FORGOT: number;
|
|
@@ -370,7 +384,7 @@ declare class Token {
|
|
|
370
384
|
private static error;
|
|
371
385
|
private static options;
|
|
372
386
|
static renew(token: string): Promise<ITokenParameters>;
|
|
373
|
-
static user(token: string): Promise<ITokenParameters>;
|
|
387
|
+
static user(key: string, token: string, app: Application): Promise<ITokenParameters>;
|
|
374
388
|
private static verify;
|
|
375
389
|
}
|
|
376
390
|
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v3.2.
|
|
2
|
+
* @andrewcaires/api v3.2.1
|
|
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,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};
|
|
7
|
+
import{Application as e,parameterFactory as t,Ctx as r,Headers as i,App as n,Session as s,Argument as o,Upload as d,Context as a,Post as u,Middleware as c,Body as l,Get as p,Controller as g,Extends as h,Status as y,Delete as m,Put as _,Params as f,Query as v,Files as I}from"@andrewcaires/express";import{LogColor as P,Log as A,Hash as E,sha256 as O}from"@andrewcaires/node";import{toBool as S,parseMs as T,noop as w,loop as R,uuidv4 as b,sleep as k,EventEmitter as D,Validation as N,isDef as x,uniqueID as F,isArray as q,isString as B,isNull as L,forEachSeries as j}from"@andrewcaires/utils.js";import K from"ws";import{Sequelize as C,DataTypes as H,Model as M,Op as U}from"sequelize";import{config as G}from"dotenv";import{existsSync as z,readFileSync as Y,statSync as X,readdirSync as W,mkdirSync as Z,lstatSync as J,rmSync as $}from"fs";import{Store as V}from"express-session";import{verify as Q,sign as ee}from"jsonwebtoken";import{join as te}from"path";function re(e,t,r,i){var n,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,i);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}function ie(e,t){return function(r,i){t(r,i,e)}}function ne(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function se(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{a(i.next(e))}catch(e){s(e)}}function d(e){try{a(i.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,d)}a((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,G();class oe{static getBool(e,t){return S(oe.getString(e,t.toString()))}static getInt(e,t){return parseInt(oe.getString(e,t.toString()))}static getMs(e,t){return T(oe.getString(e,t))}static getString(e,t){return e in process.env?process.env[e]||"":t}}oe.API_CONSOLE_ERROR=oe.getBool("API_CONSOLE_ERROR",!1),oe.API_DEFAULT_PATH=oe.getString("API_DEFAULT_PATH","/api"),oe.API_DB_DATABASE=oe.getString("API_DB_DATABASE",""),oe.API_DB_HOST=oe.getString("API_DB_HOST","127.0.0.1"),oe.API_DB_PASSWORD=oe.getString("API_DB_PASSWORD",""),oe.API_DB_PORT=oe.getInt("API_DB_PORT",3306),oe.API_DB_TYPE=oe.getString("API_DB_TYPE",""),oe.API_DB_USERNAME=oe.getString("API_DB_USERNAME","root"),oe.API_DB_LOG=oe.getBool("API_DB_LOG",!1),oe.API_DB_PREFIX=oe.getString("API_DB_PREFIX",""),oe.API_DB_TIMEZONE=oe.getString("API_DB_TIMEZONE","+00:00"),oe.API_HTTP_CRT=oe.getString("API_HTTP_CRT",""),oe.API_HTTP_KEY=oe.getString("API_HTTP_KEY",""),oe.API_HTTP_PORT=oe.getInt("API_HTTP_PORT",3e3),oe.API_HTTP_PUBLIC=oe.getString("API_HTTP_PUBLIC",""),oe.API_HTTP_CROSS=oe.getBool("API_HTTP_CROSS",!1),oe.API_HTTP_HYBRID=oe.getBool("API_HTTP_HYBRID",!1),oe.API_HTTP_REDIRECT=oe.getString("API_HTTP_REDIRECT",""),oe.API_KEY_HASH=oe.getString("API_KEY_HASH",""),oe.API_KEY_HEADER=oe.getString("API_KEY_HEADER","api_key"),oe.API_NOTFOUND_REDIRECT=oe.getString("API_NOTFOUND_REDIRECT",""),oe.API_SLEEP_AUTH=oe.getMs("API_SLEEP_AUTH","2s"),oe.API_SLEEP_FORGOT=oe.getMs("API_SLEEP_FORGOT","5s"),oe.API_SLEEP_REGISTRY=oe.getMs("API_SLEEP_REGISTRY","5s"),oe.API_SESSION_NAME=oe.getString("API_SESSION_NAME","session.id"),oe.API_SESSION_LIFETIME=oe.getMs("API_SESSION_LIFETIME","1d"),oe.API_SESSION_SECRET=oe.getString("API_SESSION_SECRET","yoursecret"),oe.API_TOKEN_CRT=oe.getString("API_TOKEN_CRT",""),oe.API_TOKEN_KEY=oe.getString("API_TOKEN_KEY",""),oe.API_TOKEN_FORGOT=oe.getMs("API_TOKEN_LIFETIME","1d"),oe.API_TOKEN_HEADER=oe.getString("API_TOKEN_HEADER","authorization"),oe.API_TOKEN_LIFETIME=oe.getMs("API_TOKEN_LIFETIME","1d"),oe.API_TOKEN_RENEW=oe.getMs("API_TOKEN_RENEW","1d"),oe.API_UPLOAD_COUNT=oe.getInt("API_UPLOAD_COUNT",1),oe.API_UPLOAD_FIELD=oe.getString("API_UPLOAD_FIELD","upload"),oe.API_UPLOAD_SIZE=oe.getInt("API_UPLOAD_SIZE",2),oe.API_UPLOAD_TEMP=oe.getString("API_UPLOAD_TEMP","./temp"),oe.API_WEBSOCKET_START=oe.getBool("API_WEBSOCKET_START",!1);class de{static connect(e){const t="connect_"+oe.API_DB_TYPE.toLowerCase();if(t in de)return de[t](e);throw new Error("No database is connected to this API")}static connect_mariadb(e){return new C(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mariadb",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_memory(){return new C("sqlite::memory:",{logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_mysql(e){return new C(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"mysql",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_postgres(e){return new C(e.database,e.username,e.password,{host:e.hostname,port:e.hostport,dialect:"postgres",logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}static connect_sqlite(e){return new C({dialect:"sqlite",storage:e.database,logging:oe.API_DB_LOG,define:{timestamps:!1},timezone:oe.API_DB_TIMEZONE})}}const ae=de.connect({database:oe.API_DB_DATABASE,username:oe.API_DB_USERNAME,password:oe.API_DB_PASSWORD,hostname:oe.API_DB_HOST,hostport:oe.API_DB_PORT});class ue extends M{}ue.init({secret:H.STRING,logout:H.DATE,useragent:H.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"auth",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ce extends M{}ce.init({token:H.STRING,timestamp:H.BIGINT,state:H.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"forgot",timestamps:!0,createdAt:"created",updatedAt:"updated"});class le extends M{}le.init({name:H.STRING,description:H.TEXT,state:H.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"group",timestamps:!0,createdAt:"created",updatedAt:"updated"});class pe extends M{}pe.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"groups_routes",timestamps:!0,createdAt:"created",updatedAt:!1}),pe.removeAttribute("id");class ge extends M{}ge.init({token:H.STRING,state:H.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"register",timestamps:!0,createdAt:"created",updatedAt:"updated"});class he extends M{}he.init({name:H.STRING,description:H.TEXT,state:H.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"route",timestamps:!0,createdAt:"created",updatedAt:"updated"});class ye extends M{}ye.init({name:H.STRING,email:H.STRING,username:H.STRING,password:H.STRING,token:H.STRING,avatar:H.STRING,date:H.DATEONLY,description:H.TEXT,state:H.BOOLEAN},{sequelize:ae,modelName:oe.API_DB_PREFIX+"user",timestamps:!0,createdAt:"created",updatedAt:"updated",defaultScope:{attributes:{exclude:["password","token"]}},scopes:{password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password"]}}}});class me extends M{}me.init({},{sequelize:ae,modelName:oe.API_DB_PREFIX+"users_groups",timestamps:!0,createdAt:"created",updatedAt:!1}),me.removeAttribute("id");class _e extends M{}_e.init({key:H.STRING,value:H.STRING},{sequelize:ae,modelName:oe.API_DB_PREFIX+"configs",timestamps:!0,createdAt:"created",updatedAt:"updated"}),_e.removeAttribute("id");class fe extends M{}fe.init({type:H.STRING,source:H.STRING,message:H.TEXT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"log",timestamps:!0,createdAt:"created",updatedAt:!1});class ve extends M{}ve.init({session:H.STRING,json:H.TEXT,expired:H.BIGINT},{sequelize:ae,modelName:oe.API_DB_PREFIX+"session",timestamps:!0,createdAt:"created",updatedAt:"updated"}),ve.removeAttribute("id"),ye.hasMany(ue),ue.belongsTo(ye),ye.hasMany(ce),ce.belongsTo(ye),ye.hasMany(ge),ge.belongsTo(ye),le.hasMany(pe),pe.belongsTo(le),he.hasMany(pe),pe.belongsTo(he),ye.hasMany(me),me.belongsTo(ye),le.hasMany(me),me.belongsTo(le);class Ie{static write(e,t,r){return se(this,void 0,void 0,(function*(){yield Ie.writeRaw(P.White,"",e,t,r)}))}static error(e,t,r){return se(this,void 0,void 0,(function*(){yield Ie.writeRaw(P.Red,"error",e,t,r)}))}static info(e,t,r){return se(this,void 0,void 0,(function*(){yield Ie.writeRaw(P.Cyan,"info",e,t,r)}))}static success(e,t,r){return se(this,void 0,void 0,(function*(){yield Ie.writeRaw(P.Green,"success",e,t,r)}))}static warning(e,t,r){return se(this,void 0,void 0,(function*(){yield Ie.writeRaw(P.Yellow,"warning",e,t,r)}))}static writeRaw(e,t,r,i,n){return se(this,void 0,void 0,(function*(){n&&A.console(e,t,r),ae&&(yield fe.create({type:t,source:i,message:r}).catch((()=>null)))}))}}const Pe=e=>z(e)?Y(e):void 0,Ae={http:Pe(oe.API_HTTP_CRT),token:Pe(oe.API_TOKEN_CRT)},Ee={http:Pe(oe.API_HTTP_KEY),token:Pe(oe.API_TOKEN_KEY)};class Oe extends V{constructor(){super(),this.all=e=>se(this,void 0,void 0,(function*(){e=e||w;const t=yield ve.findAll({attributes:["session"],where:{expired:{[U.gte]:Date.now()}}}).catch((t=>(e(t),null)));t&&e(null,t.map((e=>e.session))),e()})),this.clear=e=>se(this,void 0,void 0,(function*(){yield ve.destroy().catch(w),e&&e()})),this.destroy=(e,t)=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{session:e}}).catch(w),t&&t()})),this.expired=()=>se(this,void 0,void 0,(function*(){yield ve.destroy({where:{expired:{[U.lt]:Date.now()}}}).catch(w)})),this.get=(e,t)=>se(this,void 0,void 0,(function*(){t=t||w;const r=yield ve.findOne({where:{session:e,expired:{[U.gte]:Date.now()}}}).catch((e=>(t(e),null)));if(r){const e=JSON.parse(r.json);if(e.cookie){if(new Date(e.cookie.expires).getTime()<=Date.now())return yield r.destroy().catch(w),void t(null)}t(null,e)}else t(null)})),this.length=e=>se(this,void 0,void 0,(function*(){e&&e(null,(yield ve.count().catch(w))||0)})),this.set=(e,t,r)=>se(this,void 0,void 0,(function*(){r=r||w;const i=Date.now()+oe.API_SESSION_LIFETIME,n=JSON.stringify(t),[s,o]=(yield ve.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:i}}).catch(w))||[];s&&(o||(s.json=n,s.expired=i,yield s.save().catch(w))),r()})),this.loop=R(this.expired,3e4),this.loop.start()}}class Se{static create(e){return se(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{id:t}=e,r=b(),i=yield ue.create({secret:r,userId:t}).catch(Se.error);if(!i)return{error:"Internal Server Error"};return{auth:i,token:ee({id:t,secret:r},Ee.token,Se.options())}}))}static destroy(e){return se(this,void 0,void 0,(function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)}))}static error(e){Ie.error(e.message,"api.token",oe.API_CONSOLE_ERROR)}static options(){return{algorithm:"RS256",expiresIn:oe.API_TOKEN_LIFETIME+"ms"}}static renew(e){return se(this,void 0,void 0,(function*(){if(!Ee.token)return{error:"Key not found"};const{error:t,decode:r}=Se.verify(e,oe.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield ye.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const i=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(i&&!i.logout){i.secret=b(),yield i.save().catch(Se.error);return{auth:i,token:ee({id:e,secret:i.secret},Ee.token,Se.options())}}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static user(e,t,r){return se(this,void 0,void 0,(function*(){if(e){t=r.hash.encrypt(e);const i=yield ye.findOne({where:{token:t,state:!0}}).catch(Se.error);if(i){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield ue.findOrCreate({where:{secret:t,userId:i.id},defaults:{secret:t,userId:i.id}}).catch(Se.error))||[];if(r)return{auth:r,user:i}}return{error:"Access denied"}}const{error:i,decode:n}=Se.verify(t);if(i)return{error:i};if(n){const{id:e,secret:t}=n;if(e&&t){const r=yield ye.findOne({where:{id:e,state:!0}}).catch(Se.error);if(r){const e=yield ue.findOne({where:{secret:t,userId:r.id}}).catch(Se.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"Access denied"}}}return{error:"Invalid token"}}))}static verify(e,t){if(!Ae.token)return{error:"Cert not found"};if(!e||e.split(".").length<3)return{error:"Invalid Token"};try{return{decode:Q(e,Ae.token,{clockTolerance:t})}}catch(e){return{error:"Invalid Token"}}}}class Te extends e{constructor(e){super(e,{cert:Ae.http,cross:oe.API_HTTP_CROSS,hybrid:oe.API_HTTP_HYBRID,key:Ee.http,notfound:oe.API_NOTFOUND_REDIRECT,path:oe.API_DEFAULT_PATH,port:oe.API_HTTP_PORT,public:oe.API_HTTP_PUBLIC,redirect:oe.API_HTTP_REDIRECT,session:{store:new Oe,name:oe.API_SESSION_NAME,secret:oe.API_SESSION_SECRET,cookie:{maxAge:oe.API_SESSION_LIFETIME},genid:b}}),this.hash=new E(oe.API_KEY_HASH)}error(e,t){Ie.error(e.message,t,oe.API_CONSOLE_ERROR)}log(e,t){Ie.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return se(this,void 0,void 0,(function*(){yield ae.sync(),yield e.listen.call(this),oe.API_WEBSOCKET_START&&this.server&&(this._webSocket=new K.Server({server:this.server,verifyClient:(e,t)=>t(oe.API_WEBSOCKET_START)}),this._webSocket.on("connection",((e,t)=>se(this,void 0,void 0,(function*(){t.url||(t.url="");const r=t.url.length<=1?"":t.url.replace(/\//g,".");let i;e.on("message",(n=>se(this,void 0,void 0,(function*(){if(i)try{const s=JSON.parse(n);this.emit("ws.message"+r,{data:s,message:n,req:t,user:i,ws:e})}catch(s){this.emit("ws.message"+r,{message:n,req:t,user:i,ws:e})}else{const{user:s}=yield Se.user("",n.toString(),this);s&&(i=s,this.emit("ws.connection"+r,{req:t,user:i,ws:e}))}i||e.close()})))),e.on("close",(()=>{i&&this.emit("ws.close"+r,{user:i,ws:e})})),yield k(2e3),i||e.close()})))))}))}websocket(){return this._webSocket}}class we{static all(){return se(this,void 0,void 0,(function*(){const e=yield _e.findAll().catch(we.error),t={};return e&&e.forEach((e=>t[e.key]=e.value)),t}))}static del(e){return se(this,void 0,void 0,(function*(){return((yield _e.destroy({where:{key:e}}).catch(we.error))||0)>0}))}static error(e){Ie.error(e.message,"api.config",oe.API_CONSOLE_ERROR)}static get(e){return se(this,arguments,void 0,(function*(e,t=""){const r=yield _e.findOne({where:{key:e}}).catch(we.error);return r?r.value:t}))}static set(e,t){return se(this,void 0,void 0,(function*(){const[r]=(yield _e.findOrCreate({where:{key:e}}).catch(we.error))||[];r&&(r.value=t,yield r.save().catch(we.error))}))}}const Re=t((({ctx:e})=>e.req.auth)),be=t((({ctx:e})=>e.req.user));class ke{static all(e,t){return se(this,void 0,void 0,(function*(){return yield he.findAll({where:Object.assign(Object.assign({},t),{state:!0}),include:[{model:pe,required:!0,include:[{model:le,required:!0,where:{state:!0},include:[{model:me,required:!0,where:{userId:e.id}}]}]}]}).catch((e=>{Ie.error(e.message,"api.permission",oe.API_CONSOLE_ERROR)}))}))}static get(e){return se(this,void 0,void 0,(function*(){const t=yield ke.all(e);return t?t.map((e=>e.name)):[]}))}static is(e,t){return se(this,void 0,void 0,(function*(){const r=yield ke.all(e,{name:t});return!!r&&r.length>0}))}}class De extends D{auth(e,t,r,i,n){return se(this,void 0,void 0,(function*(){const{auth:s,error:o,user:d}=yield Se.user(t,r,n);return o?e.error(o):s&&d?s.useragent&&s.useragent!=i?e.error("Invalid token"):(e.req.auth=s,e.req.user=d,void e.next()):e.error("Internal Server Error")}))}session(e,t,r){return se(this,void 0,void 0,(function*(){r.auth&&r.user&&(r.useragent?r.useragent!=t&&r.regenerate(w):(r.useragent=t,r.save(w))),e.next()}))}error(e){Ie.error(e.message,"api.controller",oe.API_CONSOLE_ERROR)}name(){return"api"}permission(e,t,r){return se(this,void 0,void 0,(function*(){return r?(yield ke.is(r,t))?e.next():void e.unauthorized("Access denied"):e.unauthorized("Access denied")}))}read(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".read",r)}))}upload(e,t){t.path||(t.path=oe.API_UPLOAD_TEMP),t.size||(t.size=oe.API_UPLOAD_SIZE),t.field||(t.field=oe.API_UPLOAD_FIELD),d.middleware(e,t)}validation(e,t){return se(this,void 0,void 0,(function*(){const{error:r,value:i}=yield N.object(t).parse().validateAsync(e.req.body);if(r)return e.validation(r);e.req.body=i,e.next()}))}write(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,(t||this.name())+".write",r)}))}}re([ie(0,r()),ie(1,i(oe.API_KEY_HEADER)),ie(2,i(oe.API_TOKEN_HEADER)),ie(3,i("user-agent")),ie(4,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,String,Te]),ne("design:returntype",Promise)],De.prototype,"auth",null),re([ie(0,r()),ie(1,i("user-agent")),ie(2,s()),ne("design:type",Function),ne("design:paramtypes",[a,String,Object]),ne("design:returntype",Promise)],De.prototype,"session",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,ye]),ne("design:returntype",Promise)],De.prototype,"permission",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,ye]),ne("design:returntype",Promise)],De.prototype,"read",null),re([ie(0,r()),ie(1,o()),ne("design:type",Function),ne("design:paramtypes",[a,Object]),ne("design:returntype",void 0)],De.prototype,"upload",null),re([ie(0,r()),ie(1,o()),ne("design:type",Function),ne("design:paramtypes",[a,Object]),ne("design:returntype",Promise)],De.prototype,"validation",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,ye]),ne("design:returntype",Promise)],De.prototype,"write",null);let Ne=class extends De{login(e,t,r,i,n){return se(this,void 0,void 0,(function*(){yield k(oe.API_SLEEP_AUTH);const s=r,o=yield ye.findOne({where:{[U.or]:[{email:s},{username:r}],[U.and]:[{password:O(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 ge.findOne({where:{state:!0,userId:o.id}}).catch(this.error);if(d)return e.error("Activation required"),n.emit("auth.activation",{ctx:e,register:d,user:o}),void this.emit("auth.activation",{ctx:e,register:d,user:o});if(!o.state)return e.notFound("Invalid username or password"),n.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:a,error:u,token:c}=yield Se.create(o);return u?(e.error(u),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):a&&c?(a.useragent=t,yield a.save().catch(this.error),e.json({token:c}),n.emit("auth.login",{auth:a,ctx:e,user:o}),void this.emit("auth.login",{auth:a,ctx:e,user:o})):(e.error("Internal Server Error"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))}))}logout(e,t,r,i){return se(this,void 0,void 0,(function*(){if(yield Se.destroy(t))return e.success("Disconcerted"),i.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("Access denied")}))}renew(e,t,r,i){return se(this,void 0,void 0,(function*(){const{auth:n,error:s,token:o}=yield Se.renew(r);return s?e.error(s):n?(n.useragent=t,yield n.save().catch(this.error),e.json({token:o}),i.emit("auth.renew",{auth:n,ctx:e}),void this.emit("auth.renew",{auth:n,ctx:e})):e.error("Internal Server Error")}))}user(e,t){return se(this,void 0,void 0,(function*(){const r=yield ke.all(t);if(!r)return e.error("Internal Server Error");e.json(Object.assign(Object.assign({},t.toJSON()),{permissions:r.map((e=>e.name))}))}))}};re([u("/login"),c("validation",{username:N.string().min(3).required(),password:N.string().min(5).required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,l("username")),ie(3,l("password")),ie(4,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,String,Te]),ne("design:returntype",Promise)],Ne.prototype,"login",null),re([p("/logout"),c("auth"),ie(0,r()),ie(1,Re()),ie(2,be()),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,ue,ye,Te]),ne("design:returntype",Promise)],Ne.prototype,"logout",null),re([u("/renew"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,i("user-agent")),ie(2,l("token")),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,Te]),ne("design:returntype",Promise)],Ne.prototype,"renew",null),re([p(),c("auth"),ie(0,r()),ie(1,be()),ne("design:type",Function),ne("design:paramtypes",[a,ye]),ne("design:returntype",Promise)],Ne.prototype,"user",null),Ne=re([g("/auth"),h(De)],Ne);let xe=class extends De{directory(){return oe.API_HTTP_PUBLIC||"./"}files(e){return se(this,void 0,void 0,(function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const r=te(this.directory(),t);if(!z(r)||!X(r).isDirectory())return e.notFound("Path not Found");let i=[];return i=W(r),i=i.map((e=>this.info(te(r,e)))),i=i.filter(x),Object.assign(Object.assign({},this.info(r)),{files:i})}))}access(e,t,r){return se(this,void 0,void 0,(function*(){yield this.permission(e,this.name()+"."+t,r)}))}info(e){if(!z(e))return null;const t=X(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const i=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:i?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:i,symlink:t.isSymbolicLink()}}name(){return"files"}};re([p("/path/?*"),c("auth"),c("access","list"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],xe.prototype,"files",null),re([ie(0,r()),ie(1,o()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,ye]),ne("design:returntype",Promise)],xe.prototype,"access",null),xe=re([g("/files"),h(De)],xe);let Fe=class extends De{check(e,t){return se(this,void 0,void 0,(function*(){const r=yield this.find(t);if(!r||!r.user)return e.notFound("User not found");r.token=F(),yield r.save(),e.json({token:r.token})}))}forgot(e,t,r){return se(this,void 0,void 0,(function*(){yield k(oe.API_SLEEP_FORGOT);const i=t,n=yield ye.findOne({where:{[U.or]:[{email:i},{username:t}]}}).catch(this.error);if(!n)return e.notFound("User not found");const s=F(),o=Date.now()+6e4*oe.API_TOKEN_FORGOT,d=yield ce.create({token:s,timestamp:o,state:!0,userId:n.id});e.success("OK"),r.emit("forgot.send",{ctx:e,forgot:d,user:n}),this.emit("forgot.send",{ctx:e,forgot:d,user:n})}))}reset(e,t,r,i){return se(this,void 0,void 0,(function*(){const n=yield this.find(t);if(!n)return e.notFound("User not found");n.state=!1,yield n.save().catch(this.error),n.user.password=O(r),yield n.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})}))}find(e){return se(this,void 0,void 0,(function*(){return yield ce.findOne({where:{token:e,state:!0},include:[{model:ye,required:!0}]}).catch(this.error)}))}};re([p("/check"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,l("token")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Fe.prototype,"check",null),re([u(),c("validation",{username:N.string().min(4).required()}),ie(0,r()),ie(1,l("username")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"forgot",null),re([u("/reset"),c("validation",{token:N.string().required(),password:N.string().min(5).required()}),ie(0,r()),ie(1,l("token")),ie(2,l("password")),ie(3,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,Te]),ne("design:returntype",Promise)],Fe.prototype,"reset",null),Fe=re([g("/forgot"),h(De)],Fe);let qe=class extends De{constructor(){super(...arguments),this._columns=[]}_add(e){return se(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),r||{}),t||{}).catch(this.error);if(i){const t=this.key();return e.prepare(y.OK,{[t]:i.getDataValue(t)}),i}e.error("Internal Server Error")}))}_all(e){return se(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){var n,s,o,d,a;const u=this.scope(i),c=Object.assign({},t||{});c.where=Object.assign({},c.where||{});const l=null===(n=e.req.query.limit)||void 0===n?void 0:n.toString();l&&(c.limit=parseInt(l));const p=null===(s=e.req.query.offset)||void 0===s?void 0:s.toString();p&&(c.offset=parseInt(p));const g=this.columns(),h=[],m=null===(o=e.req.query.asc)||void 0===o?void 0:o.toString();m&&m.length&&m.split(",").forEach((e=>{g.indexOf(e)>=0&&h.push([e,"ASC"])}));const _=null===(d=e.req.query.desc)||void 0===d?void 0:d.toString();_&&_.length&&_.split(",").forEach((e=>{g.indexOf(e)>=0&&h.push([e,"DESC"])})),h.length&&(c.order=h);const f=[],v=q(c.attributes)?c.attributes:g,I=null===(a=e.req.query.search)||void 0===a?void 0:a.toString();v.forEach((t=>{var r;if(B(t)&&(I&&I.length&&f.push({[t]:{[U.like]:`%${I}%`}}),"search_"+t in e.req.query)){const i=null===(r=e.req.query["search_"+t])||void 0===r?void 0:r.toString();i&&i.length&&f.push({[t]:{[U.like]:`%${i}%`}})}})),f.length&&(c.where=Object.assign(Object.assign({},c.where),{[U.or]:[...f]}));const P=(yield u.count(Object.assign(Object.assign({},c),{col:g[0]})).catch(this.error))||0,A=yield u.findAll(c).catch(this.error);return A?(e.prepare(y.OK,{count:P,records:r?yield r(A):A}),[A,P]):(e.error("Internal Server Error"),[])}))}columns(){return 0==this._columns.length&&(this._columns=Object.keys(this.model().getAttributes())),this._columns}_del(e){return se(this,arguments,void 0,(function*({ctx:e,options:t}){const r=this.key(),{[r]:i}=e.req.params;if(!i)return e.error("Internal Server Error"),0;const n=yield this.model().destroy(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:i})})).catch(this.error);return n?(e.success("OK"),n):(e.notFound("Record not found"),0)}))}error(e){e.sql?Ie.error(e.message+"\n"+e.sql,"api.controller.sql",oe.API_CONSOLE_ERROR):super.error(e)}_get(e){return se(this,arguments,void 0,(function*({ctx:e,options:t,callback:r,scope:i}){const n=this.key(),{[n]:s}=e.req.params,o=yield this.scope(i).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:s})})).catch(this.error);return o?(e.prepare(y.OK,r?yield r(o):o.toJSON()),o):null===o?e.notFound("Record not found"):void e.error("Internal Server Error")}))}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}_set(e){return se(this,arguments,void 0,(function*({ctx:e,options:t,body:r}){const i=this.key(),{[i]:n}=e.req.params,[s]=(yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:n})})).catch(this.error))||[];return s?(e.success("OK"),!0):(e.success("Record not changed"),!1)}))}};qe=re([h(De)],qe);let Be=class extends qe{create(){return{}}add(e){return se(this,void 0,void 0,(function*(){yield this._add({ctx:e})}))}all(e){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e){return se(this,void 0,void 0,(function*(){yield this._del({ctx:e})}))}get(e){return se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e){return se(this,void 0,void 0,(function*(){yield this._set({ctx:e})}))}update(){return{}}validationAdd(e){return se(this,void 0,void 0,(function*(){yield this.validation(e,this.create())}))}validationSet(e){return se(this,void 0,void 0,(function*(){yield this.validation(e,this.update())}))}};re([u(),c("auth"),c("write"),c("validationAdd"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"add",null),re([p(),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"all",null),re([m("/:id"),c("auth"),c("write"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"del",null),re([p("/:id"),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"get",null),re([_("/:id"),c("auth"),c("write"),c("validationSet"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"set",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"validationAdd",null),re([ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Be.prototype,"validationSet",null),Be=re([h(qe)],Be);let Le=class extends Be{model(){return le}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};Le=re([g("/groups"),h(Be)],Le);let je=class extends qe{model(){return pe}all(e,t){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{groupId:t},include:[{model:he,required:!0}]},callback:e=>e.map((e=>e.route))})}))}set(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield le.findByPk(t,{attributes:["id"]}).catch(this.error);if(i){const t=i.id;if(yield pe.destroy({where:{groupId:t}}),r){let e=0;for(let i=0;i<r.length;i++)e=yield he.count({where:{id:r[i]}}),e&&(yield pe.create({groupId:t,routeId:r[i]}))}return e.success("OK")}if(L(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([p("/:id/routes"),c("auth"),c("read","groups"),ie(0,r()),ie(1,f("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],je.prototype,"all",null),re([_("/:id/routes"),c("auth"),c("write","groups"),c("validation",{routes:N.array(N.number().parse())}),ie(0,r()),ie(1,f("id")),ie(2,l("routes")),ne("design:type",Function),ne("design:paramtypes",[a,String,Array]),ne("design:returntype",Promise)],je.prototype,"set",null),je=re([g("/groups"),h(qe)],je);let Ke=class extends qe{model(){return fe}all(e,t,r){return se(this,void 0,void 0,(function*(){const i={};t&&(i.type=t),r&&(i.source=r),yield this._all({ctx:e,options:{where:i,order:[["created","DESC"]]}})}))}};re([p(),c("auth"),c("read"),ie(0,r()),ie(1,v("type")),ie(2,v("source")),ne("design:type",Function),ne("design:paramtypes",[a,String,String]),ne("design:returntype",Promise)],Ke.prototype,"all",null),Ke=re([g("/logs"),h(qe)],Ke);let Ce=class extends De{register(e,t,r){return se(this,void 0,void 0,(function*(){yield k(oe.API_SLEEP_REGISTRY);const{name:i,date:n,email:s,username:o,password:d,confirm:a}=t,u=o||s,c=O(d);if(yield ye.count({where:{[U.or]:[{email:s},{username:u}]}}).catch(this.error))return e.validation("Invalid email or username");if(c!=O(a))return e.error("Invalid password");const l=yield ye.create({name:i,email:s,username:u,password:c,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!l)return e.error("Internal Server Error");const p=yield ge.create({token:yield this.getId(),userId:l.id,state:!0}).catch(this.error);if(!p)return l.destroy(),e.error("Internal Server Error");e.success("OK"),r.emit("register.user",{ctx:e,register:p,user:l}),this.emit("register.user",{ctx:e,register:p,user:l})}))}confirm(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield ge.findOne({where:{token:t,state:!0},include:[{model:ye,required:!0}]}).catch(this.error);if(!i)return e.notFound("User not found");i.state=!1,yield i.save().catch(this.error),i.user.state=!0,yield i.user.save().catch(this.error),e.success("OK"),r.emit("register.confirm",{ctx:e,register:i,user:i.user}),this.emit("register.confirm",{ctx:e,register:i,user:i.user})}))}send(e,t,r){return se(this,void 0,void 0,(function*(){const i=t,n=yield ge.findOne({where:{state:!0},include:[{model:ye,required:!0,where:{[U.or]:[{email:i},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("User not found");e.success("OK"),r.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})}))}getId(){return se(this,void 0,void 0,(function*(){const e=b();return(yield ge.count({where:{token:e}}))?this.getId():e}))}};re([u(),c("validation",{name:N.string().required(),date:N.string().date().required(),email:N.string().email().required(),username:N.string().min(4).empty(),password:N.string().min(5).required(),confirm:N.string().min(5).required()}),ie(0,r()),ie(1,l()),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,Object,Te]),ne("design:returntype",Promise)],Ce.prototype,"register",null),re([u("/confirm"),c("validation",{token:N.string().required()}),ie(0,r()),ie(1,l("token")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ce.prototype,"confirm",null),re([u("/send"),c("validation",{username:N.string().min(4).required()}),ie(0,r()),ie(1,l("username")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ce.prototype,"send",null),Ce=re([g("/register"),h(De)],Ce);let He=class extends Be{model(){return he}create(){return{name:N.string().required(),description:N.string().empty(""),state:N.boolean().parse().required()}}update(){return{name:N.string().empty(),description:N.string().empty(),state:N.boolean().parse().empty()}}};He=re([g("/routes"),h(Be)],He);let Me=class extends De{setup(e){return se(this,void 0,void 0,(function*(){if(0==(yield ye.count())){const e=yield ye.create({name:"Admin",email:"admin@localhost",username:"admin",password:"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0}),t={description:"API CORE",state:!0},r=yield le.create(Object.assign({name:"admin"},t));yield me.create({userId:e.id,groupId:r.id});const i=["read","write"],n=["users","groups","routes"];yield j(n,(e=>se(this,void 0,void 0,(function*(){yield j(i,(i=>se(this,void 0,void 0,(function*(){const n=e+"."+i,s=yield he.create(Object.assign({name:n},t));yield pe.create({groupId:r.id,routeId:s.id})}))))}))));const s=[...i,"delete","list","rename","upload"];yield j(s,(e=>se(this,void 0,void 0,(function*(){const i="files."+e,n=yield he.create(Object.assign({name:i},t));yield pe.create({groupId:r.id,routeId:n.id})}))));const o=yield he.create(Object.assign({name:"logs.read"},t));yield pe.create({groupId:r.id,routeId:o.id})}e.success("OK")}))}};re([p(),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Me.prototype,"setup",null),Me=re([g("/setup"),h(De)],Me);let Ue=class extends qe{model(){return ye}constructor(){super(),this.dir=oe.API_HTTP_PUBLIC+"/avatar",oe.API_HTTP_PUBLIC&&z(oe.API_HTTP_PUBLIC)&&!z(this.dir)&&Z(this.dir)}avatar(e,t,r){return se(this,void 0,void 0,(function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.dir+"/"+r.avatar;if(z(t)&&J(t).isFile()&&$(t),r.avatar=i,yield r.save().catch(this.error))return e.success("OK")}}e.success("Record not changed")}))}avatar_remove(e,t){return se(this,void 0,void 0,(function*(){const r=this.dir+"/"+t.avatar;t.avatar="",(yield t.save().catch(this.error))&&z(r)&&$(r),e.success("OK")}))}password(e,t,r,i){return se(this,void 0,void 0,(function*(){const n=yield this.scope("password").findOne({where:{id:i.id,password:O(t),state:!0}}).catch(this.error);return n?(n.password=O(r),(yield n.save().catch(this.error))?e.success("OK"):void e.success("Record not changed")):e.error("Record not changed")}))}token(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_get(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(i)return e.json({token:r.hash.decrypt(i.token)});e.notFound("Record not found")}))}token_remove(e,t){return se(this,void 0,void 0,(function*(){const r=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(r)return r.token="",yield r.save().catch(this.error),e.success("OK");e.notFound("Record not found")}))}token_renew(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=r.hash.encrypt(t),yield i.save().catch(this.error),e.json({token:t})}e.notFound("Record not found")}))}token_new(){return se(this,void 0,void 0,(function*(){const e=b();return(yield this.model().count({where:{token:e}}))?this.token_new():e}))}add(e,t){return se(this,void 0,void 0,(function*(){yield this._add({ctx:e,body:{password:O(t)}})}))}all(e){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e})}))}del(e,t,r){return se(this,void 0,void 0,(function*(){t&&t.id.toString()!=r?yield this._del({ctx:e}):e.error("Internal Server Error")}))}get(e){return se(this,void 0,void 0,(function*(){yield this._get({ctx:e})}))}set(e,t){return se(this,void 0,void 0,(function*(){yield this._set({ctx:e,body:t?{password:O(t)}:{}})}))}};re([u("/avatar"),c("auth"),c("upload",(e=>({count:1,field:"file",path:e.controller.dir,types:["image/bmp","image/jpeg","image/png"],size:32}))),ie(0,r()),ie(1,I()),ie(2,be()),ne("design:type",Function),ne("design:paramtypes",[a,Array,ye]),ne("design:returntype",Promise)],Ue.prototype,"avatar",null),re([p("/avatar/remove"),c("auth"),ie(0,r()),ie(1,be()),ne("design:type",Function),ne("design:paramtypes",[a,ye]),ne("design:returntype",Promise)],Ue.prototype,"avatar_remove",null),re([u("/password"),c("auth"),c("validation",{oldPassword:N.string().min(5).required(),newPassword:N.string().min(5).required()}),ie(0,r()),ie(1,l("oldPassword")),ie(2,l("newPassword")),ie(3,be()),ne("design:type",Function),ne("design:paramtypes",[a,String,String,ye]),ne("design:returntype",Promise)],Ue.prototype,"password",null),re([p("/token"),c("auth"),ie(0,r()),ie(1,be()),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,ye,Te]),ne("design:returntype",Promise)],Ue.prototype,"token",null),re([p("/token/:id"),c("auth"),c("write"),ie(0,r()),ie(1,f("id")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ue.prototype,"token_get",null),re([p("/token/remove/:id"),c("auth"),c("write"),ie(0,r()),ie(1,f("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"token_remove",null),re([p("/token/renew/:id"),c("auth"),c("write"),ie(0,r()),ie(1,f("id")),ie(2,n()),ne("design:type",Function),ne("design:paramtypes",[a,String,Te]),ne("design:returntype",Promise)],Ue.prototype,"token_renew",null),re([u(),c("auth"),c("write"),c("validation",{name:N.string().required(),email:N.string().email().required(),username:N.string().min(4).required(),password:N.string().min(5).required(),description:N.string().empty(""),state:N.boolean().parse().required()}),ie(0,r()),ie(1,l("password")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"add",null),re([p(),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Ue.prototype,"all",null),re([m("/:id"),c("auth"),c("write"),ie(0,r()),ie(1,be()),ie(2,f("id")),ne("design:type",Function),ne("design:paramtypes",[a,ye,String]),ne("design:returntype",Promise)],Ue.prototype,"del",null),re([p("/:id"),c("auth"),c("read"),ie(0,r()),ne("design:type",Function),ne("design:paramtypes",[a]),ne("design:returntype",Promise)],Ue.prototype,"get",null),re([_("/:id"),c("auth"),c("write"),c("validation",{name:N.string().empty(),email:N.string().email().empty(),username:N.string().min(4).empty(),password:N.string().min(5).empty().filter(""),description:N.string().empty(),state:N.boolean().parse().empty()}),ie(0,r()),ie(1,l("password")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ue.prototype,"set",null),Ue=re([g("/users"),h(qe),ne("design:paramtypes",[])],Ue);let Ge=class extends qe{model(){return me}all(e,t){return se(this,void 0,void 0,(function*(){yield this._all({ctx:e,options:{where:{userId:t},include:[{model:le,required:!0}]},callback:e=>e.map((e=>e.group))})}))}set(e,t,r){return se(this,void 0,void 0,(function*(){const i=yield ye.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 le.count({where:{id:r[t]}}),e&&(yield me.create({userId:i.id,groupId:r[t]}))}return e.success("OK")}if(L(i))return e.notFound("Record not found");e.error("Internal Server Error")}))}};re([p("/:id/groups"),c("auth"),c("read","users"),ie(0,r()),ie(1,f("id")),ne("design:type",Function),ne("design:paramtypes",[a,String]),ne("design:returntype",Promise)],Ge.prototype,"all",null),re([_("/:id/groups"),c("auth"),c("write","users"),c("validation",{groups:N.array(N.number().parse())}),ie(0,r()),ie(1,f("id")),ie(2,l("groups")),ne("design:type",Function),ne("design:paramtypes",[a,String,Array]),ne("design:returntype",Promise)],Ge.prototype,"set",null),Ge=re([g("/users"),h(qe)],Ge);export{Te as Application,ue as Auth,Ne as AuthController,we as Config,_e as Configs,De as ControllerBase,Be as CrudController,de as Database,oe as Env,xe as FilesController,ce as Forgot,Fe as ForgotController,le as Group,pe as GroupRoute,Le as GroupsController,je as GroupsRoutesController,fe as Log,Ie as Logs,Ke as LogsController,qe as ModelController,ke as Permission,ge as Register,Ce as RegisterController,Re as ReqAuth,be as ReqUser,he as Route,He as RoutesController,ve as Session,Me as SetupController,Se as Token,ye as User,me as UserGroup,Ue as UsersController,Ge as UsersGroupsController,Ae as crt,Ee as key,ae as sequelize};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.1",
|
|
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",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@andrewcaires/express": "^1.1.10",
|
|
49
|
-
"@andrewcaires/node": "^1.1.
|
|
49
|
+
"@andrewcaires/node": "^1.1.2",
|
|
50
50
|
"@andrewcaires/utils.js": "^0.3.1",
|
|
51
51
|
"cors": "^2.8.5",
|
|
52
52
|
"dotenv": "^16.4.5",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"@types/cors": "^2.8.17",
|
|
65
65
|
"@types/express-session": "^1.18.0",
|
|
66
66
|
"@types/jsonwebtoken": "^9.0.6",
|
|
67
|
-
"@types/node": "^20.14.
|
|
67
|
+
"@types/node": "^20.14.8",
|
|
68
68
|
"@types/ws": "^8.5.10",
|
|
69
69
|
"eslint": "^9.5.0",
|
|
70
70
|
"rollup": "^4.18.0",
|