@andrewcaires/api 4.4.2 → 4.5.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/LICENSE +1 -1
- package/dist/index.cjs.js +4 -4
- package/dist/index.d.ts +83 -107
- package/dist/index.esm.js +4 -4
- package/package.json +16 -16
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2015-
|
|
3
|
+
Copyright (c) 2015-2026 Andrew Caires (https://github.com/andrewcaires)
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
3
|
-
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
-
* (c)
|
|
2
|
+
* @andrewcaires/api v4.5.1
|
|
3
|
+
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
+
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
"use strict";var e=require("@andrewcaires/utils.js"),t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("dotenv"),i=require("@andrewcaires/sequelize"),s=require("jsonwebtoken"),n=require("fs"),d=require("ws"),a=require("express-session"),p=require("sequelize"),l=require("path");class u extends e.EventEmitter{}function c(e,t,r,o){var i,s=arguments.length,n=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function g(e,t){return function(r,o){t(r,o,e)}}function y(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,r,o){return new(r||(r=Promise))(function(i,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}a((o=o.apply(e,t||[])).next())})}u.ATTRIBUTES=Symbol("ATTRIBUTES"),u.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError,o.config({quiet:!0});class x extends r.Env{}x.API_BASE_NAME=x.getString("API_BASE_NAME",""),x.API_BODYPARSER_STRICT=x.getBool("API_BODYPARSER_STRICT",!0),x.API_BODYPARSER_INFLATE=x.getBool("API_BODYPARSER_INFLATE",!0),x.API_BODYPARSER_LIMIT=x.getString("API_BODYPARSER_LIMIT","10mb"),x.API_BODYPARSER_TYPE=x.getString("API_BODYPARSER_TYPE","json"),x.API_CONSOLE_ERROR=x.getBool("API_CONSOLE_ERROR",!1),x.API_DB_DATABASE=x.getString("API_DB_DATABASE",""),x.API_DB_HOST=x.getString("API_DB_HOST","127.0.0.1"),x.API_DB_PASSWORD=x.getString("API_DB_PASSWORD",""),x.API_DB_PORT=x.getInt("API_DB_PORT",3306),x.API_DB_TYPE=x.getString("API_DB_TYPE",""),x.API_DB_USERNAME=x.getString("API_DB_USERNAME","root"),x.API_DB_LOG=x.getBool("API_DB_LOG",!1),x.API_DB_AUDIT=x.getBool("API_DB_AUDIT",!0),x.API_DB_PREFIX=x.getString("API_DB_PREFIX",""),x.API_DB_TIMEZONE=x.getString("API_DB_TIMEZONE","+00:00"),x.API_HTTP_CRT=x.getString("API_HTTP_CRT",""),x.API_HTTP_KEY=x.getString("API_HTTP_KEY",""),x.API_HTTP_PORT=x.getInt("API_HTTP_PORT",3e3),x.API_HTTP_PUBLIC=x.getString("API_HTTP_PUBLIC",""),x.API_HTTP_CROSS=x.getBool("API_HTTP_CROSS",!1),x.API_HTTP_HYBRID=x.getBool("API_HTTP_HYBRID",!1),x.API_HTTP_NOTFOUND=x.getString("API_HTTP_NOTFOUND",""),x.API_HTTP_PATH=x.getString("API_HTTP_PATH","/api"),x.API_HTTP_REDIRECT=x.getString("API_HTTP_REDIRECT",""),x.API_KEY_HASH=x.getString("API_KEY_HASH",""),x.API_KEY_HEADER=x.getString("API_KEY_HEADER","x-api-key"),x.API_MODEL_LIMIT=x.getInt("API_MODEL_LIMIT",10),x.API_MODEL_LIMIT_MAX=x.getInt("API_MODEL_LIMIT_MAX",500),x.API_SLEEP_AUTH=x.getMs("API_SLEEP_AUTH","2s"),x.API_SLEEP_FORGOT=x.getMs("API_SLEEP_FORGOT","5s"),x.API_SLEEP_REGISTRY=x.getMs("API_SLEEP_REGISTRY","5s"),x.API_SESSION_NAME=x.getString("API_SESSION_NAME","session.id"),x.API_SESSION_LIFETIME=x.getMs("API_SESSION_LIFETIME","1d"),x.API_SESSION_SECRET=x.getString("API_SESSION_SECRET","yoursecret"),x.API_TOKEN_CRT=x.getString("API_TOKEN_CRT",""),x.API_TOKEN_KEY=x.getString("API_TOKEN_KEY",""),x.API_TOKEN_FORGOT=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_HEADER=x.getString("API_TOKEN_HEADER","authorization"),x.API_TOKEN_HEADER_KEY=x.getString("API_TOKEN_HEADER","bearer"),x.API_TOKEN_LIFETIME=x.getMs("API_TOKEN_LIFETIME","1d"),x.API_TOKEN_RENEW=x.getMs("API_TOKEN_RENEW","1d"),x.API_UPLOAD_COUNT=x.getInt("API_UPLOAD_COUNT",1),x.API_UPLOAD_FIELD=x.getString("API_UPLOAD_FIELD","upload"),x.API_UPLOAD_SIZE=x.getInt("API_UPLOAD_SIZE",2),x.API_UPLOAD_TEMP=x.getString("API_UPLOAD_TEMP","./temp"),x.API_USER_HISTORY=x.getBool("API_USER_HISTORY",!0),x.API_WEBSOCKET_START=x.getBool("API_WEBSOCKET_START",!1);const m=e=>{var t,r,o,i,s,n,d,a,p;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.protocol)+"://"+(null===(o=null==e?void 0:e.req)||void 0===o?void 0:o.get("host"))+(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.originalUrl),audit_user_agent:null!==(n=null===(s=e.req)||void 0===s?void 0:s.headers["user-agent"])&&void 0!==n?n:"",audit_user_id:null!==(p=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==p?p:null}},v=t.parameterFactory(({ctx:e})=>m(e)),A=t.parameterFactory(({ctx:e})=>e.req.auth),_=t.parameterFactory(({ctx:e})=>e.req.user),S=e=>t=>{E.migrations(t).version=e};class E{static migrations(e){return r.Metadata(E.MIGRATE,e,{version:""})}}E.MIGRATE=Symbol("MIGRATE");const P=new i.Connection({type:x.API_DB_TYPE,database:x.API_DB_DATABASE,username:x.API_DB_USERNAME,password:x.API_DB_PASSWORD,hostname:x.API_DB_HOST,hostport:x.API_DB_PORT,logging:x.API_DB_LOG,prefix:x.API_DB_PREFIX,timezone:x.API_DB_TIMEZONE}),C=(e,t,r)=>{var o,i,s,n,d;return{type:e,model:null!==(o=null==t?void 0:t.getTableName())&&void 0!==o?o:null,client:null!==(i=null==r?void 0:r.audit_client)&&void 0!==i?i:null,href:null!==(s=null==r?void 0:r.audit_href)&&void 0!==s?s:null,user_agent:null!==(n=null==r?void 0:r.audit_user_agent)&&void 0!==n?n:null,user_id:null!==(d=null==r?void 0:r.audit_user_id)&&void 0!==d?d:null,state:!0}},O={afterCreate:(t,r)=>h(void 0,void 0,void 0,function*(){var o;if(!x.API_DB_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},C("CREATE",i,r)),{record:s?t.getDataValue(s):null,data:t.toJSON()})).catch(e.noop)}),afterUpdate:(t,r)=>h(void 0,void 0,void 0,function*(){var o;if(!x.API_DB_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null,n={},d=t.changed();d&&d.forEach(e=>n[e]=t.getDataValue(e)),yield exports.Audit.create(Object.assign(Object.assign({},C("UPDATE",i,r)),{record:s?t.getDataValue(s):null,data:n,previously:t.previous()})).catch(e.noop)}),afterDestroy:(t,r)=>h(void 0,void 0,void 0,function*(){var o;if(!x.API_DB_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},C("DELETE",i,r)),{record:s?t.getDataValue(s):null,data:t.toJSON()})).catch(e.noop)})};exports.Auth=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Auth.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Auth.prototype,"secret",void 0),c([i.FullDate(),y("design:type",Object)],exports.Auth.prototype,"logout",void 0),c([i.String(),y("design:type",i.String)],exports.Auth.prototype,"user_agent",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Auth.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Auth.prototype,"deleted_at",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=c([i.Database(P),i.ModelName("auth"),S("4.2.0")],exports.Auth),exports.Register=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Register.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Register.prototype,"token",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.Register.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Register.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Register.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Register.prototype,"deleted_at",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=c([i.Database(P),i.ModelName("register"),S("4.2.0")],exports.Register),exports.Group=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Group.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Group.prototype,"name",void 0),c([i.Text(),y("design:type",i.String)],exports.Group.prototype,"description",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.Group.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Group.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Group.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Group.prototype,"deleted_at",void 0),c([i.HasMany(()=>exports.UserGroup,"group_id"),y("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),c([i.HasMany(()=>exports.UserGroup,"group_id"),y("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=c([i.Database(P),i.ModelName("group"),i.Hooks(O),S("4.2.0")],exports.Group),exports.UserGroup=class extends i.Model{},c([i.CreatedAt,y("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),c([i.BelongsTo(()=>exports.Group),y("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=c([i.Database(P),i.ModelName("users_groups"),i.Hooks(O),S("4.2.0")],exports.UserGroup),exports.UserHistory=class extends i.Model{},c([i.String(),y("design:type",i.String)],exports.UserHistory.prototype,"password",void 0),c([i.CreatedAt,y("design:type",Date)],exports.UserHistory.prototype,"created_at",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.UserHistory.prototype,"user_id",void 0),exports.UserHistory=c([i.Database(P),i.ModelName("users_histories"),S("4.2.0")],exports.UserHistory),exports.User=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.User.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"name",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"email",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"username",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"password",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"salt",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"token",void 0),c([i.String(),y("design:type",i.String)],exports.User.prototype,"avatar",void 0),c([i.DateOnly(),y("design:type",i.String)],exports.User.prototype,"date",void 0),c([i.Text(),y("design:type",i.String)],exports.User.prototype,"description",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.User.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.User.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.User.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.User.prototype,"deleted_at",void 0),c([i.HasMany(()=>exports.Audit,"user_id"),y("design:type",Array)],exports.User.prototype,"audits",void 0),c([i.HasMany(()=>exports.Auth,"user_id"),y("design:type",Array)],exports.User.prototype,"auths",void 0),c([i.HasMany(()=>exports.Register,"user_id"),y("design:type",Array)],exports.User.prototype,"registers",void 0),c([i.HasMany(()=>exports.UserGroup,"user_id"),y("design:type",Array)],exports.User.prototype,"users_groups",void 0),c([i.HasMany(()=>exports.UserHistory,"user_id"),y("design:type",Array)],exports.User.prototype,"users_histories",void 0),exports.User=c([i.Database(P),i.ModelName("user"),i.DefaultScope({attributes:{exclude:["password","salt","token"]}}),i.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),i.Hooks(O),S("4.2.0")],exports.User),exports.Audit=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Audit.prototype,"id",void 0),c([i.Enum("CREATE","DELETE","UPDATE"),y("design:type",i.String)],exports.Audit.prototype,"type",void 0),c([i.String(),y("design:type",i.String)],exports.Audit.prototype,"model",void 0),c([i.String(),y("design:type",i.String)],exports.Audit.prototype,"record",void 0),c([i.Json(),y("design:type",Object)],exports.Audit.prototype,"data",void 0),c([i.Json(),y("design:type",Object)],exports.Audit.prototype,"previously",void 0),c([i.String(),y("design:type",i.String)],exports.Audit.prototype,"client",void 0),c([i.Text(),y("design:type",i.String)],exports.Audit.prototype,"href",void 0),c([i.String(),y("design:type",i.String)],exports.Audit.prototype,"user_agent",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.Audit.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Audit.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Audit.prototype,"deleted_at",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=c([i.Database(P),i.ModelName("audit"),S("4.2.0")],exports.Audit),exports.Config=class extends i.Model{static all(){return h(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return h(this,void 0,void 0,function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(this.error))||0)>0})}static get(e){return h(this,arguments,void 0,function*(e,t=""){const[r]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t,r){return h(this,void 0,void 0,function*(){var o;const i=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[s]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(this.error))||[];s&&(s.value=t,yield s.save().catch(this.error))})}},c([i.String(),y("design:type",i.String)],exports.Config.prototype,"key",void 0),c([i.String(),y("design:type",i.String)],exports.Config.prototype,"value",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Config.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Config.prototype,"updated_at",void 0),exports.Config=c([i.Database(P),i.ModelName("configs"),S("4.2.0")],exports.Config),exports.Forgot=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Forgot.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Forgot.prototype,"token",void 0),c([i.BigInt(),y("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.Forgot.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Forgot.prototype,"deleted_at",void 0),c([i.BelongsTo(()=>exports.User),y("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=c([i.Database(P),i.ModelName("forgot"),S("4.2.0")],exports.Forgot),exports.Permission=class extends i.Model{},c([i.Id(),y("design:type",Number)],exports.Permission.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Permission.prototype,"name",void 0),c([i.String(),i.Unique(!0),y("design:type",i.String)],exports.Permission.prototype,"route",void 0),c([i.String(),y("design:type",i.String)],exports.Permission.prototype,"tag",void 0),c([i.Text(),y("design:type",i.String)],exports.Permission.prototype,"description",void 0),c([i.Boolean(),y("design:type",i.Boolean)],exports.Permission.prototype,"state",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Permission.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),c([i.DeletedAt,y("design:type",Object)],exports.Permission.prototype,"deleted_at",void 0),c([i.HasMany(()=>exports.GroupPermission,"permission_id"),y("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=c([i.Database(P),i.ModelName("permission"),i.Hooks(O),S("4.3.1")],exports.Permission),exports.GroupPermission=class extends i.Model{},c([i.CreatedAt,y("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),c([i.BelongsTo(()=>exports.Group),y("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),c([i.BelongsTo(()=>exports.Permission),y("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=c([i.Database(P),i.ModelName("groups_permissions"),i.Hooks(O),S("4.2.0")],exports.GroupPermission),exports.Log=class extends i.Model{static write(e,t,o){return h(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.White,"",e,t,o)})}static error(e,t,o){return h(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Red,"error",e,t,o)})}static info(e,t,o){return h(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Cyan,"info",e,t,o)})}static success(e,t,o){return h(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Green,"success",e,t,o)})}static warning(e,t,o){return h(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Yellow,"warning",e,t,o)})}static writeRaw(e,t,o,i,s){return h(this,void 0,void 0,function*(){s&&r.Log.console(e,t,o),P&&(yield this.create({type:t,source:i,message:o}).catch(this.error))})}},c([i.Id(),y("design:type",Number)],exports.Log.prototype,"id",void 0),c([i.String(),y("design:type",i.String)],exports.Log.prototype,"type",void 0),c([i.String(),y("design:type",i.String)],exports.Log.prototype,"source",void 0),c([i.Text(),y("design:type",i.String)],exports.Log.prototype,"message",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=c([i.Database(P),i.ModelName("log"),S("4.2.0")],exports.Log),exports.Migration=class extends i.Model{},c([i.String(),y("design:type",i.String)],exports.Migration.prototype,"model",void 0),c([i.String(),y("design:type",i.String)],exports.Migration.prototype,"version",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Migration.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Migration.prototype,"updated_at",void 0),exports.Migration=c([i.Database(P),i.ModelName("migration"),S("4.2.0")],exports.Migration),exports.Session=class extends i.Model{},c([i.String(),y("design:type",i.String)],exports.Session.prototype,"session",void 0),c([i.Text(),y("design:type",i.String)],exports.Session.prototype,"json",void 0),c([i.BigInt(),y("design:type",Number)],exports.Session.prototype,"expired",void 0),c([i.CreatedAt,y("design:type",Date)],exports.Session.prototype,"created_at",void 0),c([i.UpdatedAt,y("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=c([i.Database(P),i.ModelName("session"),S("4.2.0")],exports.Session);class I{static error(e){let t="token";x.API_BASE_NAME&&(t=`${x.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,x.API_CONSOLE_ERROR)}}class f extends I{static user(e,t){return h(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const r=t.hash.encrypt(e),o=yield exports.User.findOne({where:{token:r,state:!0}}).catch(this.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(this.error))||[];if(r)return r.logout&&(r.logout=null,yield r.save().catch(this.error)),{auth:r,user:o}}return{error:"ACCESS DENIED"}})}}const R=e=>n.existsSync(e)?n.readFileSync(e):void 0,T={http:R(x.API_HTTP_CRT),token:R(x.API_TOKEN_CRT)},D={http:R(x.API_HTTP_KEY),token:R(x.API_TOKEN_KEY)};class w extends I{static options(){return{algorithm:"RS256",expiresIn:`${x.API_TOKEN_LIFETIME}ms`}}static create(t){return h(this,void 0,void 0,function*(){if(!D.token)return{error:"KEY NOT FOUND"};const{id:r}=t,o=e.uuidv4(),i=yield exports.Auth.create({secret:o,user_id:r}).catch(this.error);if(!i)return{error:"INTERNAL SERVER ERROR"};return{auth:i,token:s.sign({id:r,secret:o},D.token,this.options())}})}static destroy(e){return h(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static renew(t){return h(this,void 0,void 0,function*(){if(!D.token)return{error:"KEY NOT FOUND"};const{error:r,decode:o}=this.verify(t,x.API_TOKEN_RENEW/1e3);if(r)return{error:r};if(o){const{id:t,secret:r}=o;if(t&&r){const o=yield exports.User.findOne({where:{id:t,state:!0}}).catch(this.error);if(o){const i=yield exports.Auth.findOne({where:{secret:r,user_id:o.id}}).catch(this.error);if(i&&!i.logout){i.secret=e.uuidv4(),yield i.save().catch(this.error);return{auth:i,token:s.sign({id:t,secret:i.secret},D.token,this.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e){return h(this,void 0,void 0,function*(){const{error:t,decode:r}=this.verify(e);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(this.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!T.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:s.verify(e,T.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class N extends a.Store{constructor(){super(),this.all=t=>h(this,void 0,void 0,function*(){t=t||e.noop;const r=yield exports.Session.findAll({attributes:["session"],where:{expired:{[p.Op.gte]:Date.now()}}}).catch(e=>(t(e),null));r&&t(null,r.map(e=>e.session)),t()}),this.clear=t=>h(this,void 0,void 0,function*(){yield exports.Session.destroy().catch(e.noop),t&&t()}),this.destroy=(t,r)=>h(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{session:t}}).catch(e.noop),r&&r()}),this.expired=()=>h(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{expired:{[p.Op.lt]:Date.now()}}}).catch(e.noop)}),this.get=(t,r)=>h(this,void 0,void 0,function*(){r=r||e.noop;const o=yield exports.Session.findOne({where:{session:t,expired:{[p.Op.gte]:Date.now()}}}).catch(e=>(r(e),null));if(o){const t=JSON.parse(o.json);if(t.cookie){if(new Date(t.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(e.noop),void r(null)}return void r(null,t)}r(null)}),this.length=t=>h(this,void 0,void 0,function*(){t&&t(null,(yield exports.Session.count().catch(e.noop))||0)}),this.set=(t,r,o)=>h(this,void 0,void 0,function*(){o=o||e.noop;const i=Date.now()+x.API_SESSION_LIFETIME,s=JSON.stringify(r),[n,d]=(yield exports.Session.findOrCreate({where:{session:t},defaults:{session:t,json:s,expired:i}}).catch(e.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(e.noop))),o()}),this.loop=e.loop(this.expired,3e4),this.loop.start()}}class U extends t.Application{constructor(t){super(t,{cert:T.http,cross:x.API_HTTP_CROSS,hybrid:x.API_HTTP_HYBRID,json:{strict:x.API_BODYPARSER_STRICT,inflate:x.API_BODYPARSER_INFLATE,limit:x.API_BODYPARSER_LIMIT,type:x.API_BODYPARSER_TYPE},key:D.http,notfound:x.API_HTTP_NOTFOUND,path:x.API_HTTP_PATH,port:x.API_HTTP_PORT,public:x.API_HTTP_PUBLIC,redirect:x.API_HTTP_REDIRECT,session:{store:new N,name:x.API_SESSION_NAME,secret:x.API_SESSION_SECRET,cookie:{maxAge:x.API_SESSION_LIFETIME},genid:e.uuidv4}}),this.hash=new r.Hash(x.API_KEY_HASH)}error(e,t){x.API_BASE_NAME&&(t=t?`${x.API_BASE_NAME}.${t}`:x.API_BASE_NAME),exports.Log.error(e.message,t,x.API_CONSOLE_ERROR)}log(e,t){x.API_BASE_NAME&&(t=t?`${x.API_BASE_NAME}.${t}`:x.API_BASE_NAME),exports.Log.info(e,t,!0)}listen(){const t=Object.create(null,{listen:{get:()=>super.listen}});return h(this,void 0,void 0,function*(){yield P.sync(),yield this.migrations(P),yield e.forEachSeries(this.controllers,t=>h(this,void 0,void 0,function*(){e.isFunction(t.sync)&&(yield t.sync(this))})),yield t.listen.call(this),x.API_WEBSOCKET_START&&this.server&&(this._webSocket=new d.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(x.API_WEBSOCKET_START)}),this._webSocket.on("connection",(t,r)=>h(this,void 0,void 0,function*(){r.url||(r.url="");const o=r.url.length<=1?"":r.url.replace(/\//g,".");let i;t.on("message",e=>h(this,void 0,void 0,function*(){if(i)try{const s=JSON.parse(e);this.emit("ws.message"+o,{data:s,message:e,req:r,user:i,ws:t})}catch(s){this.emit("ws.message"+o,{erro:s,message:e,req:r,user:i,ws:t})}else{const{user:s}=yield w.user(e.toString());s&&(i=s,this.emit("ws.connection"+o,{req:r,user:i,ws:t}))}i||t.close()})),t.on("close",()=>{i&&this.emit("ws.close"+o,{user:i,ws:t})}),yield e.sleep(2e3),i||t.close()})))})}migrations(t){return h(this,void 0,void 0,function*(){const r=[];yield e.forEachSeries(Object.keys(t.models),e=>h(this,void 0,void 0,function*(){var o;const i=t.models[e],{version:s}=E.migrations(i);if(!s)return;const[n,d]=null!==(o=yield exports.Migration.findOrCreate({where:{model:i.tableName},defaults:{model:i.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=s)&&(n.version=s,yield n.save().catch(this.error),r.push(i))})),r.length&&(yield i.migrate(t,r))})}websocket(){return this._webSocket}}var M,b,F,B,L;class k extends u{constructor(){super(...arguments),this[M]=[]}auth(e,t,r,o,i,s){return h(this,void 0,void 0,function*(){var n;t=null!=t?t:o;const[d,a]=null!==(n=null==r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(t||a&&d.toLowerCase()==x.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:p,error:l,user:u}=yield t?f.user(t,s):w.user(a);return l?e.error(l):p&&u?!t&&p.user_agent&&p.user_agent!=i?e.error("INVALID TOKEN"):(e.req.auth=p,e.req.user=u,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,r){return h(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",r)})}canDelete(e,t,r){return h(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",r)})}canRead(e,t,r){return h(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",r)})}canUpdate(e,t,r){return h(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",r)})}error(e){let t="controller_base";x.API_BASE_NAME&&(t=`${x.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,x.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,r){return h(this,void 0,void 0,function*(){if(r){if((yield this.permissions(r,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return h(this,void 0,void 0,function*(){var r;return null!==(r=yield exports.Permission.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:exports.GroupPermission,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==r?r:[]})}session(t,r,o){return h(this,void 0,void 0,function*(){o.auth&&o.user&&(o.user_agent?o.user_agent!=r&&o.regenerate(e.noop):(o.user_agent=r,o.save(e.noop))),t.next()})}sync(){return h(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r={description:"",state:!0};yield e.forEachSeries(this[u.PERMISSIONS],o=>h(this,void 0,void 0,function*(){const i=`${t}.${o}`,s=e.upperCamelCase(t.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${e.upperCamelCase(o," ")}`,route:i,tag:s},r)})}))})}upload(e,r){r.path||(r.path=x.API_UPLOAD_TEMP),r.size||(r.size=x.API_UPLOAD_SIZE),r.field||(r.field=x.API_UPLOAD_FIELD),t.Upload.middleware(e,r)}validation(t,r){return h(this,void 0,void 0,function*(){const{error:o,value:i}=yield e.Validation.object(r).parse().validateAsync(t.req.body);if(o)return t.validation(o);t.req.body=i,t.next()})}}M=u.PERMISSIONS,c([g(0,t.Ctx()),g(1,t.Headers(x.API_KEY_HEADER)),g(2,t.Headers(x.API_TOKEN_HEADER)),g(3,t.Query(x.API_KEY_HEADER)),g(4,t.Headers("user-agent")),g(5,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,String,String,U]),y("design:returntype",Promise)],k.prototype,"auth",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],k.prototype,"canCreate",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],k.prototype,"canDelete",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],k.prototype,"canRead",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],k.prototype,"canUpdate",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],k.prototype,"permission",null),c([g(0,t.Ctx()),g(1,t.Headers("user-agent")),g(2,t.Session()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object]),y("design:returntype",Promise)],k.prototype,"session",null),c([g(0,t.Ctx()),g(1,t.Argument()),y("design:type",Function),y("design:paramtypes",[t.Context,Object]),y("design:returntype",void 0)],k.prototype,"upload",null),c([g(0,t.Ctx()),g(1,t.Argument()),y("design:type",Function),y("design:paramtypes",[t.Context,Object]),y("design:returntype",Promise)],k.prototype,"validation",null),exports.ControllerModel=class extends k{constructor(){super(...arguments),this[b]=[],this[F]=["create","read","update","delete"]}attributes(t){if(0==this[k.ATTRIBUTES].length&&(this[k.ATTRIBUTES]=Object.keys(this.model().getAttributes())),e.isArray(t))return t.length?t.map(t=>e.isString(t)&&-1!=this[k.ATTRIBUTES].indexOf(t)?t:void 0).filter(e.isString):this[k.ATTRIBUTES];const{exclude:r,include:o}=t,i=e.isUndefined(o)?this[k.ATTRIBUTES]:o.map(t=>e.isString(t)&&-1!=this[k.ATTRIBUTES].indexOf(t)?t:void 0).filter(e.isString),s=null!=r?r:[];return s.length?i.filter(e=>-1==s.indexOf(e)?e:void 0).filter(e.isString):i}create(e){return h(this,arguments,void 0,function*({ctx:e,options:r,body:o}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),o||{}),Object.assign(Object.assign({},r||{}),m(e))).catch(this.error);if(i){const r=this.key();return e.prepare(t.Status.OK,{[r]:i.getDataValue(r)}),i}e.error("INTERNAL SERVER ERROR")})}delete(e){return h(this,arguments,void 0,function*({ctx:e,options:t}){const r=this.key(),{[r]:o}=e.req.params;if(!o)return e.error("INTERNAL SERVER ERROR"),0;const i=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o}),individualHooks:!0}),m(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";x.API_BASE_NAME&&(t=`${x.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?exports.Log.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,x.API_CONSOLE_ERROR):super.error(e)}findAll(r){return h(this,arguments,void 0,function*({ctx:r,options:o,callback:s,scope:n,advanced:d,attributes:a,limited:l}){var u,c,g;const y=this.scope(n),h=Object.assign({},o||{}),{fields:m,limit:v,offset:A,asc:_,desc:S,search:E,where:P}=r.req.query;if(e.isUndefined(h.limit)){let t=x.API_MODEL_LIMIT;e.isString(v)&&(t=parseInt(v)||0),t=e.clamp(t,-1,x.API_MODEL_LIMIT_MAX),h.limit=t>0?t:l?x.API_MODEL_LIMIT:void 0}if(e.isNumber(h.limit)&&(h.limit=h.limit>0?h.limit:void 0),e.isString(A)){const e=parseInt(A)||0;h.offset=e>0?e:void 0}a=null!=a?a:this.attributes(null!==(u=null==h?void 0:h.attributes)&&void 0!==u?u:[]);const C=e=>a.indexOf(e)>=0,O=[];e.isString(m)&&O.push(...m.split(";").filter(C)),O.length&&(h.attributes=O);const I=[];if(e.isString(_)&&_.length&&I.push(..._.split(";").filter(C).map(e=>[e,"ASC"])),e.isString(S)&&S.length&&I.push(...S.split(";").filter(C).map(e=>[e,"DESC"])),I.length&&(h.order=I),h.where=Object.assign({},h.where||{}),e.isString(P)&&(null==d||d)){const t=i.Where.parse(a,P);if(!e.isUndefined(t.error))return r.validation(t.error.join(", ")),{count:0,records:[]};h.where=Object.assign(Object.assign({},h.where),null!==(c=t.value)&&void 0!==c?c:{})}else{const t=[];a.forEach(r=>{e.isString(E)&&E.length&&t.push({[r]:{[p.Op.like]:`%${E}%`}})}),t.length&&(h.where=Object.assign(Object.assign({},h.where),{[p.Op.or]:[...t]}))}const f=y.count(Object.assign(Object.assign({},h),{distinct:!!h.include,col:this[k.ATTRIBUTES].length?this[k.ATTRIBUTES][0]:void 0})).catch(this.error),R=y.findAll(h).catch(this.error);yield Promise.allSettled([f,R]);const T=null!==(g=yield f)&&void 0!==g?g:0;let D=yield R;const w={count:T};return D?(D=s?yield s(D):D,(e.isNumber(null==o?void 0:o.limit)||0==T)&&(w.count=D.length),r.prepare(t.Status.OK,Object.assign(Object.assign({},w),{records:D})),Object.assign(Object.assign({},w),{records:D})):(r.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},w),{records:[]}))})}findOne(e){return h(this,arguments,void 0,function*({ctx:e,options:r,callback:o,scope:i}){const s=this.key(),{[s]:n}=e.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[s]:n})})).catch(this.error);return d?(e.prepare(t.Status.OK,o?yield o(d):d.toJSON()),d):null===d?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return h(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r={description:"",state:!0};yield e.forEachSeries(this[k.PERMISSIONS],o=>h(this,void 0,void 0,function*(){const i=`${t}.${o}`,s=e.upperCamelCase(t.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${e.upperCamelCase(o," ")}`,route:i,tag:s},r)})}))})}update(e){return h(this,arguments,void 0,function*({ctx:e,options:t,body:r}){var o;const i=this.key(),{[i]:s}=e.req.params,[n]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:s}),individualHooks:!0}),m(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},b=k.ATTRIBUTES,F=k.PERMISSIONS,exports.ControllerModel=c([t.Extends(k)],exports.ControllerModel),exports.ControllerCrud=class extends exports.ControllerModel{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return h(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return h(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return h(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return h(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return h(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return h(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}},c([t.Post(),t.Middleware("auth"),t.Middleware("canCreate"),t.Middleware("validationCreate"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"add",null),c([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"all",null),c([t.Delete("/:id"),t.Middleware("auth"),t.Middleware("canDelete"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"del",null),c([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"get",null),c([t.Put("/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),t.Middleware("validationUpdate"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"set",null),c([g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationCreate",null),c([g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationUpdate",null),exports.ControllerCrud=c([t.Extends(exports.ControllerModel)],exports.ControllerCrud),exports.AuditsController=class extends exports.ControllerModel{model(){return exports.Audit}all(e,t,r){return h(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},limited:!0})})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},c([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),g(1,t.Query("type")),g(2,t.Query("table")),y("design:type",Function),y("design:paramtypes",[t.Context,String,String]),y("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),c([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=c([t.Controller("/audits"),t.Extends(exports.ControllerModel)],exports.AuditsController),exports.AuthController=class extends k{login(t,o,i,s,n){return h(this,void 0,void 0,function*(){var d;yield e.sleep(x.API_SLEEP_AUTH);const a=yield exports.User.scope("password").findOne({where:{[p.Op.or]:[{email:i},{username:i}]}}).catch(this.error);if(s+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",!a||a.password!=r.sha256(s))return t.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t});const l=yield exports.Register.findOne({where:{state:!0,user_id:a.id}}).catch(this.error);if(l)return t.error("ACTIVATION REQUIRED"),n.emit("auth.activation",{ctx:t,register:l,user:a}),void this.emit("auth.activation",{ctx:t,register:l,user:a});if(!a.state)return t.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:t,user:a}),void this.emit("auth.failure",{ctx:t,user:a});const{auth:u,error:c,token:g}=yield w.create(a);return c?(t.error(c),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t})):u&&g?(u.user_agent=o,yield u.save().catch(this.error),t.json({token:g}),n.emit("auth.login",{auth:u,ctx:t,user:a}),void this.emit("auth.login",{auth:u,ctx:t,user:a})):(t.error("INTERNAL SERVER ERROR"),n.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t}))})}logout(e,t,r,o){return h(this,void 0,void 0,function*(){if(yield w.destroy(t))return e.success("OK"),o.emit("auth.logout",{auth:t,ctx:e,user:r}),void this.emit("auth.logout",{auth:t,ctx:e,user:r});e.unauthorized("ACCESS DENIED")})}renew(e,t,r,o){return h(this,void 0,void 0,function*(){const{auth:i,error:s,token:n}=yield w.renew(r);return s?e.error(s):i?(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("INTERNAL SERVER ERROR")})}user(t,r){return h(this,void 0,void 0,function*(){const o=yield this.permissions(r);if(!o)return t.error("INTERNAL SERVER ERROR");t.json(Object.assign(Object.assign({},e.denied(["username","date","description","state","created_at","updated_at","deleted_at"],r.toJSON())),{permissions:o.map(e=>e.route)}))})}},c([t.Post("/login"),t.Middleware("validation",{username:e.Validation.string().min(3).required(),password:e.Validation.string().min(5).required()}),g(0,t.Ctx()),g(1,t.Headers("user-agent")),g(2,t.Body("username")),g(3,t.Body("password")),g(4,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,String,U]),y("design:returntype",Promise)],exports.AuthController.prototype,"login",null),c([t.Get("/logout"),t.Middleware("auth"),g(0,t.Ctx()),g(1,A()),g(2,_()),g(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.Auth,exports.User,U]),y("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),c([t.Post("/renew"),t.Middleware("validation",{token:e.Validation.string().required()}),g(0,t.Ctx()),g(1,t.Headers("user-agent")),g(2,t.Body("token")),g(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,U]),y("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),c([t.Get(),t.Middleware("auth"),g(0,t.Ctx()),g(1,_()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.User]),y("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=c([t.Controller("/auth"),t.Extends(k)],exports.AuthController),exports.FilesController=class extends k{constructor(){super(...arguments),this[B]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return x.API_HTTP_PUBLIC||"./"}files(t){return h(this,void 0,void 0,function*(){let{path:r}=t.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=l.join(this.directory(),r);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return t.notFound("RECORD NOT FOUND");let i=[];return i=n.readdirSync(o),i=i.map(e=>this.info(l.join(o,e))),i=i.filter(e.isDef),Object.assign(Object.assign({},this.info(o)),{files:i})})}access(e,t,r){return h(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,r)})}info(e){if(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return h(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r=e.upperCamelCase(t.replace(/_/g," ")," "),o={description:"",state:!0};yield e.forEachSeries(this[k.PERMISSIONS],i=>h(this,void 0,void 0,function*(){const s=`${t}.${i}`;yield exports.Permission.findOrCreate({where:{route:s},defaults:Object.assign({name:`${r} ${e.upperCamelCase(i," ")}`,route:s,tag:r},o)})}))})}},B=k.PERMISSIONS,c([t.Get("/path"),t.Get("/path/*path"),t.Middleware("auth"),t.Middleware("access","list"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.FilesController.prototype,"files",null),c([g(0,t.Ctx()),g(1,t.Argument()),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=c([t.Controller("/files"),t.Extends(k)],exports.FilesController),exports.ForgotController=class extends k{check(t,r){return h(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o||!o.user)return t.notFound("RECORD NOT FOUND");o.token=e.uniqueID(),yield o.save(),t.json({token:o.token})})}forgot(t,r,o){return h(this,void 0,void 0,function*(){yield e.sleep(x.API_SLEEP_FORGOT);const i=r,s=yield exports.User.findOne({where:{[p.Op.or]:[{email:i},{username:r}]}}).catch(this.error);if(!s)return t.notFound("RECORD NOT FOUND");const n=e.uniqueID(),d=Date.now()+6e4*x.API_TOKEN_FORGOT,a=yield exports.Forgot.create({token:n,timestamp:d,state:!0,user_id:s.id});t.success("OK"),o.emit("forgot.send",{ctx:t,forgot:a,user:s}),this.emit("forgot.send",{ctx:t,forgot:a,user:s})})}reset(e,t,o,i){return h(this,void 0,void 0,function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=r.sha256(o),yield s.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})})}find(e){return h(this,void 0,void 0,function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)})}},c([t.Get("/check"),t.Middleware("validation",{token:e.Validation.string().required()}),g(0,t.Ctx()),g(1,t.Body("token")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),c([t.Post(),t.Middleware("validation",{username:e.Validation.string().min(4).required()}),g(0,t.Ctx()),g(1,t.Body("username")),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,U]),y("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),c([t.Post("/reset"),t.Middleware("validation",{token:e.Validation.string().required(),password:e.Validation.string().min(5).required()}),g(0,t.Ctx()),g(1,t.Body("token")),g(2,t.Body("password")),g(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,U]),y("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=c([t.Controller("/forgot"),t.Extends(k)],exports.ForgotController),exports.GroupsController=class extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:e.Validation.string().required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()},this.schemaUpdate={name:e.Validation.string().empty(),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}}model(){return exports.Group}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.GroupsController=c([t.Controller("/groups"),t.Extends(exports.ControllerCrud)],exports.GroupsController),exports.GroupsPermissionsController=class extends exports.ControllerModel{model(){return exports.GroupPermission}all(e,t){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return h(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(t,r,o,i){return h(this,void 0,void 0,function*(){const s=yield exports.Group.findByPk(r,{attributes:["id"]}).catch(this.error);if(!s)return t.notFound("RECORD NOT FOUND");const n=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:n},individualHooks:!0},i)),o){let t=0;yield e.sleep(1e3);for(let e=0;e<o.length;e++)t=yield exports.Permission.count({where:{id:o[e]}}),t&&(yield exports.GroupPermission.create({group_id:n,permission_id:o[e]},Object.assign({},i)))}t.success("OK")})}},c([t.Get("/:id/permissions"),t.Middleware("auth"),t.Middleware("canRead","groups"),g(0,t.Ctx()),g(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),c([t.Get("/permissions"),t.Middleware("auth"),t.Middleware("canRead","users"),g(0,t.Ctx()),g(1,_()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.User]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"me",null),c([t.Put("/:id/permissions"),t.Middleware("auth"),t.Middleware("canUpdate","groups"),t.Middleware("validation",{permissions:e.Validation.array(e.Validation.number().parse())}),g(0,t.Ctx()),g(1,t.Params("id")),g(2,t.Body("permissions")),g(3,v()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array,Object]),y("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=c([t.Controller("/groups"),t.Extends(exports.ControllerModel)],exports.GroupsPermissionsController),exports.LogsController=class extends exports.ControllerModel{constructor(){super(...arguments),this[L]=["read"]}model(){return exports.Log}all(e,t,r){return h(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this.findAll({ctx:e,options:{where:o,order:[["created_at","DESC"]]},limited:!0})})}},L=exports.ControllerModel.PERMISSIONS,c([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),g(1,t.Query("type")),g(2,t.Query("source")),y("design:type",Function),y("design:paramtypes",[t.Context,String,String]),y("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=c([t.Controller("/logs"),t.Extends(exports.ControllerModel)],exports.LogsController),exports.PermissionsController=class extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:e.Validation.string().required(),route:e.Validation.string().required(),tag:e.Validation.string().required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()},this.schemaUpdate={name:e.Validation.string().empty(),route:e.Validation.string().empty(),tag:e.Validation.string().empty(),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}}model(){return exports.Permission}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=c([t.Controller("/permissions"),t.Extends(exports.ControllerCrud)],exports.PermissionsController),exports.RegisterController=class extends k{register(t,o,i){return h(this,void 0,void 0,function*(){yield e.sleep(x.API_SLEEP_REGISTRY);const{name:s,date:n,email:d,username:a,password:l,confirm:u}=o,c=a||d,g=r.sha256(l);if(yield exports.User.count({where:{[p.Op.or]:[{email:d},{username:c}]}}).catch(this.error))return t.validation("INVALID EMAIL OR USERNAME");if(g!=r.sha256(u))return t.error("INVALID PASSWORD");const y=yield exports.User.create({name:s,email:d,username:c,password:g,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!y)return t.error("INTERNAL SERVER ERROR");const h=yield exports.Register.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),t.error("INTERNAL SERVER ERROR");t.success("OK"),i.emit("register.user",{ctx:t,register:h,user:y}),this.emit("register.user",{ctx:t,register:h,user:y})})}confirm(e,t,r){return h(this,void 0,void 0,function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("RECORD 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 h(this,void 0,void 0,function*(){const o=t,i=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[p.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!i)return e.notFound("RECORD NOT FOUND");e.success("OK"),r.emit("register.send",{ctx:e,register:i,user:i.user}),this.emit("register.send",{ctx:e,register:i,user:i.user})})}getId(){return h(this,void 0,void 0,function*(){const t=e.uuidv4();return(yield exports.Register.count({where:{token:t}}))?this.getId():t})}},c([t.Post(),t.Middleware("validation",{name:e.Validation.string().required(),date:e.Validation.date().required(),email:e.Validation.string().email().required(),username:e.Validation.string().min(4).empty(),password:e.Validation.string().min(5).required(),confirm:e.Validation.string().min(5).required()}),g(0,t.Ctx()),g(1,t.Body()),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,Object,U]),y("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),c([t.Post("/confirm"),t.Middleware("validation",{token:e.Validation.string().required()}),g(0,t.Ctx()),g(1,t.Body("token")),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,U]),y("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),c([t.Post("/send"),t.Middleware("validation",{username:e.Validation.string().min(4).required()}),g(0,t.Ctx()),g(1,t.Body("username")),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,U]),y("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=c([t.Controller("/register"),t.Extends(k)],exports.RegisterController),exports.SetupController=class extends k{setup(t,o){return h(this,void 0,void 0,function*(){var i;if(yield exports.User.count())return t.success("OK");const s=e.uniqueID(),n=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+s),salt:s,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},o)),d=yield exports.Group.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},o));yield exports.UserGroup.create({user_id:n.id,group_id:d.id},Object.assign({},o));const a=null!==(i=yield exports.Permission.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield e.forEachSeries(a,e=>h(this,void 0,void 0,function*(){yield exports.GroupPermission.create({group_id:d.id,permission_id:e.id},Object.assign({},o))})),t.success("OK")})}},c([t.Get(),g(0,t.Ctx()),g(1,v()),y("design:type",Function),y("design:paramtypes",[t.Context,Object]),y("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=c([t.Controller("/setup"),t.Extends(k)],exports.SetupController),exports.UsersController=class extends exports.ControllerModel{model(){return exports.User}constructor(){super(),this.path=x.API_HTTP_PUBLIC+"/avatar",x.API_HTTP_PUBLIC&&n.existsSync(x.API_HTTP_PUBLIC)&&!n.existsSync(this.path)&&n.mkdirSync(this.path)}avatar(e,t,r,o){return h(this,void 0,void 0,function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.path+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=i,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,r){return h(this,void 0,void 0,function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&n.existsSync(o)&&n.rmSync(o),e.success("OK")})}password(t,o,i,s,n){return h(this,void 0,void 0,function*(){var d;if(x.API_USER_HISTORY){if(yield exports.UserHistory.count({where:{password:r.sha256(i+s.id)}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED")}const a=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return o+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==r.sha256(o)?(a.salt=e.uniqueID(),a.password=r.sha256(i+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?t.success("OK"):void t.success("RECORD NOT CHANGED")):t.error("INVALID PASSWORD")})}token(e,t,r){return h(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_del(e,t,r){return h(this,void 0,void 0,function*(){const o=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(o)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")})}token_get(e,t,r){return h(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_renew(e,t,r,o){return h(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=o.hash.encrypt(t),yield i.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")})}token_new(){return h(this,void 0,void 0,function*(){var t;const r=e.uuidv4();return(null!==(t=yield this.model().count({where:{token:r}}).catch(this.error))&&void 0!==t?t:0)?this.token_new():r})}add(t,o){return h(this,void 0,void 0,function*(){const i=e.uniqueID(),s=yield this.create({ctx:t,body:{password:r.sha256(o+i),salt:i}});x.API_USER_HISTORY&&s&&(yield exports.UserHistory.create({password:r.sha256(o+s.id),user_id:s.id}))})}all(e){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})})}del(e,t,r){return h(this,void 0,void 0,function*(){if(r.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return h(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(t,o,i){return h(this,void 0,void 0,function*(){if(x.API_USER_HISTORY&&i){const e=r.sha256(i+o);if(yield exports.UserHistory.count({where:{password:e}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED");yield exports.UserHistory.create({password:e,user_id:o}).catch(this.error)}const s=i?e.uniqueID():"";yield this.update({ctx:t,body:i?{password:r.sha256(i+s),salt:s}:{}})})}},c([t.Post("/avatar"),t.Middleware("auth"),t.Middleware("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),g(0,t.Ctx()),g(1,t.Files()),g(2,_()),g(3,v()),y("design:type",Function),y("design:paramtypes",[t.Context,Array,exports.User,Object]),y("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),c([t.Delete("/avatar"),t.Middleware("auth"),g(0,t.Ctx()),g(1,_()),g(2,v()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.User,Object]),y("design:returntype",Promise)],exports.UsersController.prototype,"avatar_del",null),c([t.Post("/password"),t.Middleware("auth"),t.Middleware("validation",{oldPassword:e.Validation.string().min(5).required(),newPassword:e.Validation.string().min(5).required(),confirmPassword:e.Validation.string().equal(e.Validation.ref("newPassword"))}),g(0,t.Ctx()),g(1,t.Body("oldPassword")),g(2,t.Body("newPassword")),g(3,_()),g(4,v()),y("design:type",Function),y("design:paramtypes",[t.Context,String,String,exports.User,Object]),y("design:returntype",Promise)],exports.UsersController.prototype,"password",null),c([t.Get("/token"),t.Middleware("auth"),g(0,t.Ctx()),g(1,_()),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.User,U]),y("design:returntype",Promise)],exports.UsersController.prototype,"token",null),c([t.Delete("/token/:id"),t.Middleware("auth"),t.Middleware("canDelete"),g(0,t.Ctx()),g(1,t.Params("id")),g(2,v()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object]),y("design:returntype",Promise)],exports.UsersController.prototype,"token_del",null),c([t.Get("/token/:id"),t.Middleware("auth"),t.Middleware("canCreate"),g(0,t.Ctx()),g(1,t.Params("id")),g(2,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,U]),y("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),c([t.Get("/token/renew/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),g(0,t.Ctx()),g(1,t.Params("id")),g(2,v()),g(3,t.App()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Object,U]),y("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),c([t.Post(),t.Middleware("auth"),t.Middleware("canCreate"),t.Middleware("validation",{name:e.Validation.string().required(),email:e.Validation.string().email().required(),username:e.Validation.string().min(4).required(),password:e.Validation.string().min(5).required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()}),g(0,t.Ctx()),g(1,t.Body("password")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.UsersController.prototype,"add",null),c([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"all",null),c([t.Delete("/:id"),t.Middleware("auth"),t.Middleware("canDelete"),g(0,t.Ctx()),g(1,t.Params("id")),g(2,_()),y("design:type",Function),y("design:paramtypes",[t.Context,String,exports.User]),y("design:returntype",Promise)],exports.UsersController.prototype,"del",null),c([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),g(0,t.Ctx()),y("design:type",Function),y("design:paramtypes",[t.Context]),y("design:returntype",Promise)],exports.UsersController.prototype,"get",null),c([t.Put("/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),t.Middleware("validation",{name:e.Validation.string().empty(),email:e.Validation.string().email().empty(),username:e.Validation.string().min(4).empty(),password:e.Validation.string().min(5).empty().filter(""),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}),g(0,t.Ctx()),g(1,t.Params("id")),g(2,t.Body("password")),y("design:type",Function),y("design:paramtypes",[t.Context,String,String]),y("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=c([t.Controller("/users"),t.Extends(exports.ControllerModel),y("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class extends exports.ControllerModel{model(){return exports.UserGroup}all(e,t){return h(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return h(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(t,r,o,i){return h(this,void 0,void 0,function*(){const s=yield exports.User.findByPk(r,{attributes:["id"]}).catch(this.error);if(!s)return t.notFound("RECORD NOT FOUND");if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},i)),o){let t=0;yield e.sleep(1e3);for(let e=0;e<o.length;e++)t=yield exports.Group.count({where:{id:o[e]}}),t&&(yield exports.UserGroup.create({user_id:s.id,group_id:o[e]},Object.assign({},i)))}t.success("OK")})}},c([t.Get("/:id/groups"),t.Middleware("auth"),t.Middleware("canRead","users"),g(0,t.Ctx()),g(1,t.Params("id")),y("design:type",Function),y("design:paramtypes",[t.Context,String]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),c([t.Get("/groups"),t.Middleware("auth"),t.Middleware("canRead","users"),g(0,t.Ctx()),g(1,_()),y("design:type",Function),y("design:paramtypes",[t.Context,exports.User]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"me",null),c([t.Put("/:id/groups"),t.Middleware("auth"),t.Middleware("canUpdate","users"),t.Middleware("validation",{groups:e.Validation.array(e.Validation.number().parse())}),g(0,t.Ctx()),g(1,t.Params("id")),g(2,t.Body("groups")),g(3,v()),y("design:type",Function),y("design:paramtypes",[t.Context,String,Array,Object]),y("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=c([t.Controller("/users"),t.Extends(exports.ControllerModel)],exports.UsersGroupsController),exports.Application=U,exports.AuthBase=I,exports.AuthKey=f,exports.AuthToken=w,exports.Controller=u,exports.ControllerBase=k,exports.Env=x,exports.Metadata=E,exports.Migrate=S,exports.ReqAudit=v,exports.ReqAuth=A,exports.ReqUser=_,exports.Store=N,exports.audit=m,exports.crt=T,exports.database=P,exports.hooks=O,exports.key=D;
|
|
7
|
+
"use strict";var e=require("@andrewcaires/utils.js"),t=require("@andrewcaires/express"),r=require("@andrewcaires/node"),o=require("dotenv"),i=require("@andrewcaires/sequelize"),s=require("jsonwebtoken"),n=require("fs"),d=require("ws"),a=require("express-session"),l=require("path");class Controller extends e.EventEmitter{}function p(e,t,r,o){var i,s=arguments.length,n=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var d=e.length-1;d>=0;d--)(i=e[d])&&(n=(s<3?i(n):s>3?i(t,r,n):i(t,r))||n);return s>3&&n&&Object.defineProperty(t,r,n),n}function u(e,t){return function(r,o){t(r,o,e)}}function c(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,s){function n(e){try{a(o.next(e))}catch(e){s(e)}}function d(e){try{a(o.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(n,d)}a((o=o.apply(e,t||[])).next())})}Controller.ATTRIBUTES=Symbol("ATTRIBUTES"),Controller.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError,o.config({quiet:!0});class Env extends r.Env{}Env.API_BASE_NAME=Env.getString("API_BASE_NAME",""),Env.API_BODYPARSER_STRICT=Env.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Env.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Env.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Env.getString("API_BODYPARSER_TYPE","json"),Env.API_CONSOLE_ERROR=Env.getBool("API_CONSOLE_ERROR",!1),Env.API_DATABASE_URL=Env.getString("API_DATABASE_URL",""),Env.API_DATABASE_LOG=Env.getBool("API_DATABASE_LOG",!1),Env.API_DATABASE_AUDIT=Env.getBool("API_DATABASE_AUDIT",!0),Env.API_DATABASE_PREFIX=Env.getString("API_DATABASE_PREFIX",""),Env.API_DATABASE_TIMEZONE=Env.getString("API_DATABASE_TIMEZONE","+00:00"),Env.API_HTTP_CRT=Env.getString("API_HTTP_CRT",""),Env.API_HTTP_KEY=Env.getString("API_HTTP_KEY",""),Env.API_HTTP_PORT=Env.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Env.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=Env.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=Env.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Env.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Env.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Env.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Env.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Env.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=Env.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=Env.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SLEEP_AUTH=Env.getMs("API_SLEEP_AUTH","2s"),Env.API_SLEEP_FORGOT=Env.getMs("API_SLEEP_FORGOT","5s"),Env.API_SLEEP_REGISTRY=Env.getMs("API_SLEEP_REGISTRY","5s"),Env.API_SESSION_NAME=Env.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Env.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Env.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_CRT=Env.getString("API_TOKEN_CRT",""),Env.API_TOKEN_KEY=Env.getString("API_TOKEN_KEY",""),Env.API_TOKEN_FORGOT=Env.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_HEADER=Env.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=Env.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_LIFETIME=Env.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_RENEW=Env.getMs("API_TOKEN_RENEW","1d"),Env.API_UPLOAD_COUNT=Env.getInt("API_UPLOAD_COUNT",1),Env.API_UPLOAD_FIELD=Env.getString("API_UPLOAD_FIELD","upload"),Env.API_UPLOAD_SIZE=Env.getInt("API_UPLOAD_SIZE",2),Env.API_UPLOAD_TEMP=Env.getString("API_UPLOAD_TEMP","./temp"),Env.API_USER_HISTORY=Env.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Env.getBool("API_WEBSOCKET_START",!1);const y=e=>{var t,r,o,i,s,n,d,a,l;return{audit_client:null!==(t=e.getIp())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.protocol)+"://"+(null===(o=null==e?void 0:e.req)||void 0===o?void 0:o.get("host"))+(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.originalUrl),audit_user_agent:null!==(n=null===(s=e.req)||void 0===s?void 0:s.headers["user-agent"])&&void 0!==n?n:"",audit_user_id:null!==(l=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==l?l:null}},h=t.parameterFactory(({ctx:e})=>y(e)),v=t.parameterFactory(({ctx:e})=>e.req.auth),x=t.parameterFactory(({ctx:e})=>e.req.user),m=new i.Sequelize(Env.API_DATABASE_URL,{logging:Env.API_DATABASE_LOG,prefix:Env.API_DATABASE_PREFIX,timezone:Env.API_DATABASE_TIMEZONE}),E=(e,t,r)=>{var o,i,s,n,d;return{type:e,model:null!==(o=null==t?void 0:t.getTableName())&&void 0!==o?o:null,client:null!==(i=null==r?void 0:r.audit_client)&&void 0!==i?i:null,href:null!==(s=null==r?void 0:r.audit_href)&&void 0!==s?s:null,user_agent:null!==(n=null==r?void 0:r.audit_user_agent)&&void 0!==n?n:null,user_id:null!==(d=null==r?void 0:r.audit_user_id)&&void 0!==d?d:null,state:!0}},A={afterCreate:(t,r)=>g(void 0,void 0,void 0,function*(){var o;if(!Env.API_DATABASE_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},E("CREATE",i,r)),{record:s?t.getDataValue(s):null,data:t.toJSON()})).catch(e.noop)}),afterUpdate:(t,r)=>g(void 0,void 0,void 0,function*(){var o;if(!Env.API_DATABASE_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null,n={},d=t.changed();d&&d.forEach(e=>n[e]=t.getDataValue(e)),yield exports.Audit.create(Object.assign(Object.assign({},E("UPDATE",i,r)),{record:s?t.getDataValue(s):null,data:n,previously:t.previous()})).catch(e.noop)}),afterDestroy:(t,r)=>g(void 0,void 0,void 0,function*(){var o;if(!Env.API_DATABASE_AUDIT)return;const i=e.isObject(t)?t.constructor:null,s=null!==(o=null==i?void 0:i.primaryKeyAttribute)&&void 0!==o?o:null;yield exports.Audit.create(Object.assign(Object.assign({},E("DELETE",i,r)),{record:s?t.getDataValue(s):null,data:t.toJSON()})).catch(e.noop)})};exports.Auth=class Auth extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Auth.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Auth.prototype,"secret",void 0),p([i.Column.FullDate(),c("design:type",Object)],exports.Auth.prototype,"logout",void 0),p([i.Column.String(),c("design:type",String)],exports.Auth.prototype,"user_agent",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Auth.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Auth.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Auth.prototype,"deleted_at",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.Auth.prototype,"user_id",void 0),exports.Auth=p([i.Database(m),i.ModelName("auth"),i.Version("4.2.0")],exports.Auth),exports.Register=class Register extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Register.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Register.prototype,"token",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.Register.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Register.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Register.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Register.prototype,"deleted_at",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.Register.prototype,"user_id",void 0),exports.Register=p([i.Database(m),i.ModelName("register"),i.Version("4.2.0")],exports.Register),exports.Group=class Group extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Group.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Group.prototype,"name",void 0),p([i.Column.Text(),c("design:type",String)],exports.Group.prototype,"description",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.Group.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Group.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Group.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Group.prototype,"deleted_at",void 0),p([i.HasMany(()=>exports.UserGroup,"group_id"),c("design:type",Array)],exports.Group.prototype,"groups_routes",void 0),p([i.HasMany(()=>exports.UserGroup,"group_id"),c("design:type",Array)],exports.Group.prototype,"users_groups",void 0),exports.Group=p([i.Database(m),i.ModelName("group"),i.Hooks(A),i.Version("4.2.0")],exports.Group),exports.UserGroup=class UserGroup extends i.Model{},p([i.Column.CreatedAt,c("design:type",Date)],exports.UserGroup.prototype,"created_at",void 0),p([i.BelongsTo(()=>exports.Group),c("design:type",Number)],exports.UserGroup.prototype,"group_id",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.UserGroup.prototype,"user_id",void 0),exports.UserGroup=p([i.Database(m),i.ModelName("users_groups"),i.Hooks(A),i.Version("4.2.0")],exports.UserGroup),exports.UserHistory=class UserHistory extends i.Model{},p([i.Column.String(),c("design:type",String)],exports.UserHistory.prototype,"password",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.UserHistory.prototype,"created_at",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.UserHistory.prototype,"user_id",void 0),exports.UserHistory=p([i.Database(m),i.ModelName("users_histories"),i.Version("4.2.0")],exports.UserHistory),exports.User=class User extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.User.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"name",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"email",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"username",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"password",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"salt",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"token",void 0),p([i.Column.String(),c("design:type",String)],exports.User.prototype,"avatar",void 0),p([i.Column.DateOnly(),c("design:type",String)],exports.User.prototype,"date",void 0),p([i.Column.Text(),c("design:type",String)],exports.User.prototype,"description",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.User.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.User.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.User.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.User.prototype,"deleted_at",void 0),p([i.HasMany(()=>exports.Audit,"user_id"),c("design:type",Array)],exports.User.prototype,"audits",void 0),p([i.HasMany(()=>exports.Auth,"user_id"),c("design:type",Array)],exports.User.prototype,"auths",void 0),p([i.HasMany(()=>exports.Register,"user_id"),c("design:type",Array)],exports.User.prototype,"registers",void 0),p([i.HasMany(()=>exports.UserGroup,"user_id"),c("design:type",Array)],exports.User.prototype,"users_groups",void 0),p([i.HasMany(()=>exports.UserHistory,"user_id"),c("design:type",Array)],exports.User.prototype,"users_histories",void 0),exports.User=p([i.Database(m),i.ModelName("user"),i.DefaultScope({attributes:{exclude:["password","salt","token"]}}),i.Scopes({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),i.Hooks(A),i.Version("4.2.0")],exports.User),exports.Audit=class Audit extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Audit.prototype,"id",void 0),p([i.Column.Enum("CREATE","DELETE","UPDATE"),c("design:type",String)],exports.Audit.prototype,"type",void 0),p([i.Column.String(),c("design:type",String)],exports.Audit.prototype,"model",void 0),p([i.Column.String(),c("design:type",String)],exports.Audit.prototype,"record",void 0),p([i.Column.Json(),c("design:type",Object)],exports.Audit.prototype,"data",void 0),p([i.Column.Json(),c("design:type",Object)],exports.Audit.prototype,"previously",void 0),p([i.Column.String(),c("design:type",String)],exports.Audit.prototype,"client",void 0),p([i.Column.Text(),c("design:type",String)],exports.Audit.prototype,"href",void 0),p([i.Column.String(),c("design:type",String)],exports.Audit.prototype,"user_agent",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.Audit.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Audit.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Audit.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Audit.prototype,"deleted_at",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.Audit.prototype,"user_id",void 0),exports.Audit=p([i.Database(m),i.ModelName("audit"),i.Version("4.2.0")],exports.Audit),exports.Config=class Config extends i.Model{static all(){return g(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return g(this,void 0,void 0,function*(){var r;const o=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:o})).catch(this.error))||0)>0})}static get(e){return g(this,arguments,void 0,function*(e,t=""){const[r]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return r?r.value:t})}static set(e,t,r){return g(this,void 0,void 0,function*(){var o;const i=null!==(o=null==r?void 0:r.id)&&void 0!==o?o:null,[s]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:i})).catch(this.error))||[];s&&(s.value=t,yield s.save().catch(this.error))})}},p([i.Column.String(),c("design:type",String)],exports.Config.prototype,"key",void 0),p([i.Column.String(),c("design:type",String)],exports.Config.prototype,"value",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Config.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Config.prototype,"updated_at",void 0),exports.Config=p([i.Database(m),i.ModelName("configs"),i.Version("4.2.0")],exports.Config),exports.Forgot=class Forgot extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Forgot.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Forgot.prototype,"token",void 0),p([i.Column.BigInt(),c("design:type",Number)],exports.Forgot.prototype,"timestamp",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.Forgot.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Forgot.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Forgot.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Forgot.prototype,"deleted_at",void 0),p([i.BelongsTo(()=>exports.User),c("design:type",Number)],exports.Forgot.prototype,"user_id",void 0),exports.Forgot=p([i.Database(m),i.ModelName("forgot"),i.Version("4.2.0")],exports.Forgot),exports.Permission=class Permission extends i.Model{},p([i.Column.Id(),c("design:type",Number)],exports.Permission.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Permission.prototype,"name",void 0),p([i.Column.String(),i.Unique(!0),c("design:type",String)],exports.Permission.prototype,"route",void 0),p([i.Column.String(),c("design:type",String)],exports.Permission.prototype,"tag",void 0),p([i.Column.Text(),c("design:type",String)],exports.Permission.prototype,"description",void 0),p([i.Column.Boolean(),c("design:type",Boolean)],exports.Permission.prototype,"state",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Permission.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Permission.prototype,"updated_at",void 0),p([i.Column.DeletedAt,c("design:type",Object)],exports.Permission.prototype,"deleted_at",void 0),p([i.HasMany(()=>exports.GroupPermission,"permission_id"),c("design:type",Array)],exports.Permission.prototype,"groups_permissions",void 0),exports.Permission=p([i.Database(m),i.ModelName("permission"),i.Hooks(A),i.Version("4.3.1")],exports.Permission),exports.GroupPermission=class GroupPermission extends i.Model{},p([i.Column.CreatedAt,c("design:type",Date)],exports.GroupPermission.prototype,"created_at",void 0),p([i.BelongsTo(()=>exports.Group),c("design:type",Number)],exports.GroupPermission.prototype,"group_id",void 0),p([i.BelongsTo(()=>exports.Permission),c("design:type",Number)],exports.GroupPermission.prototype,"permission_id",void 0),exports.GroupPermission=p([i.Database(m),i.ModelName("groups_permissions"),i.Hooks(A),i.Version("4.2.0")],exports.GroupPermission),exports.Log=class Log extends i.Model{static write(e,t,o){return g(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.White,"",e,t,o)})}static error(e,t,o){return g(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Red,"error",e,t,o)})}static info(e,t,o){return g(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Cyan,"info",e,t,o)})}static success(e,t,o){return g(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Green,"success",e,t,o)})}static warning(e,t,o){return g(this,void 0,void 0,function*(){yield this.writeRaw(r.LogColor.Yellow,"warning",e,t,o)})}static writeRaw(e,t,o,i,s){return g(this,void 0,void 0,function*(){s&&r.Log.console(e,t,o),m&&(yield this.create({type:t,source:i,message:o}).catch(this.error))})}},p([i.Column.Id(),c("design:type",Number)],exports.Log.prototype,"id",void 0),p([i.Column.String(),c("design:type",String)],exports.Log.prototype,"type",void 0),p([i.Column.String(),c("design:type",String)],exports.Log.prototype,"source",void 0),p([i.Column.Text(),c("design:type",String)],exports.Log.prototype,"message",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Log.prototype,"created_at",void 0),exports.Log=p([i.Database(m),i.ModelName("log"),i.Version("4.2.0")],exports.Log),exports.Migration=class Migration extends i.Model{},p([i.Column.String(),c("design:type",String)],exports.Migration.prototype,"model",void 0),p([i.Column.String(),c("design:type",String)],exports.Migration.prototype,"version",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Migration.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Migration.prototype,"updated_at",void 0),exports.Migration=p([i.Database(m),i.ModelName("migration"),i.Version("4.2.0")],exports.Migration),exports.Session=class Session extends i.Model{},p([i.Column.String(),c("design:type",String)],exports.Session.prototype,"session",void 0),p([i.Column.Text(),c("design:type",String)],exports.Session.prototype,"json",void 0),p([i.Column.BigInt(),c("design:type",Number)],exports.Session.prototype,"expired",void 0),p([i.Column.CreatedAt,c("design:type",Date)],exports.Session.prototype,"created_at",void 0),p([i.Column.UpdatedAt,c("design:type",Date)],exports.Session.prototype,"updated_at",void 0),exports.Session=p([i.Database(m),i.ModelName("session"),i.Version("4.2.0")],exports.Session);class AuthBase{static error(e){let t="token";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,Env.API_CONSOLE_ERROR)}}class AuthKey extends AuthBase{static user(e,t){return g(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const r=t.hash.encrypt(e),o=yield exports.User.findOne({where:{token:r,state:!0}}).catch(this.error);if(o){const t=e.replace(/(-[\w]{4})/g,"-****"),[r]=(yield exports.Auth.findOrCreate({where:{secret:t,user_id:o.id},defaults:{secret:t,user_id:o.id}}).catch(this.error))||[];if(r)return r.logout&&(r.logout=null,yield r.save().catch(this.error)),{auth:r,user:o}}return{error:"ACCESS DENIED"}})}}const C=e=>n.existsSync(e)?n.readFileSync(e):void 0,_={http:C(Env.API_HTTP_CRT),token:C(Env.API_TOKEN_CRT)},S={http:C(Env.API_HTTP_KEY),token:C(Env.API_TOKEN_KEY)};class AuthToken extends AuthBase{static options(){return{algorithm:"RS256",expiresIn:`${Env.API_TOKEN_LIFETIME}ms`}}static create(t){return g(this,void 0,void 0,function*(){if(!S.token)return{error:"KEY NOT FOUND"};const{id:r}=t,o=e.uuidv7(),i=yield exports.Auth.create({secret:o,user_id:r}).catch(this.error);if(!i)return{error:"INTERNAL SERVER ERROR"};return{auth:i,token:s.sign({id:r,secret:o},S.token,this.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 renew(t){return g(this,void 0,void 0,function*(){if(!S.token)return{error:"KEY NOT FOUND"};const{error:r,decode:o}=this.verify(t,Env.API_TOKEN_RENEW/1e3);if(r)return{error:r};if(o){const{id:t,secret:r}=o;if(t&&r){const o=yield exports.User.findOne({where:{id:t,state:!0}}).catch(this.error);if(o){const i=yield exports.Auth.findOne({where:{secret:r,user_id:o.id}}).catch(this.error);if(i&&!i.logout){i.secret=e.uuidv7(),yield i.save().catch(this.error);return{auth:i,token:s.sign({id:t,secret:i.secret},S.token,this.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}=this.verify(e);if(t)return{error:t};if(r){const{id:e,secret:t}=r;if(e&&t){const r=yield exports.User.findOne({where:{id:e,state:!0}}).catch(this.error);if(r){const e=yield exports.Auth.findOne({where:{secret:t,user_id:r.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:r}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!_.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:s.verify(e,_.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class Store extends a.Store{constructor(){super(),this.all=t=>g(this,void 0,void 0,function*(){t=t||e.noop;const r=yield exports.Session.findAll({attributes:["session"],where:{expired:{[i.Op.gte]:Date.now()}}}).catch(e=>(t(e),null));r&&t(null,r.map(e=>e.session)),t()}),this.clear=t=>g(this,void 0,void 0,function*(){yield exports.Session.destroy().catch(e.noop),t&&t()}),this.destroy=(t,r)=>g(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{session:t}}).catch(e.noop),r&&r()}),this.expired=()=>g(this,void 0,void 0,function*(){yield exports.Session.destroy({where:{expired:{[i.Op.lt]:Date.now()}}}).catch(e.noop)}),this.get=(t,r)=>g(this,void 0,void 0,function*(){r=r||e.noop;const o=yield exports.Session.findOne({where:{session:t,expired:{[i.Op.gte]:Date.now()}}}).catch(e=>(r(e),null));if(o){const t=JSON.parse(o.json);if(t.cookie){if(new Date(t.cookie.expires).getTime()<=Date.now())return yield o.destroy().catch(e.noop),void r(null)}return void r(null,t)}r(null)}),this.length=t=>g(this,void 0,void 0,function*(){t&&t(null,(yield exports.Session.count().catch(e.noop))||0)}),this.set=(t,r,o)=>g(this,void 0,void 0,function*(){o=o||e.noop;const i=Date.now()+Env.API_SESSION_LIFETIME,s=JSON.stringify(r),[n,d]=(yield exports.Session.findOrCreate({where:{session:t},defaults:{session:t,json:s,expired:i}}).catch(e.noop))||[];n&&(d||(n.json=s,n.expired=i,yield n.save().catch(e.noop))),o()}),this.loop=e.loop(this.expired,3e4),this.loop.start()}}class Application extends t.Application{constructor(t){super(t,{cert:_.http,cross:Env.API_HTTP_CROSS,hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},key:S.http,notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new Store,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:e.uuidv7}}),this.hash=new r.Hash(Env.API_KEY_HASH)}error(e,t){Env.API_BASE_NAME&&(t=t?`${Env.API_BASE_NAME}.${t}`:Env.API_BASE_NAME),exports.Log.error(e.message,t,Env.API_CONSOLE_ERROR)}log(e,t){Env.API_BASE_NAME&&(t=t?`${Env.API_BASE_NAME}.${t}`:Env.API_BASE_NAME),exports.Log.info(e,t,!0)}listen(){const t=Object.create(null,{listen:{get:()=>super.listen}});return g(this,void 0,void 0,function*(){yield m.sync(),yield this.migrations(m),yield e.forEachSeries(this.controllers,t=>g(this,void 0,void 0,function*(){e.isFunction(t.sync)&&(yield t.sync(this))})),yield t.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new d.WebSocketServer({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(t,r)=>g(this,void 0,void 0,function*(){r.url||(r.url="");const o=r.url.length<=1?"":r.url.replace(/\//g,".");let i;t.on("message",e=>g(this,void 0,void 0,function*(){if(i)try{const s=JSON.parse(e);this.emit("ws.message"+o,{data:s,message:e,req:r,user:i,ws:t})}catch(s){this.emit("ws.message"+o,{erro:s,message:e,req:r,user:i,ws:t})}else{const{user:s}=yield AuthToken.user(e.toString());s&&(i=s,this.emit("ws.connection"+o,{req:r,user:i,ws:t}))}i||t.close()})),t.on("close",()=>{i&&this.emit("ws.close"+o,{user:i,ws:t})}),yield e.sleep(2e3),i||t.close()})))})}migrations(t){return g(this,void 0,void 0,function*(){const r=[];yield e.forEachSeries(Object.keys(t.models),e=>g(this,void 0,void 0,function*(){var o;const i=t.models[e],s=i.version();if(!s)return;const[n,d]=null!==(o=yield exports.Migration.findOrCreate({where:{model:i.tableName},defaults:{model:i.tableName,version:""}}).catch(this.error))&&void 0!==o?o:[];n&&(d||n.version!=s)&&(n.version=s,yield n.save().catch(this.error),r.push(i))})),yield e.forEachSeries(r,e=>g(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}var P,O,f,I,R;class ControllerBase extends Controller{constructor(){super(...arguments),this[P]=[]}auth(e,t,r,o,i,s){return g(this,void 0,void 0,function*(){var n;t=null!=t?t:o;const[d,a]=null!==(n=null==r?void 0:r.split(" "))&&void 0!==n?n:["",""];if(!(t||a&&d.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:l,error:p,user:u}=yield t?AuthKey.user(t,s):AuthToken.user(a);return p?e.error(p):l&&u?!t&&l.user_agent&&l.user_agent!=i?e.error("INVALID TOKEN"):(e.req.auth=l,e.req.user=u,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,r){return g(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",r)})}canDelete(e,t,r){return g(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",r)})}canRead(e,t,r){return g(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",r)})}canUpdate(e,t,r){return g(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",r)})}error(e){let t="controller_base";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),exports.Log.error(e.message,t,Env.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,r){return g(this,void 0,void 0,function*(){if(r){if((yield this.permissions(r,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return g(this,void 0,void 0,function*(){var r;return null!==(r=yield exports.Permission.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:exports.GroupPermission,required:!0,include:[{model:exports.Group,required:!0,where:{state:!0},include:[{model:exports.UserGroup,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==r?r:[]})}session(t,r,o){return g(this,void 0,void 0,function*(){o.auth&&o.user&&(o.user_agent?o.user_agent!=r&&o.regenerate(e.noop):(o.user_agent=r,o.save(e.noop))),t.next()})}sync(){return g(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r={description:"",state:!0};yield e.forEachSeries(this[Controller.PERMISSIONS],o=>g(this,void 0,void 0,function*(){const i=`${t}.${o}`,s=e.upperCamelCase(t.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${e.upperCamelCase(o," ")}`,route:i,tag:s},r)})}))})}upload(e,r){r.path||(r.path=Env.API_UPLOAD_TEMP),r.size||(r.size=Env.API_UPLOAD_SIZE),r.field||(r.field=Env.API_UPLOAD_FIELD),t.Upload.middleware(e,r)}validation(t,r){return g(this,void 0,void 0,function*(){const{error:o,value:i}=yield e.Validation.object(r).parse().validateAsync(t.req.body);if(o)return t.validation(o);t.req.body=i,t.next()})}}P=Controller.PERMISSIONS,p([u(0,t.Ctx()),u(1,t.Headers(Env.API_KEY_HEADER)),u(2,t.Headers(Env.API_TOKEN_HEADER)),u(3,t.Query(Env.API_KEY_HEADER)),u(4,t.Headers("user-agent")),u(5,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,String,String,String,Application]),c("design:returntype",Promise)],ControllerBase.prototype,"auth",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],ControllerBase.prototype,"canCreate",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],ControllerBase.prototype,"canDelete",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],ControllerBase.prototype,"canRead",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],ControllerBase.prototype,"canUpdate",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],ControllerBase.prototype,"permission",null),p([u(0,t.Ctx()),u(1,t.Headers("user-agent")),u(2,t.Session()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Object]),c("design:returntype",Promise)],ControllerBase.prototype,"session",null),p([u(0,t.Ctx()),u(1,t.Argument()),c("design:type",Function),c("design:paramtypes",[t.Context,Object]),c("design:returntype",void 0)],ControllerBase.prototype,"upload",null),p([u(0,t.Ctx()),u(1,t.Argument()),c("design:type",Function),c("design:paramtypes",[t.Context,Object]),c("design:returntype",Promise)],ControllerBase.prototype,"validation",null),exports.ControllerModel=class ControllerModel extends ControllerBase{constructor(){super(...arguments),this[O]=[],this[f]=["create","read","update","delete"]}attributes(t){if(0==this[ControllerBase.ATTRIBUTES].length&&(this[ControllerBase.ATTRIBUTES]=Object.keys(this.model().getAttributes())),e.isArray(t))return t.length?t.map(t=>e.isString(t)&&-1!=this[ControllerBase.ATTRIBUTES].indexOf(t)?t:void 0).filter(e.isString):this[ControllerBase.ATTRIBUTES];const{exclude:r,include:o}=t,i=e.isUndefined(o)?this[ControllerBase.ATTRIBUTES]:o.map(t=>e.isString(t)&&-1!=this[ControllerBase.ATTRIBUTES].indexOf(t)?t:void 0).filter(e.isString),s=null!=r?r:[];return s.length?i.filter(e=>-1==s.indexOf(e)?e:void 0).filter(e.isString):i}create(e){return g(this,arguments,void 0,function*({ctx:e,options:r,body:o}){const i=yield this.model().create(Object.assign(Object.assign({},e.req.body),o||{}),Object.assign(Object.assign({},r||{}),y(e))).catch(this.error);if(i){const r=this.key();return e.prepare(t.Status.OK,{[r]:i.getDataValue(r)}),i}e.error("INTERNAL SERVER ERROR")})}delete(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(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[r]:o}),individualHooks:!0}),y(e))).catch(this.error);return i?(e.success("OK"),i):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?exports.Log.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,Env.API_CONSOLE_ERROR):super.error(e)}findAll(r){return g(this,arguments,void 0,function*({ctx:r,options:o,callback:s,scope:n,advanced:d,attributes:a,limited:l}){var p,u,c;const g=this.scope(n),y=Object.assign({},o||{}),{fields:h,limit:v,offset:x,asc:m,desc:E,search:A,where:C}=r.req.query;if(e.isUndefined(y.limit)){let t=Env.API_MODEL_LIMIT;e.isString(v)&&(t=parseInt(v)||0),t=e.clamp(t,-1,Env.API_MODEL_LIMIT_MAX),y.limit=t>0?t:l?Env.API_MODEL_LIMIT:void 0}if(e.isNumber(y.limit)&&(y.limit=y.limit>0?y.limit:void 0),e.isString(x)){const e=parseInt(x)||0;y.offset=e>0?e:void 0}a=null!=a?a:this.attributes(null!==(p=null==y?void 0:y.attributes)&&void 0!==p?p:[]);const _=e=>a.indexOf(e)>=0,S=[];e.isString(h)&&S.push(...h.split(";").filter(_)),S.length&&(y.attributes=S);const P=[];if(e.isString(m)&&m.length&&P.push(...m.split(";").filter(_).map(e=>[e,"ASC"])),e.isString(E)&&E.length&&P.push(...E.split(";").filter(_).map(e=>[e,"DESC"])),P.length&&(y.order=P),y.where=Object.assign({},y.where||{}),e.isString(C)&&(null==d||d)){const t=i.Where.parse(a,C);if(!e.isUndefined(t.error))return r.validation(t.error.join(", ")),{count:0,records:[]};y.where=Object.assign(Object.assign({},y.where),null!==(u=t.value)&&void 0!==u?u:{})}else{const t=[];a.forEach(r=>{e.isString(A)&&A.length&&t.push({[r]:{[i.Op.like]:`%${A}%`}})}),t.length&&(y.where=Object.assign(Object.assign({},y.where),{[i.Op.or]:[...t]}))}const O=g.count(Object.assign(Object.assign({},y),{distinct:!!y.include,col:this[ControllerBase.ATTRIBUTES].length?this[ControllerBase.ATTRIBUTES][0]:void 0})).catch(this.error),f=g.findAll(y).catch(this.error);yield Promise.allSettled([O,f]);const I=null!==(c=yield O)&&void 0!==c?c:0;let R=yield f;const T={count:I};return R?(R=s?yield s(R):R,(e.isNumber(null==o?void 0:o.limit)||0==I)&&(T.count=R.length),r.prepare(t.Status.OK,Object.assign(Object.assign({},T),{records:R})),Object.assign(Object.assign({},T),{records:R})):(r.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},T),{records:[]}))})}findOne(e){return g(this,arguments,void 0,function*({ctx:e,options:r,callback:o,scope:i}){const s=this.key(),{[s]:n}=e.req.params,d=yield this.scope(i).findOne(Object.assign(Object.assign({},r||{}),{where:Object.assign(Object.assign({},(r||{}).where),{[s]:n})})).catch(this.error);return d?(e.prepare(t.Status.OK,o?yield o(d):d.toJSON()),d):null===d?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return g(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r={description:"",state:!0};yield e.forEachSeries(this[ControllerBase.PERMISSIONS],o=>g(this,void 0,void 0,function*(){const i=`${t}.${o}`,s=e.upperCamelCase(t.replace(/_/g," ")," ");yield exports.Permission.findOrCreate({where:{route:i},defaults:Object.assign({name:`${s} ${e.upperCamelCase(o," ")}`,route:i,tag:s},r)})}))})}update(e){return g(this,arguments,void 0,function*({ctx:e,options:t,body:r}){var o;const i=this.key(),{[i]:s}=e.req.params,[n]=null!==(o=yield this.model().update(Object.assign(Object.assign({},e.req.body),r||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:s}),individualHooks:!0}),y(e))).catch(this.error))&&void 0!==o?o:[];return n?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}},O=ControllerBase.ATTRIBUTES,f=ControllerBase.PERMISSIONS,exports.ControllerModel=p([t.Extends(ControllerBase)],exports.ControllerModel),exports.ControllerCrud=class ControllerCrud extends exports.ControllerModel{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return g(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return g(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return g(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return g(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return g(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return g(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return g(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}},p([t.Post(),t.Middleware("auth"),t.Middleware("canCreate"),t.Middleware("validationCreate"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"add",null),p([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"all",null),p([t.Delete("/:id"),t.Middleware("auth"),t.Middleware("canDelete"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"del",null),p([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"get",null),p([t.Put("/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),t.Middleware("validationUpdate"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"set",null),p([u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationCreate",null),p([u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.ControllerCrud.prototype,"validationUpdate",null),exports.ControllerCrud=p([t.Extends(exports.ControllerModel)],exports.ControllerCrud),exports.AuditsController=class AuditsController extends exports.ControllerModel{model(){return exports.Audit}all(e,t,r){return g(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.table=r),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:o,order:[["created_at","DESC"]]},limited:!0})})}get(e){return g(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}},p([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),u(1,t.Query("type")),u(2,t.Query("table")),c("design:type",Function),c("design:paramtypes",[t.Context,String,String]),c("design:returntype",Promise)],exports.AuditsController.prototype,"all",null),p([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.AuditsController.prototype,"get",null),exports.AuditsController=p([t.Controller("/audits"),t.Extends(exports.ControllerModel)],exports.AuditsController),exports.AuthController=class AuthController extends ControllerBase{login(t,o,s,n,d){return g(this,void 0,void 0,function*(){var a;yield e.sleep(Env.API_SLEEP_AUTH);const l=yield exports.User.scope("password").findOne({where:{[i.Op.or]:[{email:s},{username:s}]}}).catch(this.error);if(n+=null!==(a=null==l?void 0:l.salt)&&void 0!==a?a:"",!l||l.password!=r.sha256(n))return t.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t});const p=yield exports.Register.findOne({where:{state:!0,user_id:l.id}}).catch(this.error);if(p)return t.error("ACTIVATION REQUIRED"),d.emit("auth.activation",{ctx:t,register:p,user:l}),void this.emit("auth.activation",{ctx:t,register:p,user:l});if(!l.state)return t.notFound("INVALID USERNAME OR PASSWORD"),d.emit("auth.failure",{ctx:t,user:l}),void this.emit("auth.failure",{ctx:t,user:l});const{auth:u,error:c,token:g}=yield AuthToken.create(l);return c?(t.error(c),d.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t})):u&&g?(u.user_agent=o,yield u.save().catch(this.error),t.json({token:g}),d.emit("auth.login",{auth:u,ctx:t,user:l}),void this.emit("auth.login",{auth:u,ctx:t,user:l})):(t.error("INTERNAL SERVER ERROR"),d.emit("auth.failure",{ctx:t}),void this.emit("auth.failure",{ctx:t}))})}logout(e,t,r,o){return g(this,void 0,void 0,function*(){if(yield AuthToken.destroy(t))return e.success("OK"),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:s,token:n}=yield AuthToken.renew(r);return s?e.error(s):i?(i.user_agent=t,yield i.save().catch(this.error),e.json({token:n}),o.emit("auth.renew",{auth:i,ctx:e}),void this.emit("auth.renew",{auth:i,ctx:e})):e.error("INTERNAL SERVER ERROR")})}user(t,r){return g(this,void 0,void 0,function*(){const o=yield this.permissions(r);if(!o)return t.error("INTERNAL SERVER ERROR");t.json(Object.assign(Object.assign({},e.denied(["username","date","description","state","created_at","updated_at","deleted_at"],r.toJSON())),{permissions:o.map(e=>e.route)}))})}},p([t.Post("/login"),t.Middleware("validation",{username:e.Validation.string().min(3).required(),password:e.Validation.string().min(5).required()}),u(0,t.Ctx()),u(1,t.Headers("user-agent")),u(2,t.Body("username")),u(3,t.Body("password")),u(4,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,String,String,Application]),c("design:returntype",Promise)],exports.AuthController.prototype,"login",null),p([t.Get("/logout"),t.Middleware("auth"),u(0,t.Ctx()),u(1,v()),u(2,x()),u(3,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.Auth,exports.User,Application]),c("design:returntype",Promise)],exports.AuthController.prototype,"logout",null),p([t.Post("/renew"),t.Middleware("validation",{token:e.Validation.string().required()}),u(0,t.Ctx()),u(1,t.Headers("user-agent")),u(2,t.Body("token")),u(3,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,String,Application]),c("design:returntype",Promise)],exports.AuthController.prototype,"renew",null),p([t.Get(),t.Middleware("auth"),u(0,t.Ctx()),u(1,x()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.User]),c("design:returntype",Promise)],exports.AuthController.prototype,"user",null),exports.AuthController=p([t.Controller("/auth"),t.Extends(ControllerBase)],exports.AuthController),exports.FilesController=class FilesController extends ControllerBase{constructor(){super(...arguments),this[I]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return Env.API_HTTP_PUBLIC||"./"}files(t){return g(this,void 0,void 0,function*(){let{path:r}=t.req;r=r.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const o=l.join(this.directory(),r);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return t.notFound("RECORD NOT FOUND");let i=[];return i=n.readdirSync(o),i=i.map(e=>this.info(l.join(o,e))),i=i.filter(e.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(!n.existsSync(e))return null;const t=n.statSync(e),r=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const o=t.isDirectory();return{name:r,path:e.replace(/^\/\//,"/"),size:t.size,extension:o?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:o,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return g(this,void 0,void 0,function*(){const t=this.name().toLowerCase(),r=e.upperCamelCase(t.replace(/_/g," ")," "),o={description:"",state:!0};yield e.forEachSeries(this[ControllerBase.PERMISSIONS],i=>g(this,void 0,void 0,function*(){const s=`${t}.${i}`;yield exports.Permission.findOrCreate({where:{route:s},defaults:Object.assign({name:`${r} ${e.upperCamelCase(i," ")}`,route:s,tag:r},o)})}))})}},I=ControllerBase.PERMISSIONS,p([t.Get("/path"),t.Get("/path/*path"),t.Middleware("auth"),t.Middleware("access","list"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.FilesController.prototype,"files",null),p([u(0,t.Ctx()),u(1,t.Argument()),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],exports.FilesController.prototype,"access",null),exports.FilesController=p([t.Controller("/files"),t.Extends(ControllerBase)],exports.FilesController),exports.ForgotController=class ForgotController extends ControllerBase{check(t,r){return g(this,void 0,void 0,function*(){const o=yield this.find(r);if(!o||!o.user)return t.notFound("RECORD NOT FOUND");o.token=e.uniqueID(),yield o.save(),t.json({token:o.token})})}forgot(t,r,o){return g(this,void 0,void 0,function*(){yield e.sleep(Env.API_SLEEP_FORGOT);const s=r,n=yield exports.User.findOne({where:{[i.Op.or]:[{email:s},{username:r}]}}).catch(this.error);if(!n)return t.notFound("RECORD NOT FOUND");const d=e.uniqueID(),a=Date.now()+6e4*Env.API_TOKEN_FORGOT,l=yield exports.Forgot.create({token:d,timestamp:a,state:!0,user_id:n.id});t.success("OK"),o.emit("forgot.send",{ctx:t,forgot:l,user:n}),this.emit("forgot.send",{ctx:t,forgot:l,user:n})})}reset(e,t,o,i){return g(this,void 0,void 0,function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=r.sha256(o),yield s.user.save().catch(this.error),e.success("OK"),i.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})})}find(e){return g(this,void 0,void 0,function*(){return yield exports.Forgot.findOne({where:{token:e,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error)})}},p([t.Get("/check"),t.Middleware("validation",{token:e.Validation.string().required()}),u(0,t.Ctx()),u(1,t.Body("token")),c("design:type",Function),c("design:paramtypes",[t.Context,String]),c("design:returntype",Promise)],exports.ForgotController.prototype,"check",null),p([t.Post(),t.Middleware("validation",{username:e.Validation.string().min(4).required()}),u(0,t.Ctx()),u(1,t.Body("username")),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Application]),c("design:returntype",Promise)],exports.ForgotController.prototype,"forgot",null),p([t.Post("/reset"),t.Middleware("validation",{token:e.Validation.string().required(),password:e.Validation.string().min(5).required()}),u(0,t.Ctx()),u(1,t.Body("token")),u(2,t.Body("password")),u(3,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,String,Application]),c("design:returntype",Promise)],exports.ForgotController.prototype,"reset",null),exports.ForgotController=p([t.Controller("/forgot"),t.Extends(ControllerBase)],exports.ForgotController),exports.GroupsController=class GroupsController extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:e.Validation.string().required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()},this.schemaUpdate={name:e.Validation.string().empty(),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}}model(){return exports.Group}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.GroupsController=p([t.Controller("/groups"),t.Extends(exports.ControllerCrud)],exports.GroupsController),exports.GroupsPermissionsController=class GroupsPermissionsController extends exports.ControllerModel{model(){return exports.GroupPermission}all(e,t){return g(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:exports.Permission,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return g(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(t,r,o,i){return g(this,void 0,void 0,function*(){const s=yield exports.Group.findByPk(r,{attributes:["id"]}).catch(this.error);if(!s)return t.notFound("RECORD NOT FOUND");const n=s.id;if(yield exports.GroupPermission.destroy(Object.assign({where:{group_id:n},individualHooks:!0},i)),o){let t=0;yield e.sleep(1e3);for(let e=0;e<o.length;e++)t=yield exports.Permission.count({where:{id:o[e]}}),t&&(yield exports.GroupPermission.create({group_id:n,permission_id:o[e]},Object.assign({},i)))}t.success("OK")})}},p([t.Get("/:id/permissions"),t.Middleware("auth"),t.Middleware("canRead","groups"),u(0,t.Ctx()),u(1,t.Params("id")),c("design:type",Function),c("design:paramtypes",[t.Context,String]),c("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"all",null),p([t.Get("/permissions"),t.Middleware("auth"),t.Middleware("canRead","users"),u(0,t.Ctx()),u(1,x()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.User]),c("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"me",null),p([t.Put("/:id/permissions"),t.Middleware("auth"),t.Middleware("canUpdate","groups"),t.Middleware("validation",{permissions:e.Validation.array(e.Validation.number().parse())}),u(0,t.Ctx()),u(1,t.Params("id")),u(2,t.Body("permissions")),u(3,h()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Array,Object]),c("design:returntype",Promise)],exports.GroupsPermissionsController.prototype,"set",null),exports.GroupsPermissionsController=p([t.Controller("/groups"),t.Extends(exports.ControllerModel)],exports.GroupsPermissionsController),exports.LogsController=class LogsController extends exports.ControllerModel{constructor(){super(...arguments),this[R]=["read"]}model(){return exports.Log}all(e,t,r){return g(this,void 0,void 0,function*(){const o={};t&&(o.type=t),r&&(o.source=r),yield this.findAll({ctx:e,options:{where:o,order:[["created_at","DESC"]]},limited:!0})})}},R=exports.ControllerModel.PERMISSIONS,p([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),u(1,t.Query("type")),u(2,t.Query("source")),c("design:type",Function),c("design:paramtypes",[t.Context,String,String]),c("design:returntype",Promise)],exports.LogsController.prototype,"all",null),exports.LogsController=p([t.Controller("/logs"),t.Extends(exports.ControllerModel)],exports.LogsController),exports.PermissionsController=class PermissionsController extends exports.ControllerCrud{constructor(){super(...arguments),this.schemaCreate={name:e.Validation.string().required(),route:e.Validation.string().required(),tag:e.Validation.string().required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()},this.schemaUpdate={name:e.Validation.string().empty(),route:e.Validation.string().empty(),tag:e.Validation.string().empty(),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}}model(){return exports.Permission}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}},exports.PermissionsController=p([t.Controller("/permissions"),t.Extends(exports.ControllerCrud)],exports.PermissionsController),exports.RegisterController=class RegisterController extends ControllerBase{register(t,o,s){return g(this,void 0,void 0,function*(){yield e.sleep(Env.API_SLEEP_REGISTRY);const{name:n,date:d,email:a,username:l,password:p,confirm:u}=o,c=l||a,g=r.sha256(p);if(yield exports.User.count({where:{[i.Op.or]:[{email:a},{username:c}]}}).catch(this.error))return t.validation("INVALID EMAIL OR USERNAME");if(g!=r.sha256(u))return t.error("INVALID PASSWORD");const y=yield exports.User.create({name:n,email:a,username:c,password:g,avatar:"",date:d,description:"",state:!1}).catch(this.error);if(!y)return t.error("INTERNAL SERVER ERROR");const h=yield exports.Register.create({token:yield this.getId(),user_id:y.id,state:!0}).catch(this.error);if(!h)return yield y.destroy().catch(this.error),t.error("INTERNAL SERVER ERROR");t.success("OK"),s.emit("register.user",{ctx:t,register:h,user:y}),this.emit("register.user",{ctx:t,register:h,user:y})})}confirm(e,t,r){return g(this,void 0,void 0,function*(){const o=yield exports.Register.findOne({where:{token:t,state:!0},include:[{model:exports.User,required:!0}]}).catch(this.error);if(!o)return e.notFound("RECORD 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,s=yield exports.Register.findOne({where:{state:!0},include:[{model:exports.User,required:!0,where:{[i.Op.or]:[{email:o},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("RECORD 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 t=e.uuidv7();return(yield exports.Register.count({where:{token:t}}))?this.getId():t})}},p([t.Post(),t.Middleware("validation",{name:e.Validation.string().required(),date:e.Validation.date().required(),email:e.Validation.string().email().required(),username:e.Validation.string().min(4).empty(),password:e.Validation.string().min(5).required(),confirm:e.Validation.string().min(5).required()}),u(0,t.Ctx()),u(1,t.Body()),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,Object,Application]),c("design:returntype",Promise)],exports.RegisterController.prototype,"register",null),p([t.Post("/confirm"),t.Middleware("validation",{token:e.Validation.string().required()}),u(0,t.Ctx()),u(1,t.Body("token")),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Application]),c("design:returntype",Promise)],exports.RegisterController.prototype,"confirm",null),p([t.Post("/send"),t.Middleware("validation",{username:e.Validation.string().min(4).required()}),u(0,t.Ctx()),u(1,t.Body("username")),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Application]),c("design:returntype",Promise)],exports.RegisterController.prototype,"send",null),exports.RegisterController=p([t.Controller("/register"),t.Extends(ControllerBase)],exports.RegisterController),exports.SetupController=class SetupController extends ControllerBase{setup(t,o){return g(this,void 0,void 0,function*(){var i;if(yield exports.User.count())return t.success("OK");const s=e.uniqueID(),n=yield exports.User.create({name:"Admin",email:"admin@localhost",username:"admin",password:r.sha256("admin"+s),salt:s,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},o)),d=yield exports.Group.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},o));yield exports.UserGroup.create({user_id:n.id,group_id:d.id},Object.assign({},o));const a=null!==(i=yield exports.Permission.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield e.forEachSeries(a,e=>g(this,void 0,void 0,function*(){yield exports.GroupPermission.create({group_id:d.id,permission_id:e.id},Object.assign({},o))})),t.success("OK")})}},p([t.Get(),u(0,t.Ctx()),u(1,h()),c("design:type",Function),c("design:paramtypes",[t.Context,Object]),c("design:returntype",Promise)],exports.SetupController.prototype,"setup",null),exports.SetupController=p([t.Controller("/setup"),t.Extends(ControllerBase)],exports.SetupController),exports.UsersController=class UsersController extends exports.ControllerModel{model(){return exports.User}constructor(){super(),this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&n.existsSync(Env.API_HTTP_PUBLIC)&&!n.existsSync(this.path)&&n.mkdirSync(this.path)}avatar(e,t,r,o){return g(this,void 0,void 0,function*(){if(t.length){const i=t[0].filename||"";if(i){const t=this.path+"/"+r.avatar;if(n.existsSync(t)&&n.lstatSync(t).isFile()&&n.rmSync(t),r.avatar=i,yield r.save(Object.assign({},o)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,r){return g(this,void 0,void 0,function*(){const o=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},r)).catch(this.error))&&n.existsSync(o)&&n.rmSync(o),e.success("OK")})}password(t,o,i,s,n){return g(this,void 0,void 0,function*(){var d;if(Env.API_USER_HISTORY){if(yield exports.UserHistory.count({where:{password:r.sha256(i+s.id)}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED")}const a=yield this.scope("password").findOne({where:{id:s.id,state:!0}}).catch(this.error);return o+=null!==(d=null==a?void 0:a.salt)&&void 0!==d?d:"",a&&a.password==r.sha256(o)?(a.salt=e.uniqueID(),a.password=r.sha256(i+a.salt),(yield a.save(Object.assign({},n)).catch(this.error))?t.success("OK"):void t.success("RECORD NOT CHANGED")):t.error("INVALID PASSWORD")})}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_del(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)return o.token="",yield o.save(Object.assign({},r)).catch(this.error),e.success("OK");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_renew(e,t,r,o){return g(this,void 0,void 0,function*(){const i=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(i){const t=yield this.token_new();return i.token=o.hash.encrypt(t),yield i.save(Object.assign({},r)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")})}token_new(){return g(this,void 0,void 0,function*(){var t;const r=e.uuidv7();return(null!==(t=yield this.model().count({where:{token:r}}).catch(this.error))&&void 0!==t?t:0)?this.token_new():r})}add(t,o){return g(this,void 0,void 0,function*(){const i=e.uniqueID(),s=yield this.create({ctx:t,body:{password:r.sha256(o+i),salt:i}});Env.API_USER_HISTORY&&s&&(yield exports.UserHistory.create({password:r.sha256(o+s.id),user_id:s.id}))})}all(e){return g(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})})}del(e,t,r){return g(this,void 0,void 0,function*(){if(r.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return g(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(t,o,i){return g(this,void 0,void 0,function*(){if(Env.API_USER_HISTORY&&i){const e=r.sha256(i+o);if(yield exports.UserHistory.count({where:{password:e}}).catch(this.error))return t.error("PASSWORD PREVIOUSLY REGISTERED");yield exports.UserHistory.create({password:e,user_id:o}).catch(this.error)}const s=i?e.uniqueID():"";yield this.update({ctx:t,body:i?{password:r.sha256(i+s),salt:s}:{}})})}},p([t.Post("/avatar"),t.Middleware("auth"),t.Middleware("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),u(0,t.Ctx()),u(1,t.Files()),u(2,x()),u(3,h()),c("design:type",Function),c("design:paramtypes",[t.Context,Array,exports.User,Object]),c("design:returntype",Promise)],exports.UsersController.prototype,"avatar",null),p([t.Delete("/avatar"),t.Middleware("auth"),u(0,t.Ctx()),u(1,x()),u(2,h()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.User,Object]),c("design:returntype",Promise)],exports.UsersController.prototype,"avatar_del",null),p([t.Post("/password"),t.Middleware("auth"),t.Middleware("validation",{oldPassword:e.Validation.string().min(5).required(),newPassword:e.Validation.string().min(5).required(),confirmPassword:e.Validation.string().equal(e.Validation.ref("newPassword"))}),u(0,t.Ctx()),u(1,t.Body("oldPassword")),u(2,t.Body("newPassword")),u(3,x()),u(4,h()),c("design:type",Function),c("design:paramtypes",[t.Context,String,String,exports.User,Object]),c("design:returntype",Promise)],exports.UsersController.prototype,"password",null),p([t.Get("/token"),t.Middleware("auth"),u(0,t.Ctx()),u(1,x()),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.User,Application]),c("design:returntype",Promise)],exports.UsersController.prototype,"token",null),p([t.Delete("/token/:id"),t.Middleware("auth"),t.Middleware("canDelete"),u(0,t.Ctx()),u(1,t.Params("id")),u(2,h()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Object]),c("design:returntype",Promise)],exports.UsersController.prototype,"token_del",null),p([t.Get("/token/:id"),t.Middleware("auth"),t.Middleware("canCreate"),u(0,t.Ctx()),u(1,t.Params("id")),u(2,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Application]),c("design:returntype",Promise)],exports.UsersController.prototype,"token_get",null),p([t.Get("/token/renew/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),u(0,t.Ctx()),u(1,t.Params("id")),u(2,h()),u(3,t.App()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Object,Application]),c("design:returntype",Promise)],exports.UsersController.prototype,"token_renew",null),p([t.Post(),t.Middleware("auth"),t.Middleware("canCreate"),t.Middleware("validation",{name:e.Validation.string().required(),email:e.Validation.string().email().required(),username:e.Validation.string().min(4).required(),password:e.Validation.string().min(5).required(),description:e.Validation.string().empty(""),state:e.Validation.boolean().parse().required()}),u(0,t.Ctx()),u(1,t.Body("password")),c("design:type",Function),c("design:paramtypes",[t.Context,String]),c("design:returntype",Promise)],exports.UsersController.prototype,"add",null),p([t.Get(),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.UsersController.prototype,"all",null),p([t.Delete("/:id"),t.Middleware("auth"),t.Middleware("canDelete"),u(0,t.Ctx()),u(1,t.Params("id")),u(2,x()),c("design:type",Function),c("design:paramtypes",[t.Context,String,exports.User]),c("design:returntype",Promise)],exports.UsersController.prototype,"del",null),p([t.Get("/:id"),t.Middleware("auth"),t.Middleware("canRead"),u(0,t.Ctx()),c("design:type",Function),c("design:paramtypes",[t.Context]),c("design:returntype",Promise)],exports.UsersController.prototype,"get",null),p([t.Put("/:id"),t.Middleware("auth"),t.Middleware("canUpdate"),t.Middleware("validation",{name:e.Validation.string().empty(),email:e.Validation.string().email().empty(),username:e.Validation.string().min(4).empty(),password:e.Validation.string().min(5).empty().filter(""),description:e.Validation.string().empty(),state:e.Validation.boolean().parse().empty()}),u(0,t.Ctx()),u(1,t.Params("id")),u(2,t.Body("password")),c("design:type",Function),c("design:paramtypes",[t.Context,String,String]),c("design:returntype",Promise)],exports.UsersController.prototype,"set",null),exports.UsersController=p([t.Controller("/users"),t.Extends(exports.ControllerModel),c("design:paramtypes",[])],exports.UsersController),exports.UsersGroupsController=class UsersGroupsController extends exports.ControllerModel{model(){return exports.UserGroup}all(e,t){return g(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:exports.Group,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return g(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(t,r,o,i){return g(this,void 0,void 0,function*(){const s=yield exports.User.findByPk(r,{attributes:["id"]}).catch(this.error);if(!s)return t.notFound("RECORD NOT FOUND");if(yield exports.UserGroup.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},i)),o){let t=0;yield e.sleep(1e3);for(let e=0;e<o.length;e++)t=yield exports.Group.count({where:{id:o[e]}}),t&&(yield exports.UserGroup.create({user_id:s.id,group_id:o[e]},Object.assign({},i)))}t.success("OK")})}},p([t.Get("/:id/groups"),t.Middleware("auth"),t.Middleware("canRead","users"),u(0,t.Ctx()),u(1,t.Params("id")),c("design:type",Function),c("design:paramtypes",[t.Context,String]),c("design:returntype",Promise)],exports.UsersGroupsController.prototype,"all",null),p([t.Get("/groups"),t.Middleware("auth"),t.Middleware("canRead","users"),u(0,t.Ctx()),u(1,x()),c("design:type",Function),c("design:paramtypes",[t.Context,exports.User]),c("design:returntype",Promise)],exports.UsersGroupsController.prototype,"me",null),p([t.Put("/:id/groups"),t.Middleware("auth"),t.Middleware("canUpdate","users"),t.Middleware("validation",{groups:e.Validation.array(e.Validation.number().parse())}),u(0,t.Ctx()),u(1,t.Params("id")),u(2,t.Body("groups")),u(3,h()),c("design:type",Function),c("design:paramtypes",[t.Context,String,Array,Object]),c("design:returntype",Promise)],exports.UsersGroupsController.prototype,"set",null),exports.UsersGroupsController=p([t.Controller("/users"),t.Extends(exports.ControllerModel)],exports.UsersGroupsController),exports.Application=Application,exports.AuthBase=AuthBase,exports.AuthKey=AuthKey,exports.AuthToken=AuthToken,exports.Controller=Controller,exports.ControllerBase=ControllerBase,exports.Env=Env,exports.ReqAudit=h,exports.ReqAuth=v,exports.ReqUser=x,exports.Store=Store,exports.audit=y,exports.crt=_,exports.database=m,exports.hooks=A,exports.key=S;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
3
|
-
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
-
* (c)
|
|
2
|
+
* @andrewcaires/api v4.5.1
|
|
3
|
+
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
+
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import { EventEmitter,
|
|
7
|
+
import { EventEmitter, TypeAnyObject, TypeObjectString, TypeObject, ValidationBase, TypeAnyFunction } from '@andrewcaires/utils.js';
|
|
8
8
|
import { Application as Application$1, Context, IStore, IUpload, IFile } from '@andrewcaires/express';
|
|
9
9
|
import { WhereOptions, Model as Model$1, CreateOptions, Attributes, FindOptions, UpdateOptions, FindAttributeOptions, ModelStatic } from 'sequelize';
|
|
10
|
-
import { Model,
|
|
10
|
+
import { Model, Sequelize } from '@andrewcaires/sequelize';
|
|
11
11
|
import { Hash, Env as Env$1 } from '@andrewcaires/node';
|
|
12
12
|
import { WebSocketServer } from 'ws';
|
|
13
13
|
import { Store as Store$1, SessionData } from 'express-session';
|
|
@@ -18,43 +18,43 @@ declare abstract class Controller extends EventEmitter {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
declare class Auth extends Model {
|
|
21
|
-
id: number;
|
|
21
|
+
readonly id: number;
|
|
22
22
|
secret: string;
|
|
23
23
|
logout: Date | null;
|
|
24
24
|
user_agent: string;
|
|
25
|
-
created_at: Date;
|
|
26
|
-
updated_at: Date;
|
|
27
|
-
deleted_at: Date | null;
|
|
25
|
+
readonly created_at: Date;
|
|
26
|
+
readonly updated_at: Date;
|
|
27
|
+
readonly deleted_at: Date | null;
|
|
28
28
|
user_id: number;
|
|
29
29
|
user: User;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
declare class Register extends Model {
|
|
33
|
-
id: number;
|
|
33
|
+
readonly id: number;
|
|
34
34
|
token: string;
|
|
35
35
|
state: boolean;
|
|
36
|
-
created_at: Date;
|
|
37
|
-
updated_at: Date;
|
|
38
|
-
deleted_at: Date | null;
|
|
36
|
+
readonly created_at: Date;
|
|
37
|
+
readonly updated_at: Date;
|
|
38
|
+
readonly deleted_at: Date | null;
|
|
39
39
|
user_id: number;
|
|
40
40
|
user: User;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
declare class Permission extends Model {
|
|
44
|
-
id: number;
|
|
44
|
+
readonly id: number;
|
|
45
45
|
name: string;
|
|
46
46
|
route: string;
|
|
47
47
|
tag: string;
|
|
48
48
|
description: string;
|
|
49
49
|
state: boolean;
|
|
50
|
-
created_at: Date;
|
|
51
|
-
updated_at: Date;
|
|
52
|
-
deleted_at: Date | null;
|
|
50
|
+
readonly created_at: Date;
|
|
51
|
+
readonly updated_at: Date;
|
|
52
|
+
readonly deleted_at: Date | null;
|
|
53
53
|
groups_permissions: Array<GroupPermission>;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
declare class GroupPermission extends Model {
|
|
57
|
-
created_at: Date;
|
|
57
|
+
readonly created_at: Date;
|
|
58
58
|
group_id: number;
|
|
59
59
|
group: Group;
|
|
60
60
|
permission_id: number;
|
|
@@ -62,19 +62,19 @@ declare class GroupPermission extends Model {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
declare class Group extends Model {
|
|
65
|
-
id: number;
|
|
65
|
+
readonly id: number;
|
|
66
66
|
name: string;
|
|
67
67
|
description: string;
|
|
68
68
|
state: boolean;
|
|
69
|
-
created_at: Date;
|
|
70
|
-
updated_at: Date;
|
|
71
|
-
deleted_at: Date | null;
|
|
69
|
+
readonly created_at: Date;
|
|
70
|
+
readonly updated_at: Date;
|
|
71
|
+
readonly deleted_at: Date | null;
|
|
72
72
|
groups_routes: Array<GroupPermission>;
|
|
73
73
|
users_groups: Array<UserGroup>;
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
declare class UserGroup extends Model {
|
|
77
|
-
created_at: Date;
|
|
77
|
+
readonly created_at: Date;
|
|
78
78
|
group_id: number;
|
|
79
79
|
group: Group;
|
|
80
80
|
user_id: number;
|
|
@@ -83,13 +83,13 @@ declare class UserGroup extends Model {
|
|
|
83
83
|
|
|
84
84
|
declare class UserHistory extends Model {
|
|
85
85
|
password: string;
|
|
86
|
-
created_at: Date;
|
|
86
|
+
readonly created_at: Date;
|
|
87
87
|
user_id: number;
|
|
88
88
|
user: User;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
declare class User extends Model {
|
|
92
|
-
id: number;
|
|
92
|
+
readonly id: number;
|
|
93
93
|
name: string;
|
|
94
94
|
email: string;
|
|
95
95
|
username: string;
|
|
@@ -100,9 +100,9 @@ declare class User extends Model {
|
|
|
100
100
|
date: string;
|
|
101
101
|
description: string;
|
|
102
102
|
state: boolean;
|
|
103
|
-
created_at: Date;
|
|
104
|
-
updated_at: Date;
|
|
105
|
-
deleted_at: Date | null;
|
|
103
|
+
readonly created_at: Date;
|
|
104
|
+
readonly updated_at: Date;
|
|
105
|
+
readonly deleted_at: Date | null;
|
|
106
106
|
audits: Array<Audit>;
|
|
107
107
|
auths: Array<Auth>;
|
|
108
108
|
registers: Array<Register>;
|
|
@@ -111,19 +111,19 @@ declare class User extends Model {
|
|
|
111
111
|
}
|
|
112
112
|
|
|
113
113
|
declare class Audit extends Model {
|
|
114
|
-
id: number;
|
|
114
|
+
readonly id: number;
|
|
115
115
|
type: string;
|
|
116
116
|
model: string;
|
|
117
117
|
record: string;
|
|
118
|
-
data:
|
|
119
|
-
previously:
|
|
118
|
+
data: TypeAnyObject;
|
|
119
|
+
previously: TypeAnyObject;
|
|
120
120
|
client: string;
|
|
121
121
|
href: string;
|
|
122
122
|
user_agent: string;
|
|
123
123
|
state: boolean;
|
|
124
|
-
created_at: Date;
|
|
125
|
-
updated_at: Date;
|
|
126
|
-
deleted_at: Date | null;
|
|
124
|
+
readonly created_at: Date;
|
|
125
|
+
readonly updated_at: Date;
|
|
126
|
+
readonly deleted_at: Date | null;
|
|
127
127
|
user_id: number;
|
|
128
128
|
user: User;
|
|
129
129
|
}
|
|
@@ -131,8 +131,8 @@ declare class Audit extends Model {
|
|
|
131
131
|
declare class Config extends Model {
|
|
132
132
|
key: string;
|
|
133
133
|
value: string;
|
|
134
|
-
created_at: Date;
|
|
135
|
-
updated_at: Date;
|
|
134
|
+
readonly created_at: Date;
|
|
135
|
+
readonly updated_at: Date;
|
|
136
136
|
static all(): Promise<TypeObjectString>;
|
|
137
137
|
static del(key: string, user?: User): Promise<boolean>;
|
|
138
138
|
static get(key: string, value?: string): Promise<string>;
|
|
@@ -140,23 +140,23 @@ declare class Config extends Model {
|
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
declare class Forgot extends Model {
|
|
143
|
-
id: number;
|
|
143
|
+
readonly id: number;
|
|
144
144
|
token: string;
|
|
145
145
|
timestamp: number;
|
|
146
146
|
state: boolean;
|
|
147
|
-
created_at: Date;
|
|
148
|
-
updated_at: Date;
|
|
149
|
-
deleted_at: Date | null;
|
|
147
|
+
readonly created_at: Date;
|
|
148
|
+
readonly updated_at: Date;
|
|
149
|
+
readonly deleted_at: Date | null;
|
|
150
150
|
user_id: number;
|
|
151
151
|
user: User;
|
|
152
152
|
}
|
|
153
153
|
|
|
154
154
|
declare class Log extends Model {
|
|
155
|
-
id: number;
|
|
155
|
+
readonly id: number;
|
|
156
156
|
type: string;
|
|
157
157
|
source: string;
|
|
158
158
|
message: string;
|
|
159
|
-
created_at: Date;
|
|
159
|
+
readonly created_at: Date;
|
|
160
160
|
static write(message: string, source?: string, show?: boolean): Promise<void>;
|
|
161
161
|
static error(message: string, source?: string, show?: boolean): Promise<void>;
|
|
162
162
|
static info(message: string, source?: string, show?: boolean): Promise<void>;
|
|
@@ -168,16 +168,16 @@ declare class Log extends Model {
|
|
|
168
168
|
declare class Migration extends Model {
|
|
169
169
|
model: string;
|
|
170
170
|
version: string;
|
|
171
|
-
created_at: Date;
|
|
172
|
-
updated_at: Date;
|
|
171
|
+
readonly created_at: Date;
|
|
172
|
+
readonly updated_at: Date;
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
declare class Session extends Model {
|
|
176
176
|
session: string;
|
|
177
177
|
json: string;
|
|
178
178
|
expired: number;
|
|
179
|
-
created_at: Date;
|
|
180
|
-
updated_at: Date;
|
|
179
|
+
readonly created_at: Date;
|
|
180
|
+
readonly updated_at: Date;
|
|
181
181
|
}
|
|
182
182
|
|
|
183
183
|
declare class Application extends Application$1 {
|
|
@@ -187,7 +187,7 @@ declare class Application extends Application$1 {
|
|
|
187
187
|
error(error: any, source?: string): void;
|
|
188
188
|
log(message: string, source?: string): void;
|
|
189
189
|
listen(): Promise<void>;
|
|
190
|
-
migrations(database:
|
|
190
|
+
migrations(database: Sequelize): Promise<void>;
|
|
191
191
|
websocket(): WebSocketServer | undefined;
|
|
192
192
|
}
|
|
193
193
|
|
|
@@ -214,16 +214,16 @@ interface ArgumentsModel<M extends Model$1<M>> {
|
|
|
214
214
|
|
|
215
215
|
interface ArgumentsModelCreate<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
216
216
|
options?: CreateOptions<Attributes<M>>;
|
|
217
|
-
body?:
|
|
217
|
+
body?: TypeAnyObject;
|
|
218
218
|
}
|
|
219
219
|
|
|
220
220
|
interface ArgumentsModelDelete<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
221
221
|
options?: FindOptions<Attributes<M>>;
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
-
type CallbackModelAll<M> = (
|
|
224
|
+
type CallbackModelAll<M> = (_records: Array<M>) => Array<any> | Promise<Array<any>>;
|
|
225
225
|
|
|
226
|
-
interface ArgumentsModelFindAll<M extends Model$1<
|
|
226
|
+
interface ArgumentsModelFindAll<M extends Model$1<any>> extends ArgumentsModel<M> {
|
|
227
227
|
options?: FindOptions<Attributes<M>>;
|
|
228
228
|
callback?: CallbackModelAll<M>;
|
|
229
229
|
scope?: string;
|
|
@@ -232,7 +232,7 @@ interface ArgumentsModelFindAll<M extends Model$1<M>> extends ArgumentsModel<M>
|
|
|
232
232
|
limited?: boolean;
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
-
type CallbackModelGet<M> = (
|
|
235
|
+
type CallbackModelGet<M> = (_records: M) => any | Promise<any>;
|
|
236
236
|
|
|
237
237
|
interface ArgumentsModelFindOne<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
238
238
|
options?: FindOptions<Attributes<M>>;
|
|
@@ -242,36 +242,24 @@ interface ArgumentsModelFindOne<M extends Model$1<M>> extends ArgumentsModel<M>
|
|
|
242
242
|
|
|
243
243
|
interface ArgumentsModelUpdate<M extends Model$1<M>> extends ArgumentsModel<M> {
|
|
244
244
|
options?: UpdateOptions<Attributes<M>>;
|
|
245
|
-
body?:
|
|
245
|
+
body?: TypeAnyObject;
|
|
246
246
|
}
|
|
247
247
|
|
|
248
248
|
interface IAuthParameters {
|
|
249
249
|
auth?: Auth;
|
|
250
|
-
decode?:
|
|
250
|
+
decode?: TypeAnyObject;
|
|
251
251
|
error?: string;
|
|
252
252
|
forgot?: Forgot;
|
|
253
253
|
token?: string;
|
|
254
254
|
user?: User;
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
-
interface IDatabaseOptions {
|
|
258
|
-
database: string;
|
|
259
|
-
username: string;
|
|
260
|
-
password: string;
|
|
261
|
-
hostname: string;
|
|
262
|
-
hostport: number;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
interface IMigrate {
|
|
266
|
-
version: string;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
257
|
interface ResultModelAll<M extends Model$1<M>> {
|
|
270
258
|
count: number;
|
|
271
259
|
records: Array<M>;
|
|
272
260
|
}
|
|
273
261
|
|
|
274
|
-
declare abstract class ControllerModel<M extends Model$1<
|
|
262
|
+
declare abstract class ControllerModel<M extends Model$1<any>> extends ControllerBase {
|
|
275
263
|
protected [ControllerBase.ATTRIBUTES]: Array<string>;
|
|
276
264
|
protected [ControllerBase.PERMISSIONS]: Array<string>;
|
|
277
265
|
protected attributes(options: FindAttributeOptions): Array<string>;
|
|
@@ -288,7 +276,7 @@ declare abstract class ControllerModel<M extends Model$1<M>> extends ControllerB
|
|
|
288
276
|
scope(name?: string): ModelStatic<M>;
|
|
289
277
|
}
|
|
290
278
|
|
|
291
|
-
declare abstract class ControllerCrud<M extends Model$1<
|
|
279
|
+
declare abstract class ControllerCrud<M extends Model$1<any>> extends ControllerModel<M> {
|
|
292
280
|
private _crud;
|
|
293
281
|
CrudArgumentsCreate(ctx: Context): ArgumentsModelUpdate<M>;
|
|
294
282
|
CrudArgumentsFindAll(ctx: Context): ArgumentsModelFindAll<M>;
|
|
@@ -313,16 +301,11 @@ declare class Env extends Env$1 {
|
|
|
313
301
|
static readonly API_BODYPARSER_LIMIT: string;
|
|
314
302
|
static readonly API_BODYPARSER_TYPE: string;
|
|
315
303
|
static readonly API_CONSOLE_ERROR: boolean;
|
|
316
|
-
static readonly
|
|
317
|
-
static readonly
|
|
318
|
-
static readonly
|
|
319
|
-
static readonly
|
|
320
|
-
static readonly
|
|
321
|
-
static readonly API_DB_USERNAME: string;
|
|
322
|
-
static readonly API_DB_LOG: boolean;
|
|
323
|
-
static readonly API_DB_AUDIT: boolean;
|
|
324
|
-
static readonly API_DB_PREFIX: string;
|
|
325
|
-
static readonly API_DB_TIMEZONE: string;
|
|
304
|
+
static readonly API_DATABASE_URL: string;
|
|
305
|
+
static readonly API_DATABASE_LOG: boolean;
|
|
306
|
+
static readonly API_DATABASE_AUDIT: boolean;
|
|
307
|
+
static readonly API_DATABASE_PREFIX: string;
|
|
308
|
+
static readonly API_DATABASE_TIMEZONE: string;
|
|
326
309
|
static readonly API_HTTP_CRT: string;
|
|
327
310
|
static readonly API_HTTP_KEY: string;
|
|
328
311
|
static readonly API_HTTP_PORT: number;
|
|
@@ -373,7 +356,7 @@ declare class AuthController extends ControllerBase {
|
|
|
373
356
|
declare class FilesController extends ControllerBase {
|
|
374
357
|
protected [ControllerBase.PERMISSIONS]: Array<string>;
|
|
375
358
|
directory(): string;
|
|
376
|
-
protected files(ctx: Context): Promise<
|
|
359
|
+
protected files(ctx: Context): Promise<TypeAnyObject | void>;
|
|
377
360
|
protected access(ctx: Context, name: string, user: User): Promise<void>;
|
|
378
361
|
private info;
|
|
379
362
|
name(): string;
|
|
@@ -400,7 +383,7 @@ declare class GroupsPermissionsController extends ControllerModel<GroupPermissio
|
|
|
400
383
|
model(): typeof GroupPermission;
|
|
401
384
|
protected all(ctx: Context, group_id: string): Promise<void>;
|
|
402
385
|
protected me(ctx: Context, user: User): Promise<void>;
|
|
403
|
-
protected set(ctx: Context, id: string, permissions: Array<number>, audit:
|
|
386
|
+
protected set(ctx: Context, id: string, permissions: Array<number>, audit: TypeAnyObject): Promise<void>;
|
|
404
387
|
}
|
|
405
388
|
|
|
406
389
|
declare class LogsController extends ControllerModel<Log> {
|
|
@@ -419,27 +402,27 @@ declare class PermissionsController extends ControllerCrud<Permission> {
|
|
|
419
402
|
}
|
|
420
403
|
|
|
421
404
|
declare class RegisterController extends ControllerBase {
|
|
422
|
-
protected register(ctx: Context, body:
|
|
405
|
+
protected register(ctx: Context, body: TypeAnyObject, app: Application): Promise<void>;
|
|
423
406
|
protected confirm(ctx: Context, token: string, app: Application): Promise<void>;
|
|
424
407
|
protected send(ctx: Context, username: string, app: Application): Promise<void>;
|
|
425
408
|
private getId;
|
|
426
409
|
}
|
|
427
410
|
|
|
428
411
|
declare class SetupController extends ControllerBase {
|
|
429
|
-
protected setup(ctx: Context, audit:
|
|
412
|
+
protected setup(ctx: Context, audit: TypeAnyObject): Promise<void>;
|
|
430
413
|
}
|
|
431
414
|
|
|
432
415
|
declare class UsersController extends ControllerModel<User> {
|
|
433
416
|
path: string;
|
|
434
417
|
model(): typeof User;
|
|
435
418
|
constructor();
|
|
436
|
-
protected avatar(ctx: Context, files: Array<IFile>, user: User, audit:
|
|
437
|
-
protected avatar_del(ctx: Context, user: User, audit:
|
|
438
|
-
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User, audit:
|
|
419
|
+
protected avatar(ctx: Context, files: Array<IFile>, user: User, audit: TypeAnyObject): Promise<void>;
|
|
420
|
+
protected avatar_del(ctx: Context, user: User, audit: TypeAnyObject): Promise<void>;
|
|
421
|
+
protected password(ctx: Context, oldPassword: string, newPassword: string, user: User, audit: TypeAnyObject): Promise<void>;
|
|
439
422
|
protected token(ctx: Context, user: User, app: Application): Promise<void>;
|
|
440
|
-
protected token_del(ctx: Context, id: string, audit:
|
|
423
|
+
protected token_del(ctx: Context, id: string, audit: TypeAnyObject): Promise<void>;
|
|
441
424
|
protected token_get(ctx: Context, id: string, app: Application): Promise<void>;
|
|
442
|
-
protected token_renew(ctx: Context, id: string, audit:
|
|
425
|
+
protected token_renew(ctx: Context, id: string, audit: TypeAnyObject, app: Application): Promise<void>;
|
|
443
426
|
private token_new;
|
|
444
427
|
protected add(ctx: Context, password: string): Promise<void>;
|
|
445
428
|
protected all(ctx: Context): Promise<void>;
|
|
@@ -452,10 +435,10 @@ declare class UsersGroupsController extends ControllerModel<UserGroup> {
|
|
|
452
435
|
model(): typeof UserGroup;
|
|
453
436
|
protected all(ctx: Context, user_id: string): Promise<void>;
|
|
454
437
|
protected me(ctx: Context, user: User): Promise<void>;
|
|
455
|
-
protected set(ctx: Context, id: string, groups: Array<number>, audit:
|
|
438
|
+
protected set(ctx: Context, id: string, groups: Array<number>, audit: TypeAnyObject): Promise<void>;
|
|
456
439
|
}
|
|
457
440
|
|
|
458
|
-
declare const database:
|
|
441
|
+
declare const database: Sequelize;
|
|
459
442
|
|
|
460
443
|
declare const ReqAudit: (key?: string) => ParameterDecorator;
|
|
461
444
|
|
|
@@ -472,13 +455,6 @@ declare global {
|
|
|
472
455
|
}
|
|
473
456
|
}
|
|
474
457
|
|
|
475
|
-
declare const Migrate: (version: string) => ClassDecorator;
|
|
476
|
-
|
|
477
|
-
declare class Metadata {
|
|
478
|
-
static readonly MIGRATE: unique symbol;
|
|
479
|
-
static migrations(target: any): IMigrate;
|
|
480
|
-
}
|
|
481
|
-
|
|
482
458
|
declare class AuthBase {
|
|
483
459
|
protected static error(error: any): void;
|
|
484
460
|
}
|
|
@@ -496,12 +472,12 @@ declare class AuthToken extends AuthBase {
|
|
|
496
472
|
private static verify;
|
|
497
473
|
}
|
|
498
474
|
|
|
499
|
-
declare const audit: (ctx: Context) =>
|
|
475
|
+
declare const audit: (ctx: Context) => TypeAnyObject;
|
|
500
476
|
|
|
501
477
|
declare const hooks: {
|
|
502
|
-
afterCreate: (record: Model, options:
|
|
503
|
-
afterUpdate: (record: Model, options:
|
|
504
|
-
afterDestroy: (record: Model, options:
|
|
478
|
+
afterCreate: (record: Model, options: TypeAnyObject) => Promise<void>;
|
|
479
|
+
afterUpdate: (record: Model, options: TypeAnyObject) => Promise<void>;
|
|
480
|
+
afterDestroy: (record: Model, options: TypeAnyObject) => Promise<void>;
|
|
505
481
|
};
|
|
506
482
|
|
|
507
483
|
declare const crt: {
|
|
@@ -516,14 +492,14 @@ declare const key: {
|
|
|
516
492
|
declare class Store extends Store$1 {
|
|
517
493
|
private loop;
|
|
518
494
|
constructor();
|
|
519
|
-
all: (callback:
|
|
520
|
-
clear: (callback:
|
|
521
|
-
destroy: (session_id: string, callback:
|
|
495
|
+
all: (callback: TypeAnyFunction) => Promise<void>;
|
|
496
|
+
clear: (callback: TypeAnyFunction) => Promise<void>;
|
|
497
|
+
destroy: (session_id: string, callback: TypeAnyFunction) => Promise<void>;
|
|
522
498
|
expired: () => Promise<void>;
|
|
523
|
-
get: (session_id: string, callback:
|
|
524
|
-
length: (callback:
|
|
525
|
-
set: (session_id: any, session: SessionData, callback:
|
|
499
|
+
get: (session_id: string, callback: TypeAnyFunction) => Promise<void>;
|
|
500
|
+
length: (callback: TypeAnyFunction) => Promise<void>;
|
|
501
|
+
set: (session_id: any, session: SessionData, callback: TypeAnyFunction) => Promise<void>;
|
|
526
502
|
}
|
|
527
503
|
|
|
528
|
-
export { Application, Audit, AuditsController, Auth, AuthBase, AuthController, AuthKey, AuthToken, Config, Controller, ControllerBase, ControllerCrud, ControllerModel, Env, FilesController, Forgot, ForgotController, Group, GroupPermission, GroupsController, GroupsPermissionsController, Log, LogsController,
|
|
529
|
-
export type { ArgumentsModel, ArgumentsModelCreate, ArgumentsModelDelete, ArgumentsModelFindAll, ArgumentsModelFindOne, ArgumentsModelUpdate, CallbackModelAll, CallbackModelGet, IAuthParameters,
|
|
504
|
+
export { Application, Audit, AuditsController, Auth, AuthBase, AuthController, AuthKey, AuthToken, Config, Controller, ControllerBase, ControllerCrud, ControllerModel, Env, FilesController, Forgot, ForgotController, Group, GroupPermission, GroupsController, GroupsPermissionsController, Log, LogsController, Migration, Permission, PermissionsController, Register, RegisterController, ReqAudit, ReqAuth, ReqUser, Session, SetupController, Store, User, UserGroup, UserHistory, UsersController, UsersGroupsController, audit, crt, database, hooks, key };
|
|
505
|
+
export type { ArgumentsModel, ArgumentsModelCreate, ArgumentsModelDelete, ArgumentsModelFindAll, ArgumentsModelFindOne, ArgumentsModelUpdate, CallbackModelAll, CallbackModelGet, IAuthParameters, ResultModelAll };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @andrewcaires/api v4.
|
|
3
|
-
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
-
* (c)
|
|
2
|
+
* @andrewcaires/api v4.5.1
|
|
3
|
+
* Simple api for small applications using express, jsonwebtoken, sequelize and websocket
|
|
4
|
+
* (c) 2026 Andrew Caires
|
|
5
5
|
* @license: MIT
|
|
6
6
|
*/
|
|
7
|
-
import{EventEmitter as e,isObject as t,noop as i,uuidv4 as r,loop as s,forEachSeries as n,isFunction as o,sleep as d,upperCamelCase as a,Validation as u,isArray as p,isString as c,isUndefined as l,clamp as y,isNumber as g,denied as h,isDef as v,uniqueID as _}from"@andrewcaires/utils.js";import{parameterFactory as m,Application as E,Ctx as A,Headers as O,Query as I,App as f,Context as P,Argument as R,Session as S,Upload as T,Extends as D,Status as N,Post as b,Middleware as w,Get as C,Delete as x,Put as F,Controller as j,Body as k,Params as L,Files as U}from"@andrewcaires/express";import{Env as B,Metadata as M,LogColor as H,Log as K,Hash as q,sha256 as Y}from"@andrewcaires/node";import{config as V}from"dotenv";import{Connection as $,Id as G,String as W,FullDate as z,CreatedAt as J,UpdatedAt as Z,DeletedAt as X,BelongsTo as Q,Database as ee,ModelName as te,Model as ie,Boolean as re,Text as se,HasMany as ne,Hooks as oe,DateOnly as de,DefaultScope as ae,Scopes as ue,Enum as pe,Json as ce,BigInt as le,Unique as ye,migrate as ge,Where as he}from"@andrewcaires/sequelize";import ve from"jsonwebtoken";import{readFileSync as _e,existsSync as me,statSync as Ee,readdirSync as Ae,mkdirSync as Oe,lstatSync as Ie,rmSync as fe}from"fs";import{WebSocketServer as Pe}from"ws";import{Store as Re}from"express-session";import{Op as Se}from"sequelize";import{join as Te}from"path";class De extends e{}function Ne(e,t,i,r){var s,n=arguments.length,o=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(s=e[d])&&(o=(n<3?s(o):n>3?s(t,i,o):s(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}function be(e,t){return function(i,r){t(i,r,e)}}function we(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Ce(e,t,i,r){return new(i||(i=Promise))(function(s,n){function o(e){try{a(r.next(e))}catch(e){n(e)}}function d(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,d)}a((r=r.apply(e,t||[])).next())})}De.ATTRIBUTES=Symbol("ATTRIBUTES"),De.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError,V({quiet:!0});class xe extends B{}xe.API_BASE_NAME=xe.getString("API_BASE_NAME",""),xe.API_BODYPARSER_STRICT=xe.getBool("API_BODYPARSER_STRICT",!0),xe.API_BODYPARSER_INFLATE=xe.getBool("API_BODYPARSER_INFLATE",!0),xe.API_BODYPARSER_LIMIT=xe.getString("API_BODYPARSER_LIMIT","10mb"),xe.API_BODYPARSER_TYPE=xe.getString("API_BODYPARSER_TYPE","json"),xe.API_CONSOLE_ERROR=xe.getBool("API_CONSOLE_ERROR",!1),xe.API_DB_DATABASE=xe.getString("API_DB_DATABASE",""),xe.API_DB_HOST=xe.getString("API_DB_HOST","127.0.0.1"),xe.API_DB_PASSWORD=xe.getString("API_DB_PASSWORD",""),xe.API_DB_PORT=xe.getInt("API_DB_PORT",3306),xe.API_DB_TYPE=xe.getString("API_DB_TYPE",""),xe.API_DB_USERNAME=xe.getString("API_DB_USERNAME","root"),xe.API_DB_LOG=xe.getBool("API_DB_LOG",!1),xe.API_DB_AUDIT=xe.getBool("API_DB_AUDIT",!0),xe.API_DB_PREFIX=xe.getString("API_DB_PREFIX",""),xe.API_DB_TIMEZONE=xe.getString("API_DB_TIMEZONE","+00:00"),xe.API_HTTP_CRT=xe.getString("API_HTTP_CRT",""),xe.API_HTTP_KEY=xe.getString("API_HTTP_KEY",""),xe.API_HTTP_PORT=xe.getInt("API_HTTP_PORT",3e3),xe.API_HTTP_PUBLIC=xe.getString("API_HTTP_PUBLIC",""),xe.API_HTTP_CROSS=xe.getBool("API_HTTP_CROSS",!1),xe.API_HTTP_HYBRID=xe.getBool("API_HTTP_HYBRID",!1),xe.API_HTTP_NOTFOUND=xe.getString("API_HTTP_NOTFOUND",""),xe.API_HTTP_PATH=xe.getString("API_HTTP_PATH","/api"),xe.API_HTTP_REDIRECT=xe.getString("API_HTTP_REDIRECT",""),xe.API_KEY_HASH=xe.getString("API_KEY_HASH",""),xe.API_KEY_HEADER=xe.getString("API_KEY_HEADER","x-api-key"),xe.API_MODEL_LIMIT=xe.getInt("API_MODEL_LIMIT",10),xe.API_MODEL_LIMIT_MAX=xe.getInt("API_MODEL_LIMIT_MAX",500),xe.API_SLEEP_AUTH=xe.getMs("API_SLEEP_AUTH","2s"),xe.API_SLEEP_FORGOT=xe.getMs("API_SLEEP_FORGOT","5s"),xe.API_SLEEP_REGISTRY=xe.getMs("API_SLEEP_REGISTRY","5s"),xe.API_SESSION_NAME=xe.getString("API_SESSION_NAME","session.id"),xe.API_SESSION_LIFETIME=xe.getMs("API_SESSION_LIFETIME","1d"),xe.API_SESSION_SECRET=xe.getString("API_SESSION_SECRET","yoursecret"),xe.API_TOKEN_CRT=xe.getString("API_TOKEN_CRT",""),xe.API_TOKEN_KEY=xe.getString("API_TOKEN_KEY",""),xe.API_TOKEN_FORGOT=xe.getMs("API_TOKEN_LIFETIME","1d"),xe.API_TOKEN_HEADER=xe.getString("API_TOKEN_HEADER","authorization"),xe.API_TOKEN_HEADER_KEY=xe.getString("API_TOKEN_HEADER","bearer"),xe.API_TOKEN_LIFETIME=xe.getMs("API_TOKEN_LIFETIME","1d"),xe.API_TOKEN_RENEW=xe.getMs("API_TOKEN_RENEW","1d"),xe.API_UPLOAD_COUNT=xe.getInt("API_UPLOAD_COUNT",1),xe.API_UPLOAD_FIELD=xe.getString("API_UPLOAD_FIELD","upload"),xe.API_UPLOAD_SIZE=xe.getInt("API_UPLOAD_SIZE",2),xe.API_UPLOAD_TEMP=xe.getString("API_UPLOAD_TEMP","./temp"),xe.API_USER_HISTORY=xe.getBool("API_USER_HISTORY",!0),xe.API_WEBSOCKET_START=xe.getBool("API_WEBSOCKET_START",!1);const Fe=e=>{var t,i,r,s,n,o,d,a,u;return{audit_client:null!==(t=e.ip())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.protocol)+"://"+(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.get("host"))+(null===(s=null==e?void 0:e.req)||void 0===s?void 0:s.originalUrl),audit_user_agent:null!==(o=null===(n=e.req)||void 0===n?void 0:n.headers["user-agent"])&&void 0!==o?o:"",audit_user_id:null!==(u=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==u?u:null}},je=m(({ctx:e})=>Fe(e)),ke=m(({ctx:e})=>e.req.auth),Le=m(({ctx:e})=>e.req.user),Ue=e=>t=>{Be.migrations(t).version=e};class Be{static migrations(e){return M(Be.MIGRATE,e,{version:""})}}Be.MIGRATE=Symbol("MIGRATE");const Me=new $({type:xe.API_DB_TYPE,database:xe.API_DB_DATABASE,username:xe.API_DB_USERNAME,password:xe.API_DB_PASSWORD,hostname:xe.API_DB_HOST,hostport:xe.API_DB_PORT,logging:xe.API_DB_LOG,prefix:xe.API_DB_PREFIX,timezone:xe.API_DB_TIMEZONE}),He=(e,t,i)=>{var r,s,n,o,d;return{type:e,model:null!==(r=null==t?void 0:t.getTableName())&&void 0!==r?r:null,client:null!==(s=null==i?void 0:i.audit_client)&&void 0!==s?s:null,href:null!==(n=null==i?void 0:i.audit_href)&&void 0!==n?n:null,user_agent:null!==(o=null==i?void 0:i.audit_user_agent)&&void 0!==o?o:null,user_id:null!==(d=null==i?void 0:i.audit_user_id)&&void 0!==d?d:null,state:!0}},Ke={afterCreate:(e,r)=>Ce(void 0,void 0,void 0,function*(){var s;if(!xe.API_DB_AUDIT)return;const n=t(e)?e.constructor:null,o=null!==(s=null==n?void 0:n.primaryKeyAttribute)&&void 0!==s?s:null;yield ze.create(Object.assign(Object.assign({},He("CREATE",n,r)),{record:o?e.getDataValue(o):null,data:e.toJSON()})).catch(i)}),afterUpdate:(e,r)=>Ce(void 0,void 0,void 0,function*(){var s;if(!xe.API_DB_AUDIT)return;const n=t(e)?e.constructor:null,o=null!==(s=null==n?void 0:n.primaryKeyAttribute)&&void 0!==s?s:null,d={},a=e.changed();a&&a.forEach(t=>d[t]=e.getDataValue(t)),yield ze.create(Object.assign(Object.assign({},He("UPDATE",n,r)),{record:o?e.getDataValue(o):null,data:d,previously:e.previous()})).catch(i)}),afterDestroy:(e,r)=>Ce(void 0,void 0,void 0,function*(){var s;if(!xe.API_DB_AUDIT)return;const n=t(e)?e.constructor:null,o=null!==(s=null==n?void 0:n.primaryKeyAttribute)&&void 0!==s?s:null;yield ze.create(Object.assign(Object.assign({},He("DELETE",n,r)),{record:o?e.getDataValue(o):null,data:e.toJSON()})).catch(i)})};let qe=class extends ie{};Ne([G(),we("design:type",Number)],qe.prototype,"id",void 0),Ne([W(),we("design:type",W)],qe.prototype,"secret",void 0),Ne([z(),we("design:type",Object)],qe.prototype,"logout",void 0),Ne([W(),we("design:type",W)],qe.prototype,"user_agent",void 0),Ne([J,we("design:type",Date)],qe.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],qe.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],qe.prototype,"deleted_at",void 0),Ne([Q(()=>We),we("design:type",Number)],qe.prototype,"user_id",void 0),qe=Ne([ee(Me),te("auth"),Ue("4.2.0")],qe);let Ye=class extends ie{};Ne([G(),we("design:type",Number)],Ye.prototype,"id",void 0),Ne([W(),we("design:type",W)],Ye.prototype,"token",void 0),Ne([re(),we("design:type",re)],Ye.prototype,"state",void 0),Ne([J,we("design:type",Date)],Ye.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],Ye.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],Ye.prototype,"deleted_at",void 0),Ne([Q(()=>We),we("design:type",Number)],Ye.prototype,"user_id",void 0),Ye=Ne([ee(Me),te("register"),Ue("4.2.0")],Ye);let Ve=class extends ie{};Ne([G(),we("design:type",Number)],Ve.prototype,"id",void 0),Ne([W(),we("design:type",W)],Ve.prototype,"name",void 0),Ne([se(),we("design:type",W)],Ve.prototype,"description",void 0),Ne([re(),we("design:type",re)],Ve.prototype,"state",void 0),Ne([J,we("design:type",Date)],Ve.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],Ve.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],Ve.prototype,"deleted_at",void 0),Ne([ne(()=>$e,"group_id"),we("design:type",Array)],Ve.prototype,"groups_routes",void 0),Ne([ne(()=>$e,"group_id"),we("design:type",Array)],Ve.prototype,"users_groups",void 0),Ve=Ne([ee(Me),te("group"),oe(Ke),Ue("4.2.0")],Ve);let $e=class extends ie{};Ne([J,we("design:type",Date)],$e.prototype,"created_at",void 0),Ne([Q(()=>Ve),we("design:type",Number)],$e.prototype,"group_id",void 0),Ne([Q(()=>We),we("design:type",Number)],$e.prototype,"user_id",void 0),$e=Ne([ee(Me),te("users_groups"),oe(Ke),Ue("4.2.0")],$e);let Ge=class extends ie{};Ne([W(),we("design:type",W)],Ge.prototype,"password",void 0),Ne([J,we("design:type",Date)],Ge.prototype,"created_at",void 0),Ne([Q(()=>We),we("design:type",Number)],Ge.prototype,"user_id",void 0),Ge=Ne([ee(Me),te("users_histories"),Ue("4.2.0")],Ge);let We=class extends ie{};Ne([G(),we("design:type",Number)],We.prototype,"id",void 0),Ne([W(),we("design:type",W)],We.prototype,"name",void 0),Ne([W(),we("design:type",W)],We.prototype,"email",void 0),Ne([W(),we("design:type",W)],We.prototype,"username",void 0),Ne([W(),we("design:type",W)],We.prototype,"password",void 0),Ne([W(),we("design:type",W)],We.prototype,"salt",void 0),Ne([W(),we("design:type",W)],We.prototype,"token",void 0),Ne([W(),we("design:type",W)],We.prototype,"avatar",void 0),Ne([de(),we("design:type",W)],We.prototype,"date",void 0),Ne([se(),we("design:type",W)],We.prototype,"description",void 0),Ne([re(),we("design:type",re)],We.prototype,"state",void 0),Ne([J,we("design:type",Date)],We.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],We.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],We.prototype,"deleted_at",void 0),Ne([ne(()=>ze,"user_id"),we("design:type",Array)],We.prototype,"audits",void 0),Ne([ne(()=>qe,"user_id"),we("design:type",Array)],We.prototype,"auths",void 0),Ne([ne(()=>Ye,"user_id"),we("design:type",Array)],We.prototype,"registers",void 0),Ne([ne(()=>$e,"user_id"),we("design:type",Array)],We.prototype,"users_groups",void 0),Ne([ne(()=>Ge,"user_id"),we("design:type",Array)],We.prototype,"users_histories",void 0),We=Ne([ee(Me),te("user"),ae({attributes:{exclude:["password","salt","token"]}}),ue({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),oe(Ke),Ue("4.2.0")],We);let ze=class extends ie{};Ne([G(),we("design:type",Number)],ze.prototype,"id",void 0),Ne([pe("CREATE","DELETE","UPDATE"),we("design:type",W)],ze.prototype,"type",void 0),Ne([W(),we("design:type",W)],ze.prototype,"model",void 0),Ne([W(),we("design:type",W)],ze.prototype,"record",void 0),Ne([ce(),we("design:type",Object)],ze.prototype,"data",void 0),Ne([ce(),we("design:type",Object)],ze.prototype,"previously",void 0),Ne([W(),we("design:type",W)],ze.prototype,"client",void 0),Ne([se(),we("design:type",W)],ze.prototype,"href",void 0),Ne([W(),we("design:type",W)],ze.prototype,"user_agent",void 0),Ne([re(),we("design:type",re)],ze.prototype,"state",void 0),Ne([J,we("design:type",Date)],ze.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],ze.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],ze.prototype,"deleted_at",void 0),Ne([Q(()=>We),we("design:type",Number)],ze.prototype,"user_id",void 0),ze=Ne([ee(Me),te("audit"),Ue("4.2.0")],ze);let Je=class extends ie{static all(){return Ce(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return Ce(this,void 0,void 0,function*(){var i;const r=null!==(i=null==t?void 0:t.id)&&void 0!==i?i:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(this.error))||0)>0})}static get(e){return Ce(this,arguments,void 0,function*(e,t=""){const[i]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t,i){return Ce(this,void 0,void 0,function*(){var r;const s=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[n]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:s})).catch(this.error))||[];n&&(n.value=t,yield n.save().catch(this.error))})}};Ne([W(),we("design:type",W)],Je.prototype,"key",void 0),Ne([W(),we("design:type",W)],Je.prototype,"value",void 0),Ne([J,we("design:type",Date)],Je.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],Je.prototype,"updated_at",void 0),Je=Ne([ee(Me),te("configs"),Ue("4.2.0")],Je);let Ze=class extends ie{};Ne([G(),we("design:type",Number)],Ze.prototype,"id",void 0),Ne([W(),we("design:type",W)],Ze.prototype,"token",void 0),Ne([le(),we("design:type",Number)],Ze.prototype,"timestamp",void 0),Ne([re(),we("design:type",re)],Ze.prototype,"state",void 0),Ne([J,we("design:type",Date)],Ze.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],Ze.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],Ze.prototype,"deleted_at",void 0),Ne([Q(()=>We),we("design:type",Number)],Ze.prototype,"user_id",void 0),Ze=Ne([ee(Me),te("forgot"),Ue("4.2.0")],Ze);let Xe=class extends ie{};Ne([G(),we("design:type",Number)],Xe.prototype,"id",void 0),Ne([W(),we("design:type",W)],Xe.prototype,"name",void 0),Ne([W(),ye(!0),we("design:type",W)],Xe.prototype,"route",void 0),Ne([W(),we("design:type",W)],Xe.prototype,"tag",void 0),Ne([se(),we("design:type",W)],Xe.prototype,"description",void 0),Ne([re(),we("design:type",re)],Xe.prototype,"state",void 0),Ne([J,we("design:type",Date)],Xe.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],Xe.prototype,"updated_at",void 0),Ne([X,we("design:type",Object)],Xe.prototype,"deleted_at",void 0),Ne([ne(()=>Qe,"permission_id"),we("design:type",Array)],Xe.prototype,"groups_permissions",void 0),Xe=Ne([ee(Me),te("permission"),oe(Ke),Ue("4.3.1")],Xe);let Qe=class extends ie{};Ne([J,we("design:type",Date)],Qe.prototype,"created_at",void 0),Ne([Q(()=>Ve),we("design:type",Number)],Qe.prototype,"group_id",void 0),Ne([Q(()=>Xe),we("design:type",Number)],Qe.prototype,"permission_id",void 0),Qe=Ne([ee(Me),te("groups_permissions"),oe(Ke),Ue("4.2.0")],Qe);let et=class extends ie{static write(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw(H.White,"",e,t,i)})}static error(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw(H.Red,"error",e,t,i)})}static info(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw(H.Cyan,"info",e,t,i)})}static success(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw(H.Green,"success",e,t,i)})}static warning(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.writeRaw(H.Yellow,"warning",e,t,i)})}static writeRaw(e,t,i,r,s){return Ce(this,void 0,void 0,function*(){s&&K.console(e,t,i),Me&&(yield this.create({type:t,source:r,message:i}).catch(this.error))})}};Ne([G(),we("design:type",Number)],et.prototype,"id",void 0),Ne([W(),we("design:type",W)],et.prototype,"type",void 0),Ne([W(),we("design:type",W)],et.prototype,"source",void 0),Ne([se(),we("design:type",W)],et.prototype,"message",void 0),Ne([J,we("design:type",Date)],et.prototype,"created_at",void 0),et=Ne([ee(Me),te("log"),Ue("4.2.0")],et);let tt=class extends ie{};Ne([W(),we("design:type",W)],tt.prototype,"model",void 0),Ne([W(),we("design:type",W)],tt.prototype,"version",void 0),Ne([J,we("design:type",Date)],tt.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],tt.prototype,"updated_at",void 0),tt=Ne([ee(Me),te("migration"),Ue("4.2.0")],tt);let it=class extends ie{};Ne([W(),we("design:type",W)],it.prototype,"session",void 0),Ne([se(),we("design:type",W)],it.prototype,"json",void 0),Ne([le(),we("design:type",Number)],it.prototype,"expired",void 0),Ne([J,we("design:type",Date)],it.prototype,"created_at",void 0),Ne([Z,we("design:type",Date)],it.prototype,"updated_at",void 0),it=Ne([ee(Me),te("session"),Ue("4.2.0")],it);class rt{static error(e){let t="token";xe.API_BASE_NAME&&(t=`${xe.API_BASE_NAME}.${t}`),et.error(e.message,t,xe.API_CONSOLE_ERROR)}}class st extends rt{static user(e,t){return Ce(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const i=t.hash.encrypt(e),r=yield We.findOne({where:{token:i,state:!0}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield qe.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(i)return i.logout&&(i.logout=null,yield i.save().catch(this.error)),{auth:i,user:r}}return{error:"ACCESS DENIED"}})}}const nt=e=>me(e)?_e(e):void 0,ot={http:nt(xe.API_HTTP_CRT),token:nt(xe.API_TOKEN_CRT)},dt={http:nt(xe.API_HTTP_KEY),token:nt(xe.API_TOKEN_KEY)};class at extends rt{static options(){return{algorithm:"RS256",expiresIn:`${xe.API_TOKEN_LIFETIME}ms`}}static create(e){return Ce(this,void 0,void 0,function*(){if(!dt.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=r(),s=yield qe.create({secret:i,user_id:t}).catch(this.error);if(!s)return{error:"INTERNAL SERVER ERROR"};return{auth:s,token:ve.sign({id:t,secret:i},dt.token,this.options())}})}static destroy(e){return Ce(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static renew(e){return Ce(this,void 0,void 0,function*(){if(!dt.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=this.verify(e,xe.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const s=yield qe.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(s&&!s.logout){s.secret=r(),yield s.save().catch(this.error);return{auth:s,token:ve.sign({id:e,secret:s.secret},dt.token,this.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e){return Ce(this,void 0,void 0,function*(){const{error:t,decode:i}=this.verify(e);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield We.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const e=yield qe.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:i}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!ot.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:ve.verify(e,ot.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class ut extends Re{constructor(){super(),this.all=e=>Ce(this,void 0,void 0,function*(){e=e||i;const t=yield it.findAll({attributes:["session"],where:{expired:{[Se.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>Ce(this,void 0,void 0,function*(){yield it.destroy().catch(i),e&&e()}),this.destroy=(e,t)=>Ce(this,void 0,void 0,function*(){yield it.destroy({where:{session:e}}).catch(i),t&&t()}),this.expired=()=>Ce(this,void 0,void 0,function*(){yield it.destroy({where:{expired:{[Se.lt]:Date.now()}}}).catch(i)}),this.get=(e,t)=>Ce(this,void 0,void 0,function*(){t=t||i;const r=yield it.findOne({where:{session:e,expired:{[Se.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(i),void t(null)}return void t(null,e)}t(null)}),this.length=e=>Ce(this,void 0,void 0,function*(){e&&e(null,(yield it.count().catch(i))||0)}),this.set=(e,t,r)=>Ce(this,void 0,void 0,function*(){r=r||i;const s=Date.now()+xe.API_SESSION_LIFETIME,n=JSON.stringify(t),[o,d]=(yield it.findOrCreate({where:{session:e},defaults:{session:e,json:n,expired:s}}).catch(i))||[];o&&(d||(o.json=n,o.expired=s,yield o.save().catch(i))),r()}),this.loop=s(this.expired,3e4),this.loop.start()}}class pt extends E{constructor(e){super(e,{cert:ot.http,cross:xe.API_HTTP_CROSS,hybrid:xe.API_HTTP_HYBRID,json:{strict:xe.API_BODYPARSER_STRICT,inflate:xe.API_BODYPARSER_INFLATE,limit:xe.API_BODYPARSER_LIMIT,type:xe.API_BODYPARSER_TYPE},key:dt.http,notfound:xe.API_HTTP_NOTFOUND,path:xe.API_HTTP_PATH,port:xe.API_HTTP_PORT,public:xe.API_HTTP_PUBLIC,redirect:xe.API_HTTP_REDIRECT,session:{store:new ut,name:xe.API_SESSION_NAME,secret:xe.API_SESSION_SECRET,cookie:{maxAge:xe.API_SESSION_LIFETIME},genid:r}}),this.hash=new q(xe.API_KEY_HASH)}error(e,t){xe.API_BASE_NAME&&(t=t?`${xe.API_BASE_NAME}.${t}`:xe.API_BASE_NAME),et.error(e.message,t,xe.API_CONSOLE_ERROR)}log(e,t){xe.API_BASE_NAME&&(t=t?`${xe.API_BASE_NAME}.${t}`:xe.API_BASE_NAME),et.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return Ce(this,void 0,void 0,function*(){yield Me.sync(),yield this.migrations(Me),yield n(this.controllers,e=>Ce(this,void 0,void 0,function*(){o(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),xe.API_WEBSOCKET_START&&this.server&&(this._webSocket=new Pe({server:this.server,verifyClient:(e,t)=>t(xe.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>Ce(this,void 0,void 0,function*(){t.url||(t.url="");const i=t.url.length<=1?"":t.url.replace(/\//g,".");let r;e.on("message",s=>Ce(this,void 0,void 0,function*(){if(r)try{const n=JSON.parse(s);this.emit("ws.message"+i,{data:n,message:s,req:t,user:r,ws:e})}catch(n){this.emit("ws.message"+i,{erro:n,message:s,req:t,user:r,ws:e})}else{const{user:n}=yield at.user(s.toString());n&&(r=n,this.emit("ws.connection"+i,{req:t,user:r,ws:e}))}r||e.close()})),e.on("close",()=>{r&&this.emit("ws.close"+i,{user:r,ws:e})}),yield d(2e3),r||e.close()})))})}migrations(e){return Ce(this,void 0,void 0,function*(){const t=[];yield n(Object.keys(e.models),i=>Ce(this,void 0,void 0,function*(){var r;const s=e.models[i],{version:n}=Be.migrations(s);if(!n)return;const[o,d]=null!==(r=yield tt.findOrCreate({where:{model:s.tableName},defaults:{model:s.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];o&&(d||o.version!=n)&&(o.version=n,yield o.save().catch(this.error),t.push(s))})),t.length&&(yield ge(e,t))})}websocket(){return this._webSocket}}var ct,lt,yt;class gt extends De{constructor(){super(...arguments),this[ct]=[]}auth(e,t,i,r,s,n){return Ce(this,void 0,void 0,function*(){var o;t=null!=t?t:r;const[d,a]=null!==(o=null==i?void 0:i.split(" "))&&void 0!==o?o:["",""];if(!(t||a&&d.toLowerCase()==xe.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:u,error:p,user:c}=yield t?st.user(t,n):at.user(a);return p?e.error(p):u&&c?!t&&u.user_agent&&u.user_agent!=s?e.error("INVALID TOKEN"):(e.req.auth=u,e.req.user=c,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",i)})}canDelete(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",i)})}canRead(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",i)})}canUpdate(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",i)})}error(e){let t="controller_base";xe.API_BASE_NAME&&(t=`${xe.API_BASE_NAME}.${t}`),et.error(e.message,t,xe.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,i){return Ce(this,void 0,void 0,function*(){if(i){if((yield this.permissions(i,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return Ce(this,void 0,void 0,function*(){var i;return null!==(i=yield Xe.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Qe,required:!0,include:[{model:Ve,required:!0,where:{state:!0},include:[{model:$e,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==i?i:[]})}session(e,t,r){return Ce(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(i):(r.user_agent=t,r.save(i))),e.next()})}sync(){return Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield n(this[De.PERMISSIONS],i=>Ce(this,void 0,void 0,function*(){const r=`${e}.${i}`,s=a(e.replace(/_/g," ")," ");yield Xe.findOrCreate({where:{route:r},defaults:Object.assign({name:`${s} ${a(i," ")}`,route:r,tag:s},t)})}))})}upload(e,t){t.path||(t.path=xe.API_UPLOAD_TEMP),t.size||(t.size=xe.API_UPLOAD_SIZE),t.field||(t.field=xe.API_UPLOAD_FIELD),T.middleware(e,t)}validation(e,t){return Ce(this,void 0,void 0,function*(){const{error:i,value:r}=yield u.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()})}}ct=De.PERMISSIONS,Ne([be(0,A()),be(1,O(xe.API_KEY_HEADER)),be(2,O(xe.API_TOKEN_HEADER)),be(3,I(xe.API_KEY_HEADER)),be(4,O("user-agent")),be(5,f()),we("design:type",Function),we("design:paramtypes",[P,String,String,String,String,pt]),we("design:returntype",Promise)],gt.prototype,"auth",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],gt.prototype,"canCreate",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],gt.prototype,"canDelete",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],gt.prototype,"canRead",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],gt.prototype,"canUpdate",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],gt.prototype,"permission",null),Ne([be(0,A()),be(1,O("user-agent")),be(2,S()),we("design:type",Function),we("design:paramtypes",[P,String,Object]),we("design:returntype",Promise)],gt.prototype,"session",null),Ne([be(0,A()),be(1,R()),we("design:type",Function),we("design:paramtypes",[P,Object]),we("design:returntype",void 0)],gt.prototype,"upload",null),Ne([be(0,A()),be(1,R()),we("design:type",Function),we("design:paramtypes",[P,Object]),we("design:returntype",Promise)],gt.prototype,"validation",null);let ht=class extends gt{constructor(){super(...arguments),this[lt]=[],this[yt]=["create","read","update","delete"]}attributes(e){if(0==this[gt.ATTRIBUTES].length&&(this[gt.ATTRIBUTES]=Object.keys(this.model().getAttributes())),p(e))return e.length?e.map(e=>c(e)&&-1!=this[gt.ATTRIBUTES].indexOf(e)?e:void 0).filter(c):this[gt.ATTRIBUTES];const{exclude:t,include:i}=e,r=l(i)?this[gt.ATTRIBUTES]:i.map(e=>c(e)&&-1!=this[gt.ATTRIBUTES].indexOf(e)?e:void 0).filter(c),s=null!=t?t:[];return s.length?r.filter(e=>-1==s.indexOf(e)?e:void 0).filter(c):r}create(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,body:i}){const r=yield this.model().create(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign({},t||{}),Fe(e))).catch(this.error);if(r){const t=this.key();return e.prepare(N.OK,{[t]:r.getDataValue(t)}),r}e.error("INTERNAL SERVER ERROR")})}delete(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t}){const i=this.key(),{[i]:r}=e.req.params;if(!r)return e.error("INTERNAL SERVER ERROR"),0;const s=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:r}),individualHooks:!0}),Fe(e))).catch(this.error);return s?(e.success("OK"),s):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";xe.API_BASE_NAME&&(t=`${xe.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?et.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,xe.API_CONSOLE_ERROR):super.error(e)}findAll(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r,advanced:s,attributes:n,limited:o}){var d,a,u;const p=this.scope(r),h=Object.assign({},t||{}),{fields:v,limit:_,offset:m,asc:E,desc:A,search:O,where:I}=e.req.query;if(l(h.limit)){let e=xe.API_MODEL_LIMIT;c(_)&&(e=parseInt(_)||0),e=y(e,-1,xe.API_MODEL_LIMIT_MAX),h.limit=e>0?e:o?xe.API_MODEL_LIMIT:void 0}if(g(h.limit)&&(h.limit=h.limit>0?h.limit:void 0),c(m)){const e=parseInt(m)||0;h.offset=e>0?e:void 0}n=null!=n?n:this.attributes(null!==(d=null==h?void 0:h.attributes)&&void 0!==d?d:[]);const f=e=>n.indexOf(e)>=0,P=[];c(v)&&P.push(...v.split(";").filter(f)),P.length&&(h.attributes=P);const R=[];if(c(E)&&E.length&&R.push(...E.split(";").filter(f).map(e=>[e,"ASC"])),c(A)&&A.length&&R.push(...A.split(";").filter(f).map(e=>[e,"DESC"])),R.length&&(h.order=R),h.where=Object.assign({},h.where||{}),c(I)&&(null==s||s)){const t=he.parse(n,I);if(!l(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};h.where=Object.assign(Object.assign({},h.where),null!==(a=t.value)&&void 0!==a?a:{})}else{const e=[];n.forEach(t=>{c(O)&&O.length&&e.push({[t]:{[Se.like]:`%${O}%`}})}),e.length&&(h.where=Object.assign(Object.assign({},h.where),{[Se.or]:[...e]}))}const S=p.count(Object.assign(Object.assign({},h),{distinct:!!h.include,col:this[gt.ATTRIBUTES].length?this[gt.ATTRIBUTES][0]:void 0})).catch(this.error),T=p.findAll(h).catch(this.error);yield Promise.allSettled([S,T]);const D=null!==(u=yield S)&&void 0!==u?u:0;let b=yield T;const w={count:D};return b?(b=i?yield i(b):b,(g(null==t?void 0:t.limit)||0==D)&&(w.count=b.length),e.prepare(N.OK,Object.assign(Object.assign({},w),{records:b})),Object.assign(Object.assign({},w),{records:b})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},w),{records:[]}))})}findOne(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r}){const s=this.key(),{[s]:n}=e.req.params,o=yield this.scope(r).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n})})).catch(this.error);return o?(e.prepare(N.OK,i?yield i(o):o.toJSON()),o):null===o?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield n(this[gt.PERMISSIONS],i=>Ce(this,void 0,void 0,function*(){const r=`${e}.${i}`,s=a(e.replace(/_/g," ")," ");yield Xe.findOrCreate({where:{route:r},defaults:Object.assign({name:`${s} ${a(i," ")}`,route:r,tag:s},t)})}))})}update(e){return Ce(this,arguments,void 0,function*({ctx:e,options:t,body:i}){var r;const s=this.key(),{[s]:n}=e.req.params,[o]=null!==(r=yield this.model().update(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[s]:n}),individualHooks:!0}),Fe(e))).catch(this.error))&&void 0!==r?r:[];return o?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};lt=gt.ATTRIBUTES,yt=gt.PERMISSIONS,ht=Ne([D(gt)],ht);let vt=class extends ht{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return Ce(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return Ce(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return Ce(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return Ce(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return Ce(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}};Ne([b(),w("auth"),w("canCreate"),w("validationCreate"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"add",null),Ne([C(),w("auth"),w("canRead"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"all",null),Ne([x("/:id"),w("auth"),w("canDelete"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"del",null),Ne([C("/:id"),w("auth"),w("canRead"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"get",null),Ne([F("/:id"),w("auth"),w("canUpdate"),w("validationUpdate"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"set",null),Ne([be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"validationCreate",null),Ne([be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],vt.prototype,"validationUpdate",null),vt=Ne([D(ht)],vt);let _t=class extends ht{model(){return ze}all(e,t,i){return Ce(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},limited:!0})})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};Ne([C(),w("auth"),w("canRead"),be(0,A()),be(1,I("type")),be(2,I("table")),we("design:type",Function),we("design:paramtypes",[P,String,String]),we("design:returntype",Promise)],_t.prototype,"all",null),Ne([C("/:id"),w("auth"),w("canRead"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],_t.prototype,"get",null),_t=Ne([j("/audits"),D(ht)],_t);let mt=class extends gt{login(e,t,i,r,s){return Ce(this,void 0,void 0,function*(){var n;yield d(xe.API_SLEEP_AUTH);const o=yield We.scope("password").findOne({where:{[Se.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",!o||o.password!=Y(r))return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const a=yield Ye.findOne({where:{state:!0,user_id:o.id}}).catch(this.error);if(a)return e.error("ACTIVATION REQUIRED"),s.emit("auth.activation",{ctx:e,register:a,user:o}),void this.emit("auth.activation",{ctx:e,register:a,user:o});if(!o.state)return e.notFound("INVALID USERNAME OR PASSWORD"),s.emit("auth.failure",{ctx:e,user:o}),void this.emit("auth.failure",{ctx:e,user:o});const{auth:u,error:p,token:c}=yield at.create(o);return p?(e.error(p),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&c?(u.user_agent=t,yield u.save().catch(this.error),e.json({token:c}),s.emit("auth.login",{auth:u,ctx:e,user:o}),void this.emit("auth.login",{auth:u,ctx:e,user:o})):(e.error("INTERNAL SERVER ERROR"),s.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))})}logout(e,t,i,r){return Ce(this,void 0,void 0,function*(){if(yield at.destroy(t))return e.success("OK"),r.emit("auth.logout",{auth:t,ctx:e,user:i}),void this.emit("auth.logout",{auth:t,ctx:e,user:i});e.unauthorized("ACCESS DENIED")})}renew(e,t,i,r){return Ce(this,void 0,void 0,function*(){const{auth:s,error:n,token:o}=yield at.renew(i);return n?e.error(n):s?(s.user_agent=t,yield s.save().catch(this.error),e.json({token:o}),r.emit("auth.renew",{auth:s,ctx:e}),void this.emit("auth.renew",{auth:s,ctx:e})):e.error("INTERNAL SERVER ERROR")})}user(e,t){return Ce(this,void 0,void 0,function*(){const i=yield this.permissions(t);if(!i)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},h(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map(e=>e.route)}))})}};var Et;Ne([b("/login"),w("validation",{username:u.string().min(3).required(),password:u.string().min(5).required()}),be(0,A()),be(1,O("user-agent")),be(2,k("username")),be(3,k("password")),be(4,f()),we("design:type",Function),we("design:paramtypes",[P,String,String,String,pt]),we("design:returntype",Promise)],mt.prototype,"login",null),Ne([C("/logout"),w("auth"),be(0,A()),be(1,ke()),be(2,Le()),be(3,f()),we("design:type",Function),we("design:paramtypes",[P,qe,We,pt]),we("design:returntype",Promise)],mt.prototype,"logout",null),Ne([b("/renew"),w("validation",{token:u.string().required()}),be(0,A()),be(1,O("user-agent")),be(2,k("token")),be(3,f()),we("design:type",Function),we("design:paramtypes",[P,String,String,pt]),we("design:returntype",Promise)],mt.prototype,"renew",null),Ne([C(),w("auth"),be(0,A()),be(1,Le()),we("design:type",Function),we("design:paramtypes",[P,We]),we("design:returntype",Promise)],mt.prototype,"user",null),mt=Ne([j("/auth"),D(gt)],mt);let At=class extends gt{constructor(){super(...arguments),this[Et]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return xe.API_HTTP_PUBLIC||"./"}files(e){return Ce(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=Te(this.directory(),t);if(!me(i)||!Ee(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=Ae(i),r=r.map(e=>this.info(Te(i,e))),r=r.filter(v),Object.assign(Object.assign({},this.info(i)),{files:r})})}access(e,t,i){return Ce(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,i)})}info(e){if(!me(e))return null;const t=Ee(e),i=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return Ce(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=a(e.replace(/_/g," ")," "),i={description:"",state:!0};yield n(this[gt.PERMISSIONS],r=>Ce(this,void 0,void 0,function*(){const s=`${e}.${r}`;yield Xe.findOrCreate({where:{route:s},defaults:Object.assign({name:`${t} ${a(r," ")}`,route:s,tag:t},i)})}))})}};Et=gt.PERMISSIONS,Ne([C("/path"),C("/path/*path"),w("auth"),w("access","list"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],At.prototype,"files",null),Ne([be(0,A()),be(1,R()),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],At.prototype,"access",null),At=Ne([j("/files"),D(gt)],At);let Ot=class extends gt{check(e,t){return Ce(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=_(),yield i.save(),e.json({token:i.token})})}forgot(e,t,i){return Ce(this,void 0,void 0,function*(){yield d(xe.API_SLEEP_FORGOT);const r=t,s=yield We.findOne({where:{[Se.or]:[{email:r},{username:t}]}}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=_(),o=Date.now()+6e4*xe.API_TOKEN_FORGOT,a=yield Ze.create({token:n,timestamp:o,state:!0,user_id:s.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:s}),this.emit("forgot.send",{ctx:e,forgot:a,user:s})})}reset(e,t,i,r){return Ce(this,void 0,void 0,function*(){const s=yield this.find(t);if(!s)return e.notFound("RECORD NOT FOUND");s.state=!1,yield s.save().catch(this.error),s.user.password=Y(i),yield s.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:s.user}),this.emit("forgot.reset",{ctx:e,user:s.user})})}find(e){return Ce(this,void 0,void 0,function*(){return yield Ze.findOne({where:{token:e,state:!0},include:[{model:We,required:!0}]}).catch(this.error)})}};Ne([C("/check"),w("validation",{token:u.string().required()}),be(0,A()),be(1,k("token")),we("design:type",Function),we("design:paramtypes",[P,String]),we("design:returntype",Promise)],Ot.prototype,"check",null),Ne([b(),w("validation",{username:u.string().min(4).required()}),be(0,A()),be(1,k("username")),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,String,pt]),we("design:returntype",Promise)],Ot.prototype,"forgot",null),Ne([b("/reset"),w("validation",{token:u.string().required(),password:u.string().min(5).required()}),be(0,A()),be(1,k("token")),be(2,k("password")),be(3,f()),we("design:type",Function),we("design:paramtypes",[P,String,String,pt]),we("design:returntype",Promise)],Ot.prototype,"reset",null),Ot=Ne([j("/forgot"),D(gt)],Ot);let It=class extends vt{constructor(){super(...arguments),this.schemaCreate={name:u.string().required(),description:u.string().empty(""),state:u.boolean().parse().required()},this.schemaUpdate={name:u.string().empty(),description:u.string().empty(),state:u.boolean().parse().empty()}}model(){return Ve}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};It=Ne([j("/groups"),D(vt)],It);let ft=class extends ht{model(){return Qe}all(e,t){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:Xe,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return Ce(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return Ce(this,void 0,void 0,function*(){const s=yield Ve.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");const n=s.id;if(yield Qe.destroy(Object.assign({where:{group_id:n},individualHooks:!0},r)),i){let e=0;yield d(1e3);for(let t=0;t<i.length;t++)e=yield Xe.count({where:{id:i[t]}}),e&&(yield Qe.create({group_id:n,permission_id:i[t]},Object.assign({},r)))}e.success("OK")})}};var Pt;Ne([C("/:id/permissions"),w("auth"),w("canRead","groups"),be(0,A()),be(1,L("id")),we("design:type",Function),we("design:paramtypes",[P,String]),we("design:returntype",Promise)],ft.prototype,"all",null),Ne([C("/permissions"),w("auth"),w("canRead","users"),be(0,A()),be(1,Le()),we("design:type",Function),we("design:paramtypes",[P,We]),we("design:returntype",Promise)],ft.prototype,"me",null),Ne([F("/:id/permissions"),w("auth"),w("canUpdate","groups"),w("validation",{permissions:u.array(u.number().parse())}),be(0,A()),be(1,L("id")),be(2,k("permissions")),be(3,je()),we("design:type",Function),we("design:paramtypes",[P,String,Array,Object]),we("design:returntype",Promise)],ft.prototype,"set",null),ft=Ne([j("/groups"),D(ht)],ft);let Rt=class extends ht{constructor(){super(...arguments),this[Pt]=["read"]}model(){return et}all(e,t,i){return Ce(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this.findAll({ctx:e,options:{where:r,order:[["created_at","DESC"]]},limited:!0})})}};Pt=ht.PERMISSIONS,Ne([C(),w("auth"),w("canRead"),be(0,A()),be(1,I("type")),be(2,I("source")),we("design:type",Function),we("design:paramtypes",[P,String,String]),we("design:returntype",Promise)],Rt.prototype,"all",null),Rt=Ne([j("/logs"),D(ht)],Rt);let St=class extends vt{constructor(){super(...arguments),this.schemaCreate={name:u.string().required(),route:u.string().required(),tag:u.string().required(),description:u.string().empty(""),state:u.boolean().parse().required()},this.schemaUpdate={name:u.string().empty(),route:u.string().empty(),tag:u.string().empty(),description:u.string().empty(),state:u.boolean().parse().empty()}}model(){return Xe}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};St=Ne([j("/permissions"),D(vt)],St);let Tt=class extends gt{register(e,t,i){return Ce(this,void 0,void 0,function*(){yield d(xe.API_SLEEP_REGISTRY);const{name:r,date:s,email:n,username:o,password:a,confirm:u}=t,p=o||n,c=Y(a);if(yield We.count({where:{[Se.or]:[{email:n},{username:p}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(c!=Y(u))return e.error("INVALID PASSWORD");const l=yield We.create({name:r,email:n,username:p,password:c,avatar:"",date:s,description:"",state:!1}).catch(this.error);if(!l)return e.error("INTERNAL SERVER ERROR");const y=yield Ye.create({token:yield this.getId(),user_id:l.id,state:!0}).catch(this.error);if(!y)return yield l.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),i.emit("register.user",{ctx:e,register:y,user:l}),this.emit("register.user",{ctx:e,register:y,user:l})})}confirm(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield Ye.findOne({where:{token:t,state:!0},include:[{model:We,required:!0}]}).catch(this.error);if(!r)return e.notFound("RECORD NOT FOUND");r.state=!1,yield r.save().catch(this.error),r.user.state=!0,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return Ce(this,void 0,void 0,function*(){const r=t,s=yield Ye.findOne({where:{state:!0},include:[{model:We,required:!0,where:{[Se.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");e.success("OK"),i.emit("register.send",{ctx:e,register:s,user:s.user}),this.emit("register.send",{ctx:e,register:s,user:s.user})})}getId(){return Ce(this,void 0,void 0,function*(){const e=r();return(yield Ye.count({where:{token:e}}))?this.getId():e})}};Ne([b(),w("validation",{name:u.string().required(),date:u.date().required(),email:u.string().email().required(),username:u.string().min(4).empty(),password:u.string().min(5).required(),confirm:u.string().min(5).required()}),be(0,A()),be(1,k()),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,Object,pt]),we("design:returntype",Promise)],Tt.prototype,"register",null),Ne([b("/confirm"),w("validation",{token:u.string().required()}),be(0,A()),be(1,k("token")),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,String,pt]),we("design:returntype",Promise)],Tt.prototype,"confirm",null),Ne([b("/send"),w("validation",{username:u.string().min(4).required()}),be(0,A()),be(1,k("username")),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,String,pt]),we("design:returntype",Promise)],Tt.prototype,"send",null),Tt=Ne([j("/register"),D(gt)],Tt);let Dt=class extends gt{setup(e,t){return Ce(this,void 0,void 0,function*(){var i;if(yield We.count())return e.success("OK");const r=_(),s=yield We.create({name:"Admin",email:"admin@localhost",username:"admin",password:Y("admin"+r),salt:r,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),o=yield Ve.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},t));yield $e.create({user_id:s.id,group_id:o.id},Object.assign({},t));const d=null!==(i=yield Xe.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield n(d,e=>Ce(this,void 0,void 0,function*(){yield Qe.create({group_id:o.id,permission_id:e.id},Object.assign({},t))})),e.success("OK")})}};Ne([C(),be(0,A()),be(1,je()),we("design:type",Function),we("design:paramtypes",[P,Object]),we("design:returntype",Promise)],Dt.prototype,"setup",null),Dt=Ne([j("/setup"),D(gt)],Dt);let Nt=class extends ht{model(){return We}constructor(){super(),this.path=xe.API_HTTP_PUBLIC+"/avatar",xe.API_HTTP_PUBLIC&&me(xe.API_HTTP_PUBLIC)&&!me(this.path)&&Oe(this.path)}avatar(e,t,i,r){return Ce(this,void 0,void 0,function*(){if(t.length){const s=t[0].filename||"";if(s){const t=this.path+"/"+i.avatar;if(me(t)&&Ie(t).isFile()&&fe(t),i.avatar=s,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,i){return Ce(this,void 0,void 0,function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&me(r)&&fe(r),e.success("OK")})}password(e,t,i,r,s){return Ce(this,void 0,void 0,function*(){var n;if(xe.API_USER_HISTORY){if(yield Ge.count({where:{password:Y(i+r.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const o=yield this.scope("password").findOne({where:{id:r.id,state:!0}}).catch(this.error);return t+=null!==(n=null==o?void 0:o.salt)&&void 0!==n?n:"",o&&o.password==Y(t)?(o.salt=_(),o.password=Y(i+o.salt),(yield o.save(Object.assign({},s)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")})}token(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")})}token_del(e,t,i){return Ce(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(Object.assign({},i)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")})}token_get(e,t,i){return Ce(this,void 0,void 0,function*(){const r=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")})}token_renew(e,t,i,r){return Ce(this,void 0,void 0,function*(){const s=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(s){const t=yield this.token_new();return s.token=r.hash.encrypt(t),yield s.save(Object.assign({},i)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")})}token_new(){return Ce(this,void 0,void 0,function*(){var e;const t=r();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e,t){return Ce(this,void 0,void 0,function*(){const i=_(),r=yield this.create({ctx:e,body:{password:Y(t+i),salt:i}});xe.API_USER_HISTORY&&r&&(yield Ge.create({password:Y(t+r.id),user_id:r.id}))})}all(e){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})})}del(e,t,i){return Ce(this,void 0,void 0,function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return Ce(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e,t,i){return Ce(this,void 0,void 0,function*(){if(xe.API_USER_HISTORY&&i){const r=Y(i+t);if(yield Ge.count({where:{password:r}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield Ge.create({password:r,user_id:t}).catch(this.error)}const r=i?_():"";yield this.update({ctx:e,body:i?{password:Y(i+r),salt:r}:{}})})}};Ne([b("/avatar"),w("auth"),w("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),be(0,A()),be(1,U()),be(2,Le()),be(3,je()),we("design:type",Function),we("design:paramtypes",[P,Array,We,Object]),we("design:returntype",Promise)],Nt.prototype,"avatar",null),Ne([x("/avatar"),w("auth"),be(0,A()),be(1,Le()),be(2,je()),we("design:type",Function),we("design:paramtypes",[P,We,Object]),we("design:returntype",Promise)],Nt.prototype,"avatar_del",null),Ne([b("/password"),w("auth"),w("validation",{oldPassword:u.string().min(5).required(),newPassword:u.string().min(5).required(),confirmPassword:u.string().equal(u.ref("newPassword"))}),be(0,A()),be(1,k("oldPassword")),be(2,k("newPassword")),be(3,Le()),be(4,je()),we("design:type",Function),we("design:paramtypes",[P,String,String,We,Object]),we("design:returntype",Promise)],Nt.prototype,"password",null),Ne([C("/token"),w("auth"),be(0,A()),be(1,Le()),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,We,pt]),we("design:returntype",Promise)],Nt.prototype,"token",null),Ne([x("/token/:id"),w("auth"),w("canDelete"),be(0,A()),be(1,L("id")),be(2,je()),we("design:type",Function),we("design:paramtypes",[P,String,Object]),we("design:returntype",Promise)],Nt.prototype,"token_del",null),Ne([C("/token/:id"),w("auth"),w("canCreate"),be(0,A()),be(1,L("id")),be(2,f()),we("design:type",Function),we("design:paramtypes",[P,String,pt]),we("design:returntype",Promise)],Nt.prototype,"token_get",null),Ne([C("/token/renew/:id"),w("auth"),w("canUpdate"),be(0,A()),be(1,L("id")),be(2,je()),be(3,f()),we("design:type",Function),we("design:paramtypes",[P,String,Object,pt]),we("design:returntype",Promise)],Nt.prototype,"token_renew",null),Ne([b(),w("auth"),w("canCreate"),w("validation",{name:u.string().required(),email:u.string().email().required(),username:u.string().min(4).required(),password:u.string().min(5).required(),description:u.string().empty(""),state:u.boolean().parse().required()}),be(0,A()),be(1,k("password")),we("design:type",Function),we("design:paramtypes",[P,String]),we("design:returntype",Promise)],Nt.prototype,"add",null),Ne([C(),w("auth"),w("canRead"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],Nt.prototype,"all",null),Ne([x("/:id"),w("auth"),w("canDelete"),be(0,A()),be(1,L("id")),be(2,Le()),we("design:type",Function),we("design:paramtypes",[P,String,We]),we("design:returntype",Promise)],Nt.prototype,"del",null),Ne([C("/:id"),w("auth"),w("canRead"),be(0,A()),we("design:type",Function),we("design:paramtypes",[P]),we("design:returntype",Promise)],Nt.prototype,"get",null),Ne([F("/:id"),w("auth"),w("canUpdate"),w("validation",{name:u.string().empty(),email:u.string().email().empty(),username:u.string().min(4).empty(),password:u.string().min(5).empty().filter(""),description:u.string().empty(),state:u.boolean().parse().empty()}),be(0,A()),be(1,L("id")),be(2,k("password")),we("design:type",Function),we("design:paramtypes",[P,String,String]),we("design:returntype",Promise)],Nt.prototype,"set",null),Nt=Ne([j("/users"),D(ht),we("design:paramtypes",[])],Nt);let bt=class extends ht{model(){return $e}all(e,t){return Ce(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:Ve,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return Ce(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return Ce(this,void 0,void 0,function*(){const s=yield We.findByPk(t,{attributes:["id"]}).catch(this.error);if(!s)return e.notFound("RECORD NOT FOUND");if(yield $e.destroy(Object.assign({where:{user_id:s.id},individualHooks:!0},r)),i){let e=0;yield d(1e3);for(let t=0;t<i.length;t++)e=yield Ve.count({where:{id:i[t]}}),e&&(yield $e.create({user_id:s.id,group_id:i[t]},Object.assign({},r)))}e.success("OK")})}};Ne([C("/:id/groups"),w("auth"),w("canRead","users"),be(0,A()),be(1,L("id")),we("design:type",Function),we("design:paramtypes",[P,String]),we("design:returntype",Promise)],bt.prototype,"all",null),Ne([C("/groups"),w("auth"),w("canRead","users"),be(0,A()),be(1,Le()),we("design:type",Function),we("design:paramtypes",[P,We]),we("design:returntype",Promise)],bt.prototype,"me",null),Ne([F("/:id/groups"),w("auth"),w("canUpdate","users"),w("validation",{groups:u.array(u.number().parse())}),be(0,A()),be(1,L("id")),be(2,k("groups")),be(3,je()),we("design:type",Function),we("design:paramtypes",[P,String,Array,Object]),we("design:returntype",Promise)],bt.prototype,"set",null),bt=Ne([j("/users"),D(ht)],bt);export{pt as Application,ze as Audit,_t as AuditsController,qe as Auth,rt as AuthBase,mt as AuthController,st as AuthKey,at as AuthToken,Je as Config,De as Controller,gt as ControllerBase,vt as ControllerCrud,ht as ControllerModel,xe as Env,At as FilesController,Ze as Forgot,Ot as ForgotController,Ve as Group,Qe as GroupPermission,It as GroupsController,ft as GroupsPermissionsController,et as Log,Rt as LogsController,Be as Metadata,Ue as Migrate,tt as Migration,Xe as Permission,St as PermissionsController,Ye as Register,Tt as RegisterController,je as ReqAudit,ke as ReqAuth,Le as ReqUser,it as Session,Dt as SetupController,ut as Store,We as User,$e as UserGroup,Ge as UserHistory,Nt as UsersController,bt as UsersGroupsController,Fe as audit,ot as crt,Me as database,Ke as hooks,dt as key};
|
|
7
|
+
import{EventEmitter as e,isObject as t,noop as i,uuidv7 as r,loop as n,forEachSeries as o,isFunction as s,sleep as d,upperCamelCase as a,Validation as u,isArray as l,isString as p,isUndefined as c,clamp as g,isNumber as y,denied as v,isDef as h,uniqueID as E}from"@andrewcaires/utils.js";import{parameterFactory as A,Application as _,Ctx as m,Headers as O,Query as S,App as f,Context as I,Argument as P,Session as R,Upload as T,Extends as D,Status as N,Post as C,Middleware as b,Get as w,Delete as B,Put as x,Controller as F,Body as k,Params as U,Files as j}from"@andrewcaires/express";import{Env as L,LogColor as K,Log as M,Hash as H,sha256 as q}from"@andrewcaires/node";import{config as Y}from"dotenv";import{Sequelize as V,Column as $,BelongsTo as G,Database as W,ModelName as z,Version as J,Model as Z,HasMany as X,Hooks as Q,DefaultScope as ee,Scopes as te,Unique as ie,Op as re,Where as ne}from"@andrewcaires/sequelize";import oe from"jsonwebtoken";import{readFileSync as se,existsSync as de,statSync as ae,readdirSync as ue,mkdirSync as le,lstatSync as pe,rmSync as ce}from"fs";import{WebSocketServer as ge}from"ws";import{Store as ye}from"express-session";import{join as ve}from"path";class Controller extends e{}function he(e,t,i,r){var n,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var d=e.length-1;d>=0;d--)(n=e[d])&&(s=(o<3?n(s):o>3?n(t,i,s):n(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s}function Ee(e,t){return function(i,r){t(i,r,e)}}function Ae(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function _e(e,t,i,r){return new(i||(i=Promise))(function(n,o){function s(e){try{a(r.next(e))}catch(e){o(e)}}function d(e){try{a(r.throw(e))}catch(e){o(e)}}function a(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,d)}a((r=r.apply(e,t||[])).next())})}Controller.ATTRIBUTES=Symbol("ATTRIBUTES"),Controller.PERMISSIONS=Symbol("PERMISSIONS"),"function"==typeof SuppressedError&&SuppressedError,Y({quiet:!0});class Env extends L{}Env.API_BASE_NAME=Env.getString("API_BASE_NAME",""),Env.API_BODYPARSER_STRICT=Env.getBool("API_BODYPARSER_STRICT",!0),Env.API_BODYPARSER_INFLATE=Env.getBool("API_BODYPARSER_INFLATE",!0),Env.API_BODYPARSER_LIMIT=Env.getString("API_BODYPARSER_LIMIT","10mb"),Env.API_BODYPARSER_TYPE=Env.getString("API_BODYPARSER_TYPE","json"),Env.API_CONSOLE_ERROR=Env.getBool("API_CONSOLE_ERROR",!1),Env.API_DATABASE_URL=Env.getString("API_DATABASE_URL",""),Env.API_DATABASE_LOG=Env.getBool("API_DATABASE_LOG",!1),Env.API_DATABASE_AUDIT=Env.getBool("API_DATABASE_AUDIT",!0),Env.API_DATABASE_PREFIX=Env.getString("API_DATABASE_PREFIX",""),Env.API_DATABASE_TIMEZONE=Env.getString("API_DATABASE_TIMEZONE","+00:00"),Env.API_HTTP_CRT=Env.getString("API_HTTP_CRT",""),Env.API_HTTP_KEY=Env.getString("API_HTTP_KEY",""),Env.API_HTTP_PORT=Env.getInt("API_HTTP_PORT",3e3),Env.API_HTTP_PUBLIC=Env.getString("API_HTTP_PUBLIC",""),Env.API_HTTP_CROSS=Env.getBool("API_HTTP_CROSS",!1),Env.API_HTTP_HYBRID=Env.getBool("API_HTTP_HYBRID",!1),Env.API_HTTP_NOTFOUND=Env.getString("API_HTTP_NOTFOUND",""),Env.API_HTTP_PATH=Env.getString("API_HTTP_PATH","/api"),Env.API_HTTP_REDIRECT=Env.getString("API_HTTP_REDIRECT",""),Env.API_KEY_HASH=Env.getString("API_KEY_HASH",""),Env.API_KEY_HEADER=Env.getString("API_KEY_HEADER","x-api-key"),Env.API_MODEL_LIMIT=Env.getInt("API_MODEL_LIMIT",10),Env.API_MODEL_LIMIT_MAX=Env.getInt("API_MODEL_LIMIT_MAX",500),Env.API_SLEEP_AUTH=Env.getMs("API_SLEEP_AUTH","2s"),Env.API_SLEEP_FORGOT=Env.getMs("API_SLEEP_FORGOT","5s"),Env.API_SLEEP_REGISTRY=Env.getMs("API_SLEEP_REGISTRY","5s"),Env.API_SESSION_NAME=Env.getString("API_SESSION_NAME","session.id"),Env.API_SESSION_LIFETIME=Env.getMs("API_SESSION_LIFETIME","1d"),Env.API_SESSION_SECRET=Env.getString("API_SESSION_SECRET","yoursecret"),Env.API_TOKEN_CRT=Env.getString("API_TOKEN_CRT",""),Env.API_TOKEN_KEY=Env.getString("API_TOKEN_KEY",""),Env.API_TOKEN_FORGOT=Env.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_HEADER=Env.getString("API_TOKEN_HEADER","authorization"),Env.API_TOKEN_HEADER_KEY=Env.getString("API_TOKEN_HEADER","bearer"),Env.API_TOKEN_LIFETIME=Env.getMs("API_TOKEN_LIFETIME","1d"),Env.API_TOKEN_RENEW=Env.getMs("API_TOKEN_RENEW","1d"),Env.API_UPLOAD_COUNT=Env.getInt("API_UPLOAD_COUNT",1),Env.API_UPLOAD_FIELD=Env.getString("API_UPLOAD_FIELD","upload"),Env.API_UPLOAD_SIZE=Env.getInt("API_UPLOAD_SIZE",2),Env.API_UPLOAD_TEMP=Env.getString("API_UPLOAD_TEMP","./temp"),Env.API_USER_HISTORY=Env.getBool("API_USER_HISTORY",!0),Env.API_WEBSOCKET_START=Env.getBool("API_WEBSOCKET_START",!1);const me=e=>{var t,i,r,n,o,s,d,a,u;return{audit_client:null!==(t=e.getIp())&&void 0!==t?t:"0.0.0.0",audit_href:(null===(i=null==e?void 0:e.req)||void 0===i?void 0:i.protocol)+"://"+(null===(r=null==e?void 0:e.req)||void 0===r?void 0:r.get("host"))+(null===(n=null==e?void 0:e.req)||void 0===n?void 0:n.originalUrl),audit_user_agent:null!==(s=null===(o=e.req)||void 0===o?void 0:o.headers["user-agent"])&&void 0!==s?s:"",audit_user_id:null!==(u=null===(a=null===(d=null==e?void 0:e.req)||void 0===d?void 0:d.user)||void 0===a?void 0:a.id)&&void 0!==u?u:null}},Oe=A(({ctx:e})=>me(e)),Se=A(({ctx:e})=>e.req.auth),fe=A(({ctx:e})=>e.req.user),Ie=new V(Env.API_DATABASE_URL,{logging:Env.API_DATABASE_LOG,prefix:Env.API_DATABASE_PREFIX,timezone:Env.API_DATABASE_TIMEZONE}),Pe=(e,t,i)=>{var r,n,o,s,d;return{type:e,model:null!==(r=null==t?void 0:t.getTableName())&&void 0!==r?r:null,client:null!==(n=null==i?void 0:i.audit_client)&&void 0!==n?n:null,href:null!==(o=null==i?void 0:i.audit_href)&&void 0!==o?o:null,user_agent:null!==(s=null==i?void 0:i.audit_user_agent)&&void 0!==s?s:null,user_id:null!==(d=null==i?void 0:i.audit_user_id)&&void 0!==d?d:null,state:!0}},Re={afterCreate:(e,r)=>_e(void 0,void 0,void 0,function*(){var n;if(!Env.API_DATABASE_AUDIT)return;const o=t(e)?e.constructor:null,s=null!==(n=null==o?void 0:o.primaryKeyAttribute)&&void 0!==n?n:null;yield Be.create(Object.assign(Object.assign({},Pe("CREATE",o,r)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i)}),afterUpdate:(e,r)=>_e(void 0,void 0,void 0,function*(){var n;if(!Env.API_DATABASE_AUDIT)return;const o=t(e)?e.constructor:null,s=null!==(n=null==o?void 0:o.primaryKeyAttribute)&&void 0!==n?n:null,d={},a=e.changed();a&&a.forEach(t=>d[t]=e.getDataValue(t)),yield Be.create(Object.assign(Object.assign({},Pe("UPDATE",o,r)),{record:s?e.getDataValue(s):null,data:d,previously:e.previous()})).catch(i)}),afterDestroy:(e,r)=>_e(void 0,void 0,void 0,function*(){var n;if(!Env.API_DATABASE_AUDIT)return;const o=t(e)?e.constructor:null,s=null!==(n=null==o?void 0:o.primaryKeyAttribute)&&void 0!==n?n:null;yield Be.create(Object.assign(Object.assign({},Pe("DELETE",o,r)),{record:s?e.getDataValue(s):null,data:e.toJSON()})).catch(i)})};let Te=class Auth extends Z{};he([$.Id(),Ae("design:type",Number)],Te.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],Te.prototype,"secret",void 0),he([$.FullDate(),Ae("design:type",Object)],Te.prototype,"logout",void 0),he([$.String(),Ae("design:type",String)],Te.prototype,"user_agent",void 0),he([$.CreatedAt,Ae("design:type",Date)],Te.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Te.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],Te.prototype,"deleted_at",void 0),he([G(()=>we),Ae("design:type",Number)],Te.prototype,"user_id",void 0),Te=he([W(Ie),z("auth"),J("4.2.0")],Te);let De=class Register extends Z{};he([$.Id(),Ae("design:type",Number)],De.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],De.prototype,"token",void 0),he([$.Boolean(),Ae("design:type",Boolean)],De.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],De.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],De.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],De.prototype,"deleted_at",void 0),he([G(()=>we),Ae("design:type",Number)],De.prototype,"user_id",void 0),De=he([W(Ie),z("register"),J("4.2.0")],De);let Ne=class Group extends Z{};he([$.Id(),Ae("design:type",Number)],Ne.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],Ne.prototype,"name",void 0),he([$.Text(),Ae("design:type",String)],Ne.prototype,"description",void 0),he([$.Boolean(),Ae("design:type",Boolean)],Ne.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],Ne.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Ne.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],Ne.prototype,"deleted_at",void 0),he([X(()=>Ce,"group_id"),Ae("design:type",Array)],Ne.prototype,"groups_routes",void 0),he([X(()=>Ce,"group_id"),Ae("design:type",Array)],Ne.prototype,"users_groups",void 0),Ne=he([W(Ie),z("group"),Q(Re),J("4.2.0")],Ne);let Ce=class UserGroup extends Z{};he([$.CreatedAt,Ae("design:type",Date)],Ce.prototype,"created_at",void 0),he([G(()=>Ne),Ae("design:type",Number)],Ce.prototype,"group_id",void 0),he([G(()=>we),Ae("design:type",Number)],Ce.prototype,"user_id",void 0),Ce=he([W(Ie),z("users_groups"),Q(Re),J("4.2.0")],Ce);let be=class UserHistory extends Z{};he([$.String(),Ae("design:type",String)],be.prototype,"password",void 0),he([$.CreatedAt,Ae("design:type",Date)],be.prototype,"created_at",void 0),he([G(()=>we),Ae("design:type",Number)],be.prototype,"user_id",void 0),be=he([W(Ie),z("users_histories"),J("4.2.0")],be);let we=class User extends Z{};he([$.Id(),Ae("design:type",Number)],we.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"name",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"email",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"username",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"password",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"salt",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"token",void 0),he([$.String(),Ae("design:type",String)],we.prototype,"avatar",void 0),he([$.DateOnly(),Ae("design:type",String)],we.prototype,"date",void 0),he([$.Text(),Ae("design:type",String)],we.prototype,"description",void 0),he([$.Boolean(),Ae("design:type",Boolean)],we.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],we.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],we.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],we.prototype,"deleted_at",void 0),he([X(()=>Be,"user_id"),Ae("design:type",Array)],we.prototype,"audits",void 0),he([X(()=>Te,"user_id"),Ae("design:type",Array)],we.prototype,"auths",void 0),he([X(()=>De,"user_id"),Ae("design:type",Array)],we.prototype,"registers",void 0),he([X(()=>Ce,"user_id"),Ae("design:type",Array)],we.prototype,"users_groups",void 0),he([X(()=>be,"user_id"),Ae("design:type",Array)],we.prototype,"users_histories",void 0),we=he([W(Ie),z("user"),ee({attributes:{exclude:["password","salt","token"]}}),te({password:{attributes:{exclude:["token"]}},token:{attributes:{exclude:["password","salt"]}}}),Q(Re),J("4.2.0")],we);let Be=class Audit extends Z{};he([$.Id(),Ae("design:type",Number)],Be.prototype,"id",void 0),he([$.Enum("CREATE","DELETE","UPDATE"),Ae("design:type",String)],Be.prototype,"type",void 0),he([$.String(),Ae("design:type",String)],Be.prototype,"model",void 0),he([$.String(),Ae("design:type",String)],Be.prototype,"record",void 0),he([$.Json(),Ae("design:type",Object)],Be.prototype,"data",void 0),he([$.Json(),Ae("design:type",Object)],Be.prototype,"previously",void 0),he([$.String(),Ae("design:type",String)],Be.prototype,"client",void 0),he([$.Text(),Ae("design:type",String)],Be.prototype,"href",void 0),he([$.String(),Ae("design:type",String)],Be.prototype,"user_agent",void 0),he([$.Boolean(),Ae("design:type",Boolean)],Be.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],Be.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Be.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],Be.prototype,"deleted_at",void 0),he([G(()=>we),Ae("design:type",Number)],Be.prototype,"user_id",void 0),Be=he([W(Ie),z("audit"),J("4.2.0")],Be);let xe=class Config extends Z{static all(){return _e(this,void 0,void 0,function*(){const e=yield this.findAll().catch(this.error),t={};return e&&e.forEach(e=>t[e.key]=e.value),t})}static del(e,t){return _e(this,void 0,void 0,function*(){var i;const r=null!==(i=null==t?void 0:t.id)&&void 0!==i?i:null;return((yield this.destroy(Object.assign({where:{key:e},individualHooks:!0},{user_id:r})).catch(this.error))||0)>0})}static get(e){return _e(this,arguments,void 0,function*(e,t=""){const[i]=(yield this.findOrCreate({where:{key:e},defaults:{key:e,value:t}}).catch(this.error))||[];return i?i.value:t})}static set(e,t,i){return _e(this,void 0,void 0,function*(){var r;const n=null!==(r=null==i?void 0:i.id)&&void 0!==r?r:null,[o]=(yield this.findOrCreate(Object.assign({where:{key:e}},{user_id:n})).catch(this.error))||[];o&&(o.value=t,yield o.save().catch(this.error))})}};he([$.String(),Ae("design:type",String)],xe.prototype,"key",void 0),he([$.String(),Ae("design:type",String)],xe.prototype,"value",void 0),he([$.CreatedAt,Ae("design:type",Date)],xe.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],xe.prototype,"updated_at",void 0),xe=he([W(Ie),z("configs"),J("4.2.0")],xe);let Fe=class Forgot extends Z{};he([$.Id(),Ae("design:type",Number)],Fe.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],Fe.prototype,"token",void 0),he([$.BigInt(),Ae("design:type",Number)],Fe.prototype,"timestamp",void 0),he([$.Boolean(),Ae("design:type",Boolean)],Fe.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],Fe.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Fe.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],Fe.prototype,"deleted_at",void 0),he([G(()=>we),Ae("design:type",Number)],Fe.prototype,"user_id",void 0),Fe=he([W(Ie),z("forgot"),J("4.2.0")],Fe);let ke=class Permission extends Z{};he([$.Id(),Ae("design:type",Number)],ke.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],ke.prototype,"name",void 0),he([$.String(),ie(!0),Ae("design:type",String)],ke.prototype,"route",void 0),he([$.String(),Ae("design:type",String)],ke.prototype,"tag",void 0),he([$.Text(),Ae("design:type",String)],ke.prototype,"description",void 0),he([$.Boolean(),Ae("design:type",Boolean)],ke.prototype,"state",void 0),he([$.CreatedAt,Ae("design:type",Date)],ke.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],ke.prototype,"updated_at",void 0),he([$.DeletedAt,Ae("design:type",Object)],ke.prototype,"deleted_at",void 0),he([X(()=>Ue,"permission_id"),Ae("design:type",Array)],ke.prototype,"groups_permissions",void 0),ke=he([W(Ie),z("permission"),Q(Re),J("4.3.1")],ke);let Ue=class GroupPermission extends Z{};he([$.CreatedAt,Ae("design:type",Date)],Ue.prototype,"created_at",void 0),he([G(()=>Ne),Ae("design:type",Number)],Ue.prototype,"group_id",void 0),he([G(()=>ke),Ae("design:type",Number)],Ue.prototype,"permission_id",void 0),Ue=he([W(Ie),z("groups_permissions"),Q(Re),J("4.2.0")],Ue);let je=class Log extends Z{static write(e,t,i){return _e(this,void 0,void 0,function*(){yield this.writeRaw(K.White,"",e,t,i)})}static error(e,t,i){return _e(this,void 0,void 0,function*(){yield this.writeRaw(K.Red,"error",e,t,i)})}static info(e,t,i){return _e(this,void 0,void 0,function*(){yield this.writeRaw(K.Cyan,"info",e,t,i)})}static success(e,t,i){return _e(this,void 0,void 0,function*(){yield this.writeRaw(K.Green,"success",e,t,i)})}static warning(e,t,i){return _e(this,void 0,void 0,function*(){yield this.writeRaw(K.Yellow,"warning",e,t,i)})}static writeRaw(e,t,i,r,n){return _e(this,void 0,void 0,function*(){n&&M.console(e,t,i),Ie&&(yield this.create({type:t,source:r,message:i}).catch(this.error))})}};he([$.Id(),Ae("design:type",Number)],je.prototype,"id",void 0),he([$.String(),Ae("design:type",String)],je.prototype,"type",void 0),he([$.String(),Ae("design:type",String)],je.prototype,"source",void 0),he([$.Text(),Ae("design:type",String)],je.prototype,"message",void 0),he([$.CreatedAt,Ae("design:type",Date)],je.prototype,"created_at",void 0),je=he([W(Ie),z("log"),J("4.2.0")],je);let Le=class Migration extends Z{};he([$.String(),Ae("design:type",String)],Le.prototype,"model",void 0),he([$.String(),Ae("design:type",String)],Le.prototype,"version",void 0),he([$.CreatedAt,Ae("design:type",Date)],Le.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Le.prototype,"updated_at",void 0),Le=he([W(Ie),z("migration"),J("4.2.0")],Le);let Ke=class Session extends Z{};he([$.String(),Ae("design:type",String)],Ke.prototype,"session",void 0),he([$.Text(),Ae("design:type",String)],Ke.prototype,"json",void 0),he([$.BigInt(),Ae("design:type",Number)],Ke.prototype,"expired",void 0),he([$.CreatedAt,Ae("design:type",Date)],Ke.prototype,"created_at",void 0),he([$.UpdatedAt,Ae("design:type",Date)],Ke.prototype,"updated_at",void 0),Ke=he([W(Ie),z("session"),J("4.2.0")],Ke);class AuthBase{static error(e){let t="token";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),je.error(e.message,t,Env.API_CONSOLE_ERROR)}}class AuthKey extends AuthBase{static user(e,t){return _e(this,void 0,void 0,function*(){if(!e)return{error:"INVALID TOKEN"};const i=t.hash.encrypt(e),r=yield we.findOne({where:{token:i,state:!0}}).catch(this.error);if(r){const t=e.replace(/(-[\w]{4})/g,"-****"),[i]=(yield Te.findOrCreate({where:{secret:t,user_id:r.id},defaults:{secret:t,user_id:r.id}}).catch(this.error))||[];if(i)return i.logout&&(i.logout=null,yield i.save().catch(this.error)),{auth:i,user:r}}return{error:"ACCESS DENIED"}})}}const Me=e=>de(e)?se(e):void 0,He={http:Me(Env.API_HTTP_CRT),token:Me(Env.API_TOKEN_CRT)},qe={http:Me(Env.API_HTTP_KEY),token:Me(Env.API_TOKEN_KEY)};class AuthToken extends AuthBase{static options(){return{algorithm:"RS256",expiresIn:`${Env.API_TOKEN_LIFETIME}ms`}}static create(e){return _e(this,void 0,void 0,function*(){if(!qe.token)return{error:"KEY NOT FOUND"};const{id:t}=e,i=r(),n=yield Te.create({secret:i,user_id:t}).catch(this.error);if(!n)return{error:"INTERNAL SERVER ERROR"};return{auth:n,token:oe.sign({id:t,secret:i},qe.token,this.options())}})}static destroy(e){return _e(this,void 0,void 0,function*(){return!(!e||e.logout)&&(e.logout=new Date,yield e.save(),!0)})}static renew(e){return _e(this,void 0,void 0,function*(){if(!qe.token)return{error:"KEY NOT FOUND"};const{error:t,decode:i}=this.verify(e,Env.API_TOKEN_RENEW/1e3);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield we.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const n=yield Te.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(n&&!n.logout){n.secret=r(),yield n.save().catch(this.error);return{auth:n,token:oe.sign({id:e,secret:n.secret},qe.token,this.options())}}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static user(e){return _e(this,void 0,void 0,function*(){const{error:t,decode:i}=this.verify(e);if(t)return{error:t};if(i){const{id:e,secret:t}=i;if(e&&t){const i=yield we.findOne({where:{id:e,state:!0}}).catch(this.error);if(i){const e=yield Te.findOne({where:{secret:t,user_id:i.id}}).catch(this.error);if(e&&!e.logout)return{auth:e,user:i}}return{error:"ACCESS DENIED"}}}return{error:"INVALID TOKEN"}})}static verify(e,t){if(!He.token)return{error:"CERT NOT FOUND"};if(!e||e.split(".").length<3)return{error:"INVALID TOKEN"};try{return{decode:oe.verify(e,He.token,{clockTolerance:t})}}catch(e){return{error:"INVALID TOKEN"}}}}class Store extends ye{constructor(){super(),this.all=e=>_e(this,void 0,void 0,function*(){e=e||i;const t=yield Ke.findAll({attributes:["session"],where:{expired:{[re.gte]:Date.now()}}}).catch(t=>(e(t),null));t&&e(null,t.map(e=>e.session)),e()}),this.clear=e=>_e(this,void 0,void 0,function*(){yield Ke.destroy().catch(i),e&&e()}),this.destroy=(e,t)=>_e(this,void 0,void 0,function*(){yield Ke.destroy({where:{session:e}}).catch(i),t&&t()}),this.expired=()=>_e(this,void 0,void 0,function*(){yield Ke.destroy({where:{expired:{[re.lt]:Date.now()}}}).catch(i)}),this.get=(e,t)=>_e(this,void 0,void 0,function*(){t=t||i;const r=yield Ke.findOne({where:{session:e,expired:{[re.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(i),void t(null)}return void t(null,e)}t(null)}),this.length=e=>_e(this,void 0,void 0,function*(){e&&e(null,(yield Ke.count().catch(i))||0)}),this.set=(e,t,r)=>_e(this,void 0,void 0,function*(){r=r||i;const n=Date.now()+Env.API_SESSION_LIFETIME,o=JSON.stringify(t),[s,d]=(yield Ke.findOrCreate({where:{session:e},defaults:{session:e,json:o,expired:n}}).catch(i))||[];s&&(d||(s.json=o,s.expired=n,yield s.save().catch(i))),r()}),this.loop=n(this.expired,3e4),this.loop.start()}}class Application extends _{constructor(e){super(e,{cert:He.http,cross:Env.API_HTTP_CROSS,hybrid:Env.API_HTTP_HYBRID,json:{strict:Env.API_BODYPARSER_STRICT,inflate:Env.API_BODYPARSER_INFLATE,limit:Env.API_BODYPARSER_LIMIT,type:Env.API_BODYPARSER_TYPE},key:qe.http,notfound:Env.API_HTTP_NOTFOUND,path:Env.API_HTTP_PATH,port:Env.API_HTTP_PORT,public:Env.API_HTTP_PUBLIC,redirect:Env.API_HTTP_REDIRECT,session:{store:new Store,name:Env.API_SESSION_NAME,secret:Env.API_SESSION_SECRET,cookie:{maxAge:Env.API_SESSION_LIFETIME},genid:r}}),this.hash=new H(Env.API_KEY_HASH)}error(e,t){Env.API_BASE_NAME&&(t=t?`${Env.API_BASE_NAME}.${t}`:Env.API_BASE_NAME),je.error(e.message,t,Env.API_CONSOLE_ERROR)}log(e,t){Env.API_BASE_NAME&&(t=t?`${Env.API_BASE_NAME}.${t}`:Env.API_BASE_NAME),je.info(e,t,!0)}listen(){const e=Object.create(null,{listen:{get:()=>super.listen}});return _e(this,void 0,void 0,function*(){yield Ie.sync(),yield this.migrations(Ie),yield o(this.controllers,e=>_e(this,void 0,void 0,function*(){s(e.sync)&&(yield e.sync(this))})),yield e.listen.call(this),Env.API_WEBSOCKET_START&&this.server&&(this._webSocket=new ge({server:this.server,verifyClient:(e,t)=>t(Env.API_WEBSOCKET_START)}),this._webSocket.on("connection",(e,t)=>_e(this,void 0,void 0,function*(){t.url||(t.url="");const i=t.url.length<=1?"":t.url.replace(/\//g,".");let r;e.on("message",n=>_e(this,void 0,void 0,function*(){if(r)try{const o=JSON.parse(n);this.emit("ws.message"+i,{data:o,message:n,req:t,user:r,ws:e})}catch(o){this.emit("ws.message"+i,{erro:o,message:n,req:t,user:r,ws:e})}else{const{user:o}=yield AuthToken.user(n.toString());o&&(r=o,this.emit("ws.connection"+i,{req:t,user:r,ws:e}))}r||e.close()})),e.on("close",()=>{r&&this.emit("ws.close"+i,{user:r,ws:e})}),yield d(2e3),r||e.close()})))})}migrations(e){return _e(this,void 0,void 0,function*(){const t=[];yield o(Object.keys(e.models),i=>_e(this,void 0,void 0,function*(){var r;const n=e.models[i],o=n.version();if(!o)return;const[s,d]=null!==(r=yield Le.findOrCreate({where:{model:n.tableName},defaults:{model:n.tableName,version:""}}).catch(this.error))&&void 0!==r?r:[];s&&(d||s.version!=o)&&(s.version=o,yield s.save().catch(this.error),t.push(n))})),yield o(t,e=>_e(this,void 0,void 0,function*(){return yield e.updateAttributes()}))})}websocket(){return this._webSocket}}var Ye,Ve,$e;class ControllerBase extends Controller{constructor(){super(...arguments),this[Ye]=[]}auth(e,t,i,r,n,o){return _e(this,void 0,void 0,function*(){var s;t=null!=t?t:r;const[d,a]=null!==(s=null==i?void 0:i.split(" "))&&void 0!==s?s:["",""];if(!(t||a&&d.toLowerCase()==Env.API_TOKEN_HEADER_KEY))return e.error("INVALID TOKEN");const{auth:u,error:l,user:p}=yield t?AuthKey.user(t,o):AuthToken.user(a);return l?e.error(l):u&&p?!t&&u.user_agent&&u.user_agent!=n?e.error("INVALID TOKEN"):(e.req.auth=u,e.req.user=p,void e.next()):e.error("INTERNAL SERVER ERROR")})}canCreate(e,t,i){return _e(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".create",i)})}canDelete(e,t,i){return _e(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".delete",i)})}canRead(e,t,i){return _e(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".read",i)})}canUpdate(e,t,i){return _e(this,void 0,void 0,function*(){yield this.permission(e,(t||this.name())+".update",i)})}error(e){let t="controller_base";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),je.error(e.message,t,Env.API_CONSOLE_ERROR)}name(){var e,t;return(null!==(t=null===(e=this.constructor)||void 0===e?void 0:e.name)&&void 0!==t?t:"api").replace(/(([a-z])([A-Z]))/g,"$2_$3")}permission(e,t,i){return _e(this,void 0,void 0,function*(){if(i){if((yield this.permissions(i,{route:t})).length>0)return e.next()}e.unauthorized("ACCESS DENIED")})}permissions(e,t){return _e(this,void 0,void 0,function*(){var i;return null!==(i=yield ke.findAll({where:Object.assign(Object.assign({},null!=t?t:{}),{state:!0}),include:[{model:Ue,required:!0,include:[{model:Ne,required:!0,where:{state:!0},include:[{model:Ce,required:!0,where:{user_id:e.id}}]}]}]}).catch(this.error))&&void 0!==i?i:[]})}session(e,t,r){return _e(this,void 0,void 0,function*(){r.auth&&r.user&&(r.user_agent?r.user_agent!=t&&r.regenerate(i):(r.user_agent=t,r.save(i))),e.next()})}sync(){return _e(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o(this[Controller.PERMISSIONS],i=>_e(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=a(e.replace(/_/g," ")," ");yield ke.findOrCreate({where:{route:r},defaults:Object.assign({name:`${n} ${a(i," ")}`,route:r,tag:n},t)})}))})}upload(e,t){t.path||(t.path=Env.API_UPLOAD_TEMP),t.size||(t.size=Env.API_UPLOAD_SIZE),t.field||(t.field=Env.API_UPLOAD_FIELD),T.middleware(e,t)}validation(e,t){return _e(this,void 0,void 0,function*(){const{error:i,value:r}=yield u.object(t).parse().validateAsync(e.req.body);if(i)return e.validation(i);e.req.body=r,e.next()})}}Ye=Controller.PERMISSIONS,he([Ee(0,m()),Ee(1,O(Env.API_KEY_HEADER)),Ee(2,O(Env.API_TOKEN_HEADER)),Ee(3,S(Env.API_KEY_HEADER)),Ee(4,O("user-agent")),Ee(5,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String,String,String,Application]),Ae("design:returntype",Promise)],ControllerBase.prototype,"auth",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],ControllerBase.prototype,"canCreate",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],ControllerBase.prototype,"canDelete",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],ControllerBase.prototype,"canRead",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],ControllerBase.prototype,"canUpdate",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],ControllerBase.prototype,"permission",null),he([Ee(0,m()),Ee(1,O("user-agent")),Ee(2,R()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Object]),Ae("design:returntype",Promise)],ControllerBase.prototype,"session",null),he([Ee(0,m()),Ee(1,P()),Ae("design:type",Function),Ae("design:paramtypes",[I,Object]),Ae("design:returntype",void 0)],ControllerBase.prototype,"upload",null),he([Ee(0,m()),Ee(1,P()),Ae("design:type",Function),Ae("design:paramtypes",[I,Object]),Ae("design:returntype",Promise)],ControllerBase.prototype,"validation",null);let Ge=class ControllerModel extends ControllerBase{constructor(){super(...arguments),this[Ve]=[],this[$e]=["create","read","update","delete"]}attributes(e){if(0==this[ControllerBase.ATTRIBUTES].length&&(this[ControllerBase.ATTRIBUTES]=Object.keys(this.model().getAttributes())),l(e))return e.length?e.map(e=>p(e)&&-1!=this[ControllerBase.ATTRIBUTES].indexOf(e)?e:void 0).filter(p):this[ControllerBase.ATTRIBUTES];const{exclude:t,include:i}=e,r=c(i)?this[ControllerBase.ATTRIBUTES]:i.map(e=>p(e)&&-1!=this[ControllerBase.ATTRIBUTES].indexOf(e)?e:void 0).filter(p),n=null!=t?t:[];return n.length?r.filter(e=>-1==n.indexOf(e)?e:void 0).filter(p):r}create(e){return _e(this,arguments,void 0,function*({ctx:e,options:t,body:i}){const r=yield this.model().create(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign({},t||{}),me(e))).catch(this.error);if(r){const t=this.key();return e.prepare(N.OK,{[t]:r.getDataValue(t)}),r}e.error("INTERNAL SERVER ERROR")})}delete(e){return _e(this,arguments,void 0,function*({ctx:e,options:t}){const i=this.key(),{[i]:r}=e.req.params;if(!r)return e.error("INTERNAL SERVER ERROR"),0;const n=yield this.model().destroy(Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[i]:r}),individualHooks:!0}),me(e))).catch(this.error);return n?(e.success("OK"),n):(e.notFound("RECORD NOT FOUND"),0)})}error(e){let t="controller_model";Env.API_BASE_NAME&&(t=`${Env.API_BASE_NAME}.${t}`),(null==e?void 0:e.sql)?je.error((null==e?void 0:e.message)+"\n"+(null==e?void 0:e.sql),t,Env.API_CONSOLE_ERROR):super.error(e)}findAll(e){return _e(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r,advanced:n,attributes:o,limited:s}){var d,a,u;const l=this.scope(r),v=Object.assign({},t||{}),{fields:h,limit:E,offset:A,asc:_,desc:m,search:O,where:S}=e.req.query;if(c(v.limit)){let e=Env.API_MODEL_LIMIT;p(E)&&(e=parseInt(E)||0),e=g(e,-1,Env.API_MODEL_LIMIT_MAX),v.limit=e>0?e:s?Env.API_MODEL_LIMIT:void 0}if(y(v.limit)&&(v.limit=v.limit>0?v.limit:void 0),p(A)){const e=parseInt(A)||0;v.offset=e>0?e:void 0}o=null!=o?o:this.attributes(null!==(d=null==v?void 0:v.attributes)&&void 0!==d?d:[]);const f=e=>o.indexOf(e)>=0,I=[];p(h)&&I.push(...h.split(";").filter(f)),I.length&&(v.attributes=I);const P=[];if(p(_)&&_.length&&P.push(..._.split(";").filter(f).map(e=>[e,"ASC"])),p(m)&&m.length&&P.push(...m.split(";").filter(f).map(e=>[e,"DESC"])),P.length&&(v.order=P),v.where=Object.assign({},v.where||{}),p(S)&&(null==n||n)){const t=ne.parse(o,S);if(!c(t.error))return e.validation(t.error.join(", ")),{count:0,records:[]};v.where=Object.assign(Object.assign({},v.where),null!==(a=t.value)&&void 0!==a?a:{})}else{const e=[];o.forEach(t=>{p(O)&&O.length&&e.push({[t]:{[re.like]:`%${O}%`}})}),e.length&&(v.where=Object.assign(Object.assign({},v.where),{[re.or]:[...e]}))}const R=l.count(Object.assign(Object.assign({},v),{distinct:!!v.include,col:this[ControllerBase.ATTRIBUTES].length?this[ControllerBase.ATTRIBUTES][0]:void 0})).catch(this.error),T=l.findAll(v).catch(this.error);yield Promise.allSettled([R,T]);const D=null!==(u=yield R)&&void 0!==u?u:0;let C=yield T;const b={count:D};return C?(C=i?yield i(C):C,(y(null==t?void 0:t.limit)||0==D)&&(b.count=C.length),e.prepare(N.OK,Object.assign(Object.assign({},b),{records:C})),Object.assign(Object.assign({},b),{records:C})):(e.error("INTERNAL SERVER ERROR"),Object.assign(Object.assign({},b),{records:[]}))})}findOne(e){return _e(this,arguments,void 0,function*({ctx:e,options:t,callback:i,scope:r}){const n=this.key(),{[n]:o}=e.req.params,s=yield this.scope(r).findOne(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:o})})).catch(this.error);return s?(e.prepare(N.OK,i?yield i(s):s.toJSON()),s):null===s?e.notFound("RECORD NOT FOUND"):void e.error("INTERNAL SERVER ERROR")})}sync(){return _e(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t={description:"",state:!0};yield o(this[ControllerBase.PERMISSIONS],i=>_e(this,void 0,void 0,function*(){const r=`${e}.${i}`,n=a(e.replace(/_/g," ")," ");yield ke.findOrCreate({where:{route:r},defaults:Object.assign({name:`${n} ${a(i," ")}`,route:r,tag:n},t)})}))})}update(e){return _e(this,arguments,void 0,function*({ctx:e,options:t,body:i}){var r;const n=this.key(),{[n]:o}=e.req.params,[s]=null!==(r=yield this.model().update(Object.assign(Object.assign({},e.req.body),i||{}),Object.assign(Object.assign(Object.assign({},t||{}),{where:Object.assign(Object.assign({},(t||{}).where),{[n]:o}),individualHooks:!0}),me(e))).catch(this.error))&&void 0!==r?r:[];return s?(e.success("OK"),!0):(e.success("RECORD NOT CHANGED"),!1)})}key(){return this.model().primaryKeyAttribute}name(){return this.model().tableName}scope(e){return e?this.model().scope(e):this.model()}};Ve=ControllerBase.ATTRIBUTES,$e=ControllerBase.PERMISSIONS,Ge=he([D(ControllerBase)],Ge);let We=class ControllerCrud extends Ge{constructor(){super(...arguments),this._crud={}}CrudArgumentsCreate(e){return{ctx:e}}CrudArgumentsFindAll(e){return{ctx:e}}CrudArgumentsFindOne(e){return{ctx:e}}CrudArgumentsDelete(e){return{ctx:e}}CrudArgumentsUpdate(e){return{ctx:e}}CrudValidationCreate(){return this._crud}CrudValidationUpdate(){return this._crud}add(e){return _e(this,void 0,void 0,function*(){yield this.create(this.CrudArgumentsCreate(e))})}all(e){return _e(this,void 0,void 0,function*(){yield this.findAll(this.CrudArgumentsFindAll(e))})}del(e){return _e(this,void 0,void 0,function*(){yield this.delete(this.CrudArgumentsDelete(e))})}get(e){return _e(this,void 0,void 0,function*(){yield this.findOne(this.CrudArgumentsFindOne(e))})}set(e){return _e(this,void 0,void 0,function*(){yield this.update(this.CrudArgumentsUpdate(e))})}validationCreate(e){return _e(this,void 0,void 0,function*(){const t=this.CrudValidationCreate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}validationUpdate(e){return _e(this,void 0,void 0,function*(){const t=this.CrudValidationUpdate();if(t==this._crud)return e.error("INTERNAL SERVER ERROR");yield this.validation(e,t)})}};he([C(),b("auth"),b("canCreate"),b("validationCreate"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"add",null),he([w(),b("auth"),b("canRead"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"all",null),he([B("/:id"),b("auth"),b("canDelete"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"del",null),he([w("/:id"),b("auth"),b("canRead"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"get",null),he([x("/:id"),b("auth"),b("canUpdate"),b("validationUpdate"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"set",null),he([Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"validationCreate",null),he([Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],We.prototype,"validationUpdate",null),We=he([D(Ge)],We);let ze=class AuditsController extends Ge{model(){return Be}all(e,t,i){return _e(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.table=i),yield this.findAll({ctx:e,options:{attributes:{exclude:["data","previously"]},where:r,order:[["created_at","DESC"]]},limited:!0})})}get(e){return _e(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}};he([w(),b("auth"),b("canRead"),Ee(0,m()),Ee(1,S("type")),Ee(2,S("table")),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String]),Ae("design:returntype",Promise)],ze.prototype,"all",null),he([w("/:id"),b("auth"),b("canRead"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],ze.prototype,"get",null),ze=he([F("/audits"),D(Ge)],ze);let Je=class AuthController extends ControllerBase{login(e,t,i,r,n){return _e(this,void 0,void 0,function*(){var o;yield d(Env.API_SLEEP_AUTH);const s=yield we.scope("password").findOne({where:{[re.or]:[{email:i},{username:i}]}}).catch(this.error);if(r+=null!==(o=null==s?void 0:s.salt)&&void 0!==o?o:"",!s||s.password!=q(r))return e.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e});const a=yield De.findOne({where:{state:!0,user_id:s.id}}).catch(this.error);if(a)return e.error("ACTIVATION REQUIRED"),n.emit("auth.activation",{ctx:e,register:a,user:s}),void this.emit("auth.activation",{ctx:e,register:a,user:s});if(!s.state)return e.notFound("INVALID USERNAME OR PASSWORD"),n.emit("auth.failure",{ctx:e,user:s}),void this.emit("auth.failure",{ctx:e,user:s});const{auth:u,error:l,token:p}=yield AuthToken.create(s);return l?(e.error(l),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e})):u&&p?(u.user_agent=t,yield u.save().catch(this.error),e.json({token:p}),n.emit("auth.login",{auth:u,ctx:e,user:s}),void this.emit("auth.login",{auth:u,ctx:e,user:s})):(e.error("INTERNAL SERVER ERROR"),n.emit("auth.failure",{ctx:e}),void this.emit("auth.failure",{ctx:e}))})}logout(e,t,i,r){return _e(this,void 0,void 0,function*(){if(yield AuthToken.destroy(t))return e.success("OK"),r.emit("auth.logout",{auth:t,ctx:e,user:i}),void this.emit("auth.logout",{auth:t,ctx:e,user:i});e.unauthorized("ACCESS DENIED")})}renew(e,t,i,r){return _e(this,void 0,void 0,function*(){const{auth:n,error:o,token:s}=yield AuthToken.renew(i);return o?e.error(o):n?(n.user_agent=t,yield n.save().catch(this.error),e.json({token:s}),r.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 _e(this,void 0,void 0,function*(){const i=yield this.permissions(t);if(!i)return e.error("INTERNAL SERVER ERROR");e.json(Object.assign(Object.assign({},v(["username","date","description","state","created_at","updated_at","deleted_at"],t.toJSON())),{permissions:i.map(e=>e.route)}))})}};var Ze;he([C("/login"),b("validation",{username:u.string().min(3).required(),password:u.string().min(5).required()}),Ee(0,m()),Ee(1,O("user-agent")),Ee(2,k("username")),Ee(3,k("password")),Ee(4,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String,String,Application]),Ae("design:returntype",Promise)],Je.prototype,"login",null),he([w("/logout"),b("auth"),Ee(0,m()),Ee(1,Se()),Ee(2,fe()),Ee(3,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,Te,we,Application]),Ae("design:returntype",Promise)],Je.prototype,"logout",null),he([C("/renew"),b("validation",{token:u.string().required()}),Ee(0,m()),Ee(1,O("user-agent")),Ee(2,k("token")),Ee(3,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String,Application]),Ae("design:returntype",Promise)],Je.prototype,"renew",null),he([w(),b("auth"),Ee(0,m()),Ee(1,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,we]),Ae("design:returntype",Promise)],Je.prototype,"user",null),Je=he([F("/auth"),D(ControllerBase)],Je);let Xe=class FilesController extends ControllerBase{constructor(){super(...arguments),this[Ze]=["delete","download","edit","list","read","rename","upload","write"]}directory(){return Env.API_HTTP_PUBLIC||"./"}files(e){return _e(this,void 0,void 0,function*(){let{path:t}=e.req;t=t.replace(/(^\/path(\/)?)|([\\.]{1,2}\/)/g,"");const i=ve(this.directory(),t);if(!de(i)||!ae(i).isDirectory())return e.notFound("RECORD NOT FOUND");let r=[];return r=ue(i),r=r.map(e=>this.info(ve(i,e))),r=r.filter(h),Object.assign(Object.assign({},this.info(i)),{files:r})})}access(e,t,i){return _e(this,void 0,void 0,function*(){yield this.permission(e,this.name()+"."+t,i)})}info(e){if(!de(e))return null;const t=ae(e),i=e.split("/").pop();e=e.replace(this.directory(),"/").replace(/^\/\//,"/");const r=t.isDirectory();return{name:i,path:e.replace(/^\/\//,"/"),size:t.size,extension:r?"":"."+e.split(".").pop(),created:t.birthtime,modified:t.mtime,directory:r,symlink:t.isSymbolicLink()}}name(){return"files"}sync(){return _e(this,void 0,void 0,function*(){const e=this.name().toLowerCase(),t=a(e.replace(/_/g," ")," "),i={description:"",state:!0};yield o(this[ControllerBase.PERMISSIONS],r=>_e(this,void 0,void 0,function*(){const n=`${e}.${r}`;yield ke.findOrCreate({where:{route:n},defaults:Object.assign({name:`${t} ${a(r," ")}`,route:n,tag:t},i)})}))})}};Ze=ControllerBase.PERMISSIONS,he([w("/path"),w("/path/*path"),b("auth"),b("access","list"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],Xe.prototype,"files",null),he([Ee(0,m()),Ee(1,P()),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],Xe.prototype,"access",null),Xe=he([F("/files"),D(ControllerBase)],Xe);let Qe=class ForgotController extends ControllerBase{check(e,t){return _e(this,void 0,void 0,function*(){const i=yield this.find(t);if(!i||!i.user)return e.notFound("RECORD NOT FOUND");i.token=E(),yield i.save(),e.json({token:i.token})})}forgot(e,t,i){return _e(this,void 0,void 0,function*(){yield d(Env.API_SLEEP_FORGOT);const r=t,n=yield we.findOne({where:{[re.or]:[{email:r},{username:t}]}}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const o=E(),s=Date.now()+6e4*Env.API_TOKEN_FORGOT,a=yield Fe.create({token:o,timestamp:s,state:!0,user_id:n.id});e.success("OK"),i.emit("forgot.send",{ctx:e,forgot:a,user:n}),this.emit("forgot.send",{ctx:e,forgot:a,user:n})})}reset(e,t,i,r){return _e(this,void 0,void 0,function*(){const n=yield this.find(t);if(!n)return e.notFound("RECORD NOT FOUND");n.state=!1,yield n.save().catch(this.error),n.user.password=q(i),yield n.user.save().catch(this.error),e.success("OK"),r.emit("forgot.reset",{ctx:e,user:n.user}),this.emit("forgot.reset",{ctx:e,user:n.user})})}find(e){return _e(this,void 0,void 0,function*(){return yield Fe.findOne({where:{token:e,state:!0},include:[{model:we,required:!0}]}).catch(this.error)})}};he([w("/check"),b("validation",{token:u.string().required()}),Ee(0,m()),Ee(1,k("token")),Ae("design:type",Function),Ae("design:paramtypes",[I,String]),Ae("design:returntype",Promise)],Qe.prototype,"check",null),he([C(),b("validation",{username:u.string().min(4).required()}),Ee(0,m()),Ee(1,k("username")),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Application]),Ae("design:returntype",Promise)],Qe.prototype,"forgot",null),he([C("/reset"),b("validation",{token:u.string().required(),password:u.string().min(5).required()}),Ee(0,m()),Ee(1,k("token")),Ee(2,k("password")),Ee(3,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String,Application]),Ae("design:returntype",Promise)],Qe.prototype,"reset",null),Qe=he([F("/forgot"),D(ControllerBase)],Qe);let et=class GroupsController extends We{constructor(){super(...arguments),this.schemaCreate={name:u.string().required(),description:u.string().empty(""),state:u.boolean().parse().required()},this.schemaUpdate={name:u.string().empty(),description:u.string().empty(),state:u.boolean().parse().empty()}}model(){return Ne}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};et=he([F("/groups"),D(We)],et);let tt=class GroupsPermissionsController extends Ge{model(){return Ue}all(e,t){return _e(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{group_id:t},include:[{model:ke,required:!0}]},callback:e=>e.map(e=>e.permission)})})}me(e,t){return _e(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return _e(this,void 0,void 0,function*(){const n=yield Ne.findByPk(t,{attributes:["id"]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");const o=n.id;if(yield Ue.destroy(Object.assign({where:{group_id:o},individualHooks:!0},r)),i){let e=0;yield d(1e3);for(let t=0;t<i.length;t++)e=yield ke.count({where:{id:i[t]}}),e&&(yield Ue.create({group_id:o,permission_id:i[t]},Object.assign({},r)))}e.success("OK")})}};var it;he([w("/:id/permissions"),b("auth"),b("canRead","groups"),Ee(0,m()),Ee(1,U("id")),Ae("design:type",Function),Ae("design:paramtypes",[I,String]),Ae("design:returntype",Promise)],tt.prototype,"all",null),he([w("/permissions"),b("auth"),b("canRead","users"),Ee(0,m()),Ee(1,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,we]),Ae("design:returntype",Promise)],tt.prototype,"me",null),he([x("/:id/permissions"),b("auth"),b("canUpdate","groups"),b("validation",{permissions:u.array(u.number().parse())}),Ee(0,m()),Ee(1,U("id")),Ee(2,k("permissions")),Ee(3,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Array,Object]),Ae("design:returntype",Promise)],tt.prototype,"set",null),tt=he([F("/groups"),D(Ge)],tt);let rt=class LogsController extends Ge{constructor(){super(...arguments),this[it]=["read"]}model(){return je}all(e,t,i){return _e(this,void 0,void 0,function*(){const r={};t&&(r.type=t),i&&(r.source=i),yield this.findAll({ctx:e,options:{where:r,order:[["created_at","DESC"]]},limited:!0})})}};it=Ge.PERMISSIONS,he([w(),b("auth"),b("canRead"),Ee(0,m()),Ee(1,S("type")),Ee(2,S("source")),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String]),Ae("design:returntype",Promise)],rt.prototype,"all",null),rt=he([F("/logs"),D(Ge)],rt);let nt=class PermissionsController extends We{constructor(){super(...arguments),this.schemaCreate={name:u.string().required(),route:u.string().required(),tag:u.string().required(),description:u.string().empty(""),state:u.boolean().parse().required()},this.schemaUpdate={name:u.string().empty(),route:u.string().empty(),tag:u.string().empty(),description:u.string().empty(),state:u.boolean().parse().empty()}}model(){return ke}CrudArgumentsFindAll(e){return{ctx:e}}CrudValidationCreate(){return this.schemaCreate}CrudValidationUpdate(){return this.schemaUpdate}};nt=he([F("/permissions"),D(We)],nt);let ot=class RegisterController extends ControllerBase{register(e,t,i){return _e(this,void 0,void 0,function*(){yield d(Env.API_SLEEP_REGISTRY);const{name:r,date:n,email:o,username:s,password:a,confirm:u}=t,l=s||o,p=q(a);if(yield we.count({where:{[re.or]:[{email:o},{username:l}]}}).catch(this.error))return e.validation("INVALID EMAIL OR USERNAME");if(p!=q(u))return e.error("INVALID PASSWORD");const c=yield we.create({name:r,email:o,username:l,password:p,avatar:"",date:n,description:"",state:!1}).catch(this.error);if(!c)return e.error("INTERNAL SERVER ERROR");const g=yield De.create({token:yield this.getId(),user_id:c.id,state:!0}).catch(this.error);if(!g)return yield c.destroy().catch(this.error),e.error("INTERNAL SERVER ERROR");e.success("OK"),i.emit("register.user",{ctx:e,register:g,user:c}),this.emit("register.user",{ctx:e,register:g,user:c})})}confirm(e,t,i){return _e(this,void 0,void 0,function*(){const r=yield De.findOne({where:{token:t,state:!0},include:[{model:we,required:!0}]}).catch(this.error);if(!r)return e.notFound("RECORD NOT FOUND");r.state=!1,yield r.save().catch(this.error),r.user.state=!0,yield r.user.save().catch(this.error),e.success("OK"),i.emit("register.confirm",{ctx:e,register:r,user:r.user}),this.emit("register.confirm",{ctx:e,register:r,user:r.user})})}send(e,t,i){return _e(this,void 0,void 0,function*(){const r=t,n=yield De.findOne({where:{state:!0},include:[{model:we,required:!0,where:{[re.or]:[{email:r},{username:t}]}}]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");e.success("OK"),i.emit("register.send",{ctx:e,register:n,user:n.user}),this.emit("register.send",{ctx:e,register:n,user:n.user})})}getId(){return _e(this,void 0,void 0,function*(){const e=r();return(yield De.count({where:{token:e}}))?this.getId():e})}};he([C(),b("validation",{name:u.string().required(),date:u.date().required(),email:u.string().email().required(),username:u.string().min(4).empty(),password:u.string().min(5).required(),confirm:u.string().min(5).required()}),Ee(0,m()),Ee(1,k()),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,Object,Application]),Ae("design:returntype",Promise)],ot.prototype,"register",null),he([C("/confirm"),b("validation",{token:u.string().required()}),Ee(0,m()),Ee(1,k("token")),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Application]),Ae("design:returntype",Promise)],ot.prototype,"confirm",null),he([C("/send"),b("validation",{username:u.string().min(4).required()}),Ee(0,m()),Ee(1,k("username")),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Application]),Ae("design:returntype",Promise)],ot.prototype,"send",null),ot=he([F("/register"),D(ControllerBase)],ot);let st=class SetupController extends ControllerBase{setup(e,t){return _e(this,void 0,void 0,function*(){var i;if(yield we.count())return e.success("OK");const r=E(),n=yield we.create({name:"Admin",email:"admin@localhost",username:"admin",password:q("admin"+r),salt:r,token:"",avatar:"",date:new Date,description:"DEFAULT",state:!0},Object.assign({},t)),s=yield Ne.create(Object.assign({name:"Admin"},{description:"API CORE",state:!0}),Object.assign({},t));yield Ce.create({user_id:n.id,group_id:s.id},Object.assign({},t));const d=null!==(i=yield ke.findAll({where:{state:!0}}).catch(this.error))&&void 0!==i?i:[];yield o(d,e=>_e(this,void 0,void 0,function*(){yield Ue.create({group_id:s.id,permission_id:e.id},Object.assign({},t))})),e.success("OK")})}};he([w(),Ee(0,m()),Ee(1,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,Object]),Ae("design:returntype",Promise)],st.prototype,"setup",null),st=he([F("/setup"),D(ControllerBase)],st);let dt=class UsersController extends Ge{model(){return we}constructor(){super(),this.path=Env.API_HTTP_PUBLIC+"/avatar",Env.API_HTTP_PUBLIC&&de(Env.API_HTTP_PUBLIC)&&!de(this.path)&&le(this.path)}avatar(e,t,i,r){return _e(this,void 0,void 0,function*(){if(t.length){const n=t[0].filename||"";if(n){const t=this.path+"/"+i.avatar;if(de(t)&&pe(t).isFile()&&ce(t),i.avatar=n,yield i.save(Object.assign({},r)).catch(this.error))return e.success("OK")}}e.success("RECORD NOT CHANGED")})}avatar_del(e,t,i){return _e(this,void 0,void 0,function*(){const r=this.path+"/"+t.avatar;t.avatar="",(yield t.save(Object.assign({},i)).catch(this.error))&&de(r)&&ce(r),e.success("OK")})}password(e,t,i,r,n){return _e(this,void 0,void 0,function*(){var o;if(Env.API_USER_HISTORY){if(yield be.count({where:{password:q(i+r.id)}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED")}const s=yield this.scope("password").findOne({where:{id:r.id,state:!0}}).catch(this.error);return t+=null!==(o=null==s?void 0:s.salt)&&void 0!==o?o:"",s&&s.password==q(t)?(s.salt=E(),s.password=q(i+s.salt),(yield s.save(Object.assign({},n)).catch(this.error))?e.success("OK"):void e.success("RECORD NOT CHANGED")):e.error("INVALID PASSWORD")})}token(e,t,i){return _e(this,void 0,void 0,function*(){const r=yield this.model().findOne({attributes:["token"],where:{id:t.id}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")})}token_del(e,t,i){return _e(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(Object.assign({},i)).catch(this.error),e.success("OK");e.notFound("RECORD NOT FOUND")})}token_get(e,t,i){return _e(this,void 0,void 0,function*(){const r=yield this.scope("token").findOne({where:{id:t}}).catch(this.error);if(r)return e.json({token:i.hash.decrypt(r.token)});e.notFound("RECORD NOT FOUND")})}token_renew(e,t,i,r){return _e(this,void 0,void 0,function*(){const n=yield this.model().findOne({attributes:["id","token"],where:{id:t}}).catch(this.error);if(n){const t=yield this.token_new();return n.token=r.hash.encrypt(t),yield n.save(Object.assign({},i)).catch(this.error),e.json({token:t})}e.notFound("RECORD NOT FOUND")})}token_new(){return _e(this,void 0,void 0,function*(){var e;const t=r();return(null!==(e=yield this.model().count({where:{token:t}}).catch(this.error))&&void 0!==e?e:0)?this.token_new():t})}add(e,t){return _e(this,void 0,void 0,function*(){const i=E(),r=yield this.create({ctx:e,body:{password:q(t+i),salt:i}});Env.API_USER_HISTORY&&r&&(yield be.create({password:q(t+r.id),user_id:r.id}))})}all(e){return _e(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{attributes:{exclude:["password","salt","token"]}}})})}del(e,t,i){return _e(this,void 0,void 0,function*(){if(i.id.toString()==t)return e.notFound("RECORD NOT FOUND");yield this.delete({ctx:e})})}get(e){return _e(this,void 0,void 0,function*(){yield this.findOne({ctx:e})})}set(e,t,i){return _e(this,void 0,void 0,function*(){if(Env.API_USER_HISTORY&&i){const r=q(i+t);if(yield be.count({where:{password:r}}).catch(this.error))return e.error("PASSWORD PREVIOUSLY REGISTERED");yield be.create({password:r,user_id:t}).catch(this.error)}const r=i?E():"";yield this.update({ctx:e,body:i?{password:q(i+r),salt:r}:{}})})}};he([C("/avatar"),b("auth"),b("upload",e=>({count:1,field:"file",path:e.controller.path,types:["image/bmp","image/jpeg","image/png"],size:32})),Ee(0,m()),Ee(1,j()),Ee(2,fe()),Ee(3,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,Array,we,Object]),Ae("design:returntype",Promise)],dt.prototype,"avatar",null),he([B("/avatar"),b("auth"),Ee(0,m()),Ee(1,fe()),Ee(2,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,we,Object]),Ae("design:returntype",Promise)],dt.prototype,"avatar_del",null),he([C("/password"),b("auth"),b("validation",{oldPassword:u.string().min(5).required(),newPassword:u.string().min(5).required(),confirmPassword:u.string().equal(u.ref("newPassword"))}),Ee(0,m()),Ee(1,k("oldPassword")),Ee(2,k("newPassword")),Ee(3,fe()),Ee(4,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String,we,Object]),Ae("design:returntype",Promise)],dt.prototype,"password",null),he([w("/token"),b("auth"),Ee(0,m()),Ee(1,fe()),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,we,Application]),Ae("design:returntype",Promise)],dt.prototype,"token",null),he([B("/token/:id"),b("auth"),b("canDelete"),Ee(0,m()),Ee(1,U("id")),Ee(2,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Object]),Ae("design:returntype",Promise)],dt.prototype,"token_del",null),he([w("/token/:id"),b("auth"),b("canCreate"),Ee(0,m()),Ee(1,U("id")),Ee(2,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Application]),Ae("design:returntype",Promise)],dt.prototype,"token_get",null),he([w("/token/renew/:id"),b("auth"),b("canUpdate"),Ee(0,m()),Ee(1,U("id")),Ee(2,Oe()),Ee(3,f()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Object,Application]),Ae("design:returntype",Promise)],dt.prototype,"token_renew",null),he([C(),b("auth"),b("canCreate"),b("validation",{name:u.string().required(),email:u.string().email().required(),username:u.string().min(4).required(),password:u.string().min(5).required(),description:u.string().empty(""),state:u.boolean().parse().required()}),Ee(0,m()),Ee(1,k("password")),Ae("design:type",Function),Ae("design:paramtypes",[I,String]),Ae("design:returntype",Promise)],dt.prototype,"add",null),he([w(),b("auth"),b("canRead"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],dt.prototype,"all",null),he([B("/:id"),b("auth"),b("canDelete"),Ee(0,m()),Ee(1,U("id")),Ee(2,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,we]),Ae("design:returntype",Promise)],dt.prototype,"del",null),he([w("/:id"),b("auth"),b("canRead"),Ee(0,m()),Ae("design:type",Function),Ae("design:paramtypes",[I]),Ae("design:returntype",Promise)],dt.prototype,"get",null),he([x("/:id"),b("auth"),b("canUpdate"),b("validation",{name:u.string().empty(),email:u.string().email().empty(),username:u.string().min(4).empty(),password:u.string().min(5).empty().filter(""),description:u.string().empty(),state:u.boolean().parse().empty()}),Ee(0,m()),Ee(1,U("id")),Ee(2,k("password")),Ae("design:type",Function),Ae("design:paramtypes",[I,String,String]),Ae("design:returntype",Promise)],dt.prototype,"set",null),dt=he([F("/users"),D(Ge),Ae("design:paramtypes",[])],dt);let at=class UsersGroupsController extends Ge{model(){return Ce}all(e,t){return _e(this,void 0,void 0,function*(){yield this.findAll({ctx:e,options:{where:{user_id:t},include:[{model:Ne,required:!0}]},callback:e=>e.map(e=>e.group)})})}me(e,t){return _e(this,void 0,void 0,function*(){yield this.all(e,t.id.toString())})}set(e,t,i,r){return _e(this,void 0,void 0,function*(){const n=yield we.findByPk(t,{attributes:["id"]}).catch(this.error);if(!n)return e.notFound("RECORD NOT FOUND");if(yield Ce.destroy(Object.assign({where:{user_id:n.id},individualHooks:!0},r)),i){let e=0;yield d(1e3);for(let t=0;t<i.length;t++)e=yield Ne.count({where:{id:i[t]}}),e&&(yield Ce.create({user_id:n.id,group_id:i[t]},Object.assign({},r)))}e.success("OK")})}};he([w("/:id/groups"),b("auth"),b("canRead","users"),Ee(0,m()),Ee(1,U("id")),Ae("design:type",Function),Ae("design:paramtypes",[I,String]),Ae("design:returntype",Promise)],at.prototype,"all",null),he([w("/groups"),b("auth"),b("canRead","users"),Ee(0,m()),Ee(1,fe()),Ae("design:type",Function),Ae("design:paramtypes",[I,we]),Ae("design:returntype",Promise)],at.prototype,"me",null),he([x("/:id/groups"),b("auth"),b("canUpdate","users"),b("validation",{groups:u.array(u.number().parse())}),Ee(0,m()),Ee(1,U("id")),Ee(2,k("groups")),Ee(3,Oe()),Ae("design:type",Function),Ae("design:paramtypes",[I,String,Array,Object]),Ae("design:returntype",Promise)],at.prototype,"set",null),at=he([F("/users"),D(Ge)],at);export{Application,Be as Audit,ze as AuditsController,Te as Auth,AuthBase,Je as AuthController,AuthKey,AuthToken,xe as Config,Controller,ControllerBase,We as ControllerCrud,Ge as ControllerModel,Env,Xe as FilesController,Fe as Forgot,Qe as ForgotController,Ne as Group,Ue as GroupPermission,et as GroupsController,tt as GroupsPermissionsController,je as Log,rt as LogsController,Le as Migration,ke as Permission,nt as PermissionsController,De as Register,ot as RegisterController,Oe as ReqAudit,Se as ReqAuth,fe as ReqUser,Ke as Session,st as SetupController,Store,we as User,Ce as UserGroup,be as UserHistory,dt as UsersController,at as UsersGroupsController,me as audit,He as crt,Ie as database,Re as hooks,qe as key};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrewcaires/api",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.5.1",
|
|
4
4
|
"description": "Simple api for small applications using express, jsonwebtoken, sequelize and websocket",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs.js",
|
|
@@ -46,31 +46,31 @@
|
|
|
46
46
|
},
|
|
47
47
|
"homepage": "https://github.com/andrewcaires/npm/tree/main/api#readme",
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@andrewcaires/express": "^1.2.
|
|
50
|
-
"@andrewcaires/node": "^1.2.
|
|
51
|
-
"@andrewcaires/sequelize": "^
|
|
52
|
-
"@andrewcaires/utils.js": "^0.4.
|
|
49
|
+
"@andrewcaires/express": "^1.2.7",
|
|
50
|
+
"@andrewcaires/node": "^1.2.9",
|
|
51
|
+
"@andrewcaires/sequelize": "^2.0.2",
|
|
52
|
+
"@andrewcaires/utils.js": "^0.4.20",
|
|
53
53
|
"cors": "^2.8.5",
|
|
54
|
-
"dotenv": "^17.2.
|
|
54
|
+
"dotenv": "^17.2.3",
|
|
55
55
|
"express-session": "^1.18.2",
|
|
56
|
-
"jsonwebtoken": "^9.0.
|
|
57
|
-
"tsx": "^4.
|
|
58
|
-
"ws": "^8.
|
|
56
|
+
"jsonwebtoken": "^9.0.3",
|
|
57
|
+
"tsx": "^4.21.0",
|
|
58
|
+
"ws": "^8.19.0"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
|
-
"@rollup/plugin-commonjs": "^
|
|
61
|
+
"@rollup/plugin-commonjs": "^29.0.0",
|
|
62
62
|
"@rollup/plugin-terser": "^0.4.4",
|
|
63
|
-
"@rollup/plugin-typescript": "^12.
|
|
63
|
+
"@rollup/plugin-typescript": "^12.3.0",
|
|
64
64
|
"@types/cors": "^2.8.19",
|
|
65
65
|
"@types/express-session": "^1.18.2",
|
|
66
66
|
"@types/jsonwebtoken": "^9.0.10",
|
|
67
|
-
"@types/node": "^
|
|
67
|
+
"@types/node": "^25.0.8",
|
|
68
68
|
"@types/ws": "^8.18.1",
|
|
69
|
-
"eslint": "^9.
|
|
69
|
+
"eslint": "^9.39.2",
|
|
70
70
|
"mariadb": "^3.4.5",
|
|
71
|
-
"rollup": "^4.
|
|
72
|
-
"rollup-plugin-dts": "^6.
|
|
71
|
+
"rollup": "^4.55.1",
|
|
72
|
+
"rollup-plugin-dts": "^6.3.0",
|
|
73
73
|
"tslib": "^2.8.1",
|
|
74
|
-
"typescript-eslint": "^8.
|
|
74
|
+
"typescript-eslint": "^8.53.0"
|
|
75
75
|
}
|
|
76
76
|
}
|