chyz 1.0.12-rc.14

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.
Files changed (163) hide show
  1. package/BaseChyz.ts +316 -0
  2. package/Chyz.ts +11 -0
  3. package/Examples/Controllers/ApiController.ts +121 -0
  4. package/Examples/Controllers/PublicController.ts +44 -0
  5. package/Examples/Controllers/SiteController.ts +127 -0
  6. package/Examples/Models/Customer.ts +113 -0
  7. package/Examples/Models/Order.ts +48 -0
  8. package/Examples/Models/OrderItem.ts +26 -0
  9. package/Examples/Models/User.ts +80 -0
  10. package/Examples/index.ts +38 -0
  11. package/Examples/log/access.log +0 -0
  12. package/Examples/log/app.log +3264 -0
  13. package/Examples/log/errors.log +534 -0
  14. package/Examples/package.json +45 -0
  15. package/Examples/tsconfig.json +20 -0
  16. package/Examples/yarn.lock +2202 -0
  17. package/README.md +218 -0
  18. package/base/ActionFilter.ts +71 -0
  19. package/base/BaseError.ts +26 -0
  20. package/base/BaseObject.ts +19 -0
  21. package/base/Behavior.ts +6 -0
  22. package/base/Component.ts +66 -0
  23. package/base/Configurable.ts +10 -0
  24. package/base/Controller.ts +84 -0
  25. package/base/DataErrorDbException.ts +16 -0
  26. package/base/DbConnection.ts +51 -0
  27. package/base/ForbiddenHttpException.ts +15 -0
  28. package/base/InvalidConfigException.ts +16 -0
  29. package/base/Model.ts +254 -0
  30. package/base/NotFoundHttpException.ts +14 -0
  31. package/base/RestClient.ts +27 -0
  32. package/base/UnauthorizedHttpException.ts +16 -0
  33. package/base/ValidationHttpException.ts +14 -0
  34. package/base/db/Exception.ts +14 -0
  35. package/base/index.ts +16 -0
  36. package/decorator/Middleware.ts +9 -0
  37. package/decorator/controller.ts +22 -0
  38. package/decorator/enums/ControllerDecoratorParams.ts +5 -0
  39. package/decorator/get.ts +37 -0
  40. package/decorator/index.ts +3 -0
  41. package/decorator/post.ts +36 -0
  42. package/dist/BaseChyz.js +257 -0
  43. package/dist/BaseChyz.js.map +1 -0
  44. package/dist/Chyz.js +15 -0
  45. package/dist/Chyz.js.map +1 -0
  46. package/dist/base/ActionFilter.js +75 -0
  47. package/dist/base/ActionFilter.js.map +1 -0
  48. package/dist/base/BaseError.js +26 -0
  49. package/dist/base/BaseError.js.map +1 -0
  50. package/dist/base/BaseObject.js +20 -0
  51. package/dist/base/BaseObject.js.map +1 -0
  52. package/dist/base/Behavior.js +8 -0
  53. package/dist/base/Behavior.js.map +1 -0
  54. package/dist/base/Component.js +61 -0
  55. package/dist/base/Component.js.map +1 -0
  56. package/dist/base/Configurable.js +9 -0
  57. package/dist/base/Configurable.js.map +1 -0
  58. package/dist/base/Controller.js +75 -0
  59. package/dist/base/Controller.js.map +1 -0
  60. package/dist/base/DataErrorDbException.js +18 -0
  61. package/dist/base/DataErrorDbException.js.map +1 -0
  62. package/dist/base/DbConnection.js +53 -0
  63. package/dist/base/DbConnection.js.map +1 -0
  64. package/dist/base/ForbiddenHttpException.js +17 -0
  65. package/dist/base/ForbiddenHttpException.js.map +1 -0
  66. package/dist/base/InvalidConfigException.js +18 -0
  67. package/dist/base/InvalidConfigException.js.map +1 -0
  68. package/dist/base/Model.js +243 -0
  69. package/dist/base/Model.js.map +1 -0
  70. package/dist/base/NotFoundHttpException.js +18 -0
  71. package/dist/base/NotFoundHttpException.js.map +1 -0
  72. package/dist/base/RestClient.js +26 -0
  73. package/dist/base/RestClient.js.map +1 -0
  74. package/dist/base/UnauthorizedHttpException.js +18 -0
  75. package/dist/base/UnauthorizedHttpException.js.map +1 -0
  76. package/dist/base/ValidationHttpException.js +18 -0
  77. package/dist/base/ValidationHttpException.js.map +1 -0
  78. package/dist/base/db/Exception.js +16 -0
  79. package/dist/base/db/Exception.js.map +1 -0
  80. package/dist/base/index.js +29 -0
  81. package/dist/base/index.js.map +1 -0
  82. package/dist/decorator/Middleware.js +12 -0
  83. package/dist/decorator/Middleware.js.map +1 -0
  84. package/dist/decorator/controller.js +25 -0
  85. package/dist/decorator/controller.js.map +1 -0
  86. package/dist/decorator/enums/ControllerDecoratorParams.js +10 -0
  87. package/dist/decorator/enums/ControllerDecoratorParams.js.map +1 -0
  88. package/dist/decorator/get.js +37 -0
  89. package/dist/decorator/get.js.map +1 -0
  90. package/dist/decorator/index.js +16 -0
  91. package/dist/decorator/index.js.map +1 -0
  92. package/dist/decorator/post.js +37 -0
  93. package/dist/decorator/post.js.map +1 -0
  94. package/dist/filters/AccessControl.js +76 -0
  95. package/dist/filters/AccessControl.js.map +1 -0
  96. package/dist/filters/AccessRule.js +79 -0
  97. package/dist/filters/AccessRule.js.map +1 -0
  98. package/dist/filters/auth/AuthInterface.js +3 -0
  99. package/dist/filters/auth/AuthInterface.js.map +1 -0
  100. package/dist/filters/auth/AuthMethod.js +71 -0
  101. package/dist/filters/auth/AuthMethod.js.map +1 -0
  102. package/dist/filters/auth/HttpBasicAuth.js +8 -0
  103. package/dist/filters/auth/HttpBasicAuth.js.map +1 -0
  104. package/dist/filters/auth/HttpBearerAuth.js +33 -0
  105. package/dist/filters/auth/HttpBearerAuth.js.map +1 -0
  106. package/dist/filters/auth/HttpHeaderAuth.js +61 -0
  107. package/dist/filters/auth/HttpHeaderAuth.js.map +1 -0
  108. package/dist/filters/auth/JwtHttpBearerAuth.js +82 -0
  109. package/dist/filters/auth/JwtHttpBearerAuth.js.map +1 -0
  110. package/dist/filters/auth/index.js +16 -0
  111. package/dist/filters/auth/index.js.map +1 -0
  112. package/dist/filters/index.js +15 -0
  113. package/dist/filters/index.js.map +1 -0
  114. package/dist/index.js +28 -0
  115. package/dist/index.js.map +1 -0
  116. package/dist/log/config/log4js.json +55 -0
  117. package/dist/model/RouteDefinition.js +9 -0
  118. package/dist/model/RouteDefinition.js.map +1 -0
  119. package/dist/requiments/Glob.js +11 -0
  120. package/dist/requiments/Glob.js.map +1 -0
  121. package/dist/requiments/ReflectUtil.js +25 -0
  122. package/dist/requiments/ReflectUtil.js.map +1 -0
  123. package/dist/requiments/Utils.js +40 -0
  124. package/dist/requiments/Utils.js.map +1 -0
  125. package/dist/validators/BooleanValidator.js +2 -0
  126. package/dist/validators/BooleanValidator.js.map +1 -0
  127. package/dist/validators/CompareValidator.js +2 -0
  128. package/dist/validators/CompareValidator.js.map +1 -0
  129. package/dist/validators/DateValidator.js +2 -0
  130. package/dist/validators/DateValidator.js.map +1 -0
  131. package/dist/validators/EmailValidator.js +2 -0
  132. package/dist/validators/EmailValidator.js.map +1 -0
  133. package/dist/validators/Validator.js +28 -0
  134. package/dist/validators/Validator.js.map +1 -0
  135. package/dist/web/IdentityInterface.js +9 -0
  136. package/dist/web/IdentityInterface.js.map +1 -0
  137. package/dist/web/User.js +83 -0
  138. package/dist/web/User.js.map +1 -0
  139. package/filters/AccessControl.ts +64 -0
  140. package/filters/AccessRule.ts +137 -0
  141. package/filters/auth/AuthInterface.ts +34 -0
  142. package/filters/auth/AuthMethod.ts +88 -0
  143. package/filters/auth/HttpBasicAuth.ts +7 -0
  144. package/filters/auth/HttpBearerAuth.ts +31 -0
  145. package/filters/auth/HttpHeaderAuth.ts +53 -0
  146. package/filters/auth/JwtHttpBearerAuth.ts +81 -0
  147. package/filters/auth/index.ts +3 -0
  148. package/filters/index.ts +2 -0
  149. package/index.ts +14 -0
  150. package/log/config/log4js.json +55 -0
  151. package/model/RouteDefinition.ts +18 -0
  152. package/package.json +52 -0
  153. package/requiments/Glob.ts +9 -0
  154. package/requiments/ReflectUtil.ts +26 -0
  155. package/requiments/Utils.ts +57 -0
  156. package/tsconfig.json +18 -0
  157. package/validators/BooleanValidator.ts +0 -0
  158. package/validators/CompareValidator.ts +0 -0
  159. package/validators/DateValidator.ts +0 -0
  160. package/validators/EmailValidator.ts +0 -0
  161. package/validators/Validator.ts +27 -0
  162. package/web/IdentityInterface.ts +62 -0
  163. package/web/User.ts +96 -0
package/BaseChyz.ts ADDED
@@ -0,0 +1,316 @@
1
+ import 'reflect-metadata';
2
+ import {RouteDefinition} from "./model/RouteDefinition";
3
+ import {NextFunction, Request, Response} from "express";
4
+ import {Controller} from "./base/Controller";
5
+ import Utils from "./requiments/Utils";
6
+
7
+
8
+ const express = require("express");
9
+ const log4js = require("log4js");
10
+ const fs = require('fs');
11
+
12
+
13
+ var bodyParser = require('body-parser')
14
+ var methodOverride = require('method-override')
15
+
16
+ export {Request, Response, NextFunction} from "express";
17
+ export default class BaseChyz {
18
+ private config: any;
19
+ static app: string;
20
+ static express = express()
21
+ private _port: number = 3001;
22
+ static db: any;
23
+ static routes: any;
24
+ private _logConfig: any = require('./log/config/log4js.json') ?? {}
25
+ private _controllerpath: string = "Controllers"
26
+ private static controllers: Array<Controller> = []
27
+ public static components: any = {}
28
+
29
+
30
+
31
+
32
+ get logConfig(): any {
33
+ return this._logConfig;
34
+ }
35
+
36
+ set logConfig(value: any) {
37
+ this._logConfig = value;
38
+ }
39
+
40
+ get controllerpath(): string {
41
+ return this._controllerpath;
42
+ }
43
+
44
+ set controllerpath(value: string) {
45
+ this._controllerpath = value;
46
+ }
47
+
48
+ init() {
49
+ this.logProvider().level = log4js.levels.ALL;
50
+ this.logProvider().configure(this._logConfig);
51
+
52
+ /**
53
+ * set request id
54
+ */
55
+ Object.defineProperty(BaseChyz.express.request, 'reqId', {
56
+ configurable: true,
57
+ enumerable: true,
58
+ writable: true
59
+ })
60
+
61
+ Object.defineProperty(BaseChyz.express.request, 'user', {
62
+ configurable: true,
63
+ enumerable: true,
64
+ writable: true
65
+ })
66
+
67
+
68
+ Object.defineProperty(BaseChyz.express.request, 'identity', {
69
+ configurable: true,
70
+ enumerable: true,
71
+ writable: true
72
+ })
73
+
74
+
75
+ /**
76
+ * server port setting
77
+ */
78
+ if (this.config.hasOwnProperty("port"))
79
+ this.port = this.config.port;
80
+
81
+ /**
82
+ * controller path
83
+ */
84
+ if (this.config.controllerpath) {
85
+ this.controllerpath = this.config.controllerpath
86
+ }
87
+
88
+ /**
89
+ * Express Server
90
+ */
91
+ this.middleware()
92
+
93
+ /**
94
+ * Load Controller
95
+ */
96
+ this.loadController();
97
+
98
+
99
+ }
100
+
101
+ /**
102
+ * Listen port number
103
+ * Server port number get
104
+ */
105
+ get port(): number {
106
+ return this._port;
107
+ }
108
+
109
+ /**
110
+ * Listen port number
111
+ * Server port number setting
112
+ * @param value
113
+ */
114
+ set port(value: number) {
115
+ this._port = value;
116
+ }
117
+
118
+
119
+ app(config: any = {}): BaseChyz {
120
+
121
+ /**
122
+ * Config set
123
+ */
124
+ this.config = config;
125
+
126
+ this.init();
127
+
128
+ let components = Utils.findKeyValue(config, "components")
129
+ if (components) {
130
+ for (const componentsKey in components) {
131
+ let comp = components[componentsKey];
132
+ BaseChyz.debug("Create Component ", componentsKey)
133
+ BaseChyz.components[componentsKey] = Utils.createObject(new comp.class, comp);
134
+ BaseChyz.components[componentsKey]?.init();
135
+ }
136
+ }
137
+
138
+ return this;
139
+ }
140
+
141
+
142
+ public logProvider() {
143
+ return log4js;
144
+ }
145
+
146
+ public getLogger(){
147
+ return this.logProvider().getLogger(this.constructor.name);
148
+ }
149
+
150
+ static logs(...args: any[]) {
151
+ return log4js.getLogger(this.name);
152
+ }
153
+
154
+ public static trace(...args: any[]) {
155
+ BaseChyz.logs().fatal(...arguments)
156
+ }
157
+ public static debug(...args: any[]) {
158
+ BaseChyz.logs().debug(...arguments)
159
+ }
160
+ public static info(...args: any[]) {
161
+ BaseChyz.logs().info(...arguments)
162
+ }
163
+ public static warn(...args: any[]) {
164
+ BaseChyz.logs().warn(...arguments)
165
+ }
166
+
167
+ public static error(...args: any[]) {
168
+ BaseChyz.logs().error(...arguments)
169
+ }
170
+
171
+ public static fatal(...args: any[]) {
172
+ BaseChyz.logs().fatal(...arguments)
173
+ }
174
+
175
+
176
+
177
+
178
+ public static warning(...args: any[]) {
179
+ BaseChyz.logs().warn(...arguments)
180
+ }
181
+
182
+ public static t(text: string) {
183
+ return text;
184
+ }
185
+
186
+
187
+ public errorLogger(error: any, req: any, res: any, next: any) { // for logging errors
188
+ BaseChyz.error(error)
189
+ next(error) // forward to next middleware
190
+ }
191
+
192
+ public errorResponder(error: any, req: any, res: any, next: any) { // responding to client
193
+ if (error.type == 'redirect')
194
+ res.redirect('/error')
195
+ else if (error.type == 'time-out') // arbitrary condition check
196
+ res.status(408).json(error)
197
+ else
198
+ next(error) // forwarding exceptional case to fail-safe middleware
199
+ }
200
+
201
+
202
+ public errorHandler(err: any, req: any, res: any, next: any) {
203
+ if (res.headersSent) {
204
+ return next(err)
205
+ }
206
+ res.status(500)
207
+ res.json('error', {error: err})
208
+ }
209
+
210
+ public static getComponent(key: any) {
211
+ return BaseChyz.components[key] ?? null
212
+ }
213
+
214
+ /**
215
+ * load contoller
216
+ */
217
+ async loadController() {
218
+ let articlesEndpoints: string[] = [];
219
+ fs.readdirSync(`${this._controllerpath}/`).forEach((file: string) => {
220
+ let controller = require(`${this._controllerpath}/${file}`);
221
+
222
+ // This is our instantiated class
223
+ const instance: Controller = new controller();
224
+
225
+ BaseChyz.controllers.push(instance);
226
+
227
+ // The prefix saved to our controller
228
+ // @ts-ignore
229
+ const prefix = Reflect.getMetadata('prefix', controller);
230
+ // Our `routes` array containing all our routes for this controller
231
+ // @ts-ignore
232
+ const routes: Array<RouteDefinition> = Reflect.getMetadata('routes', controller);
233
+ BaseChyz.logs().debug("Controller load ", controller.name, `(${prefix})`)
234
+
235
+ if (routes) {
236
+ routes.forEach(route => {
237
+
238
+ let actionId = route.path == "/" || route.path == "" ? instance.defaultAction : route.path;
239
+ route.id = actionId;
240
+ BaseChyz.logs().debug("Controller route Path", prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`))
241
+
242
+ BaseChyz.express[route.requestMethod](prefix + (route.path.startsWith("/") ? route.path : `/${route.path}`),
243
+ async (req: Request, res: Response, next: NextFunction) => {
244
+ try {
245
+ BaseChyz.debug(`Call Request id ${instance.id}`)
246
+ await instance.beforeAction(route, req, res)
247
+ next()
248
+ } catch (e) {
249
+ BaseChyz.error(e);
250
+
251
+ res.status(e.statusCode || 500)
252
+ res.json({error: {code: e.statusCode || 500, name: e.name, message: e.message}})
253
+ // next(e)
254
+ }
255
+
256
+ },
257
+ async (req: Request, res: Response, next: NextFunction) => {
258
+ try {
259
+ // @ts-ignore
260
+ BaseChyz.debug("Request ID ", req.reqId)
261
+ // @ts-ignore
262
+ await instance[route.methodName](req, res, next);
263
+ instance.afterAction(route, req, res);
264
+ } catch (e) {
265
+ BaseChyz.error(e)
266
+ // next(e)
267
+ res.status(e.statusCode)
268
+ res.json({error: {code: e.statusCode, name: e.name, message: e.message}})
269
+ }
270
+ })
271
+
272
+
273
+ });
274
+ }
275
+ })
276
+ }
277
+
278
+ public middleware() {
279
+
280
+ BaseChyz.express.use(bodyParser.json())
281
+ BaseChyz.express.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
282
+ BaseChyz.express.use(methodOverride());
283
+ BaseChyz.express.use(this.errorResponder)
284
+ BaseChyz.express.use(this.errorHandler)
285
+
286
+
287
+ // CORS
288
+ BaseChyz.express.use(function (req: any, res: Response, next: any) {
289
+ // @ts-ignore
290
+ req.reqId = Utils.uniqueId("chyzzzz_")
291
+ res.setHeader('Content-Type', 'application/json');
292
+ res.setHeader("Access-Control-Allow-Origin", "*");
293
+ res.setHeader("Access-Control-Allow-Credentials", "true");
294
+ res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
295
+ res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization");
296
+ next();
297
+ });
298
+
299
+
300
+ }
301
+
302
+
303
+ public Start() {
304
+
305
+ BaseChyz.info("Express Server Starting")
306
+ BaseChyz.express.listen(this._port, () => {
307
+ BaseChyz.info("Express Server Start ")
308
+ BaseChyz.info(`Liten Port ${this._port}`)
309
+ })
310
+ return this;
311
+ }
312
+
313
+
314
+ }
315
+
316
+
package/Chyz.ts ADDED
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
3
+ * Author: Cihan Ozturk
4
+ * E-mail: cihan@chy.com.tr
5
+ * Github:https://github.com/cihan53/
6
+ */
7
+
8
+ import BaseChyz from "./BaseChyz";
9
+ const Chyz = new BaseChyz();
10
+
11
+ export default Chyz;
@@ -0,0 +1,121 @@
1
+ /*
2
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
3
+ * Author: Cihan Ozturk
4
+ * E-mail: cihan@chy.com.tr
5
+ * Github:https://github.com/cihan53/
6
+ */
7
+
8
+ import {Controller} from "../../base/Controller";
9
+ import BaseChyz from "../../BaseChyz";
10
+ // @ts-ignore
11
+ import {Request, Response} from "express";
12
+ import {get} from "../../decorator/get";
13
+ import {post} from "../../decorator/post";
14
+ import {controller} from "../../decorator/controller";
15
+ import {AccessControl} from "../../filters/AccessControl";
16
+ import {JwtHttpBearerAuth} from "../../filters/auth/JwtHttpBearerAuth";
17
+ import {Order} from "../Models/Order";
18
+ import {Customer} from "../Models/Customer";
19
+ import {ValidationHttpException} from "../../base/ValidationHttpException";
20
+ import {ValidationError} from "sequelize";
21
+ import {ForbiddenHttpException} from "../../base";
22
+
23
+ @controller("/api")
24
+ class ApiController extends Controller {
25
+
26
+ public myCheck(token) {
27
+ console.log("myyyyyyyyyyyyyyyyyyyyy")
28
+ }
29
+
30
+ public behaviors(): any[] {
31
+
32
+ return [{
33
+ 'authenticator': {
34
+ "class": JwtHttpBearerAuth,
35
+ // "auth": this.myCheck
36
+ },
37
+ 'access': {
38
+ 'class': AccessControl,
39
+ 'only': ['login', 'logout', 'signup'],
40
+ 'rules': [
41
+ {
42
+ 'allow': true,
43
+ 'actions': ['login', 'index'],
44
+ 'roles': ['?'],
45
+ },
46
+ {
47
+ 'allow': true,
48
+ 'actions': ['logout', "logout2"],
49
+ 'roles': ['@'],
50
+ }
51
+ ]
52
+ }
53
+ }]
54
+ }
55
+
56
+ @get("/")
57
+ Index(req: Request, res: Response) {
58
+
59
+ BaseChyz.logs().info("Site Controller Burası", this.id)
60
+ return res.json({message: "index sayfası"})
61
+ }
62
+
63
+ @post("orderCreate")
64
+ async Login(req: Request, res: Response) {
65
+ let data = req.body;
66
+ data.Customer.status = "true";
67
+ data.Customer["2fa"] = "true";
68
+
69
+ //Customer Model Create
70
+ let customer: Customer = new Customer();
71
+ //Order Model Create
72
+ let order: Order = new Order();
73
+
74
+
75
+ let transaction
76
+ try {
77
+ // get transaction
78
+ transaction = await BaseChyz.getComponent("db").transaction();
79
+
80
+
81
+ customer.load(data, "Customer");//load customer data
82
+ let cus: any = await customer.save({}, {transaction});
83
+
84
+ if (!cus) {
85
+ throw new ValidationHttpException(customer.errors);
86
+ }
87
+
88
+ data.Order.customer_id = cus.id;
89
+ // data.Order.total = 0;
90
+ // data.Order.status = true;
91
+ order.load(data, "Order");
92
+ let res1 = await order.save({}, {transaction});
93
+ if (!res1) {
94
+ throw new ValidationHttpException(order.errors);
95
+ }
96
+
97
+ // commit
98
+ await transaction.commit();
99
+
100
+ } catch (e) {
101
+ if (transaction) {
102
+ await transaction.rollback();
103
+ BaseChyz.warn("Rollback transaction")
104
+ }
105
+
106
+ if (e instanceof ValidationHttpException)
107
+ throw new ValidationHttpException(e.message)
108
+ else
109
+ throw new ForbiddenHttpException(e.message)
110
+ }
111
+ return res.send("Post Controller")
112
+ }
113
+
114
+
115
+ error(req: Request, res: Response) {
116
+ BaseChyz.logs().info("Error Sayfası")
117
+ return res.send("Post Controller")
118
+ }
119
+ }
120
+
121
+ module.exports = ApiController
@@ -0,0 +1,44 @@
1
+ /*
2
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
3
+ * Author: Cihan Ozturk
4
+ * E-mail: cihan@chy.com.tr
5
+ * Github:https://github.com/cihan53/
6
+ */
7
+
8
+ import {Controller} from "../../base/Controller";
9
+ import BaseChyz from "../../BaseChyz";
10
+ // @ts-ignore
11
+ import {Request, Response} from "express";
12
+ import {get} from "../../decorator/get";
13
+ import {post} from "../../decorator/post";
14
+ import {controller} from "../../decorator/controller";
15
+ import {AccessControl} from "../../filters/AccessControl";
16
+ import {JwtHttpBearerAuth} from "../../filters/auth/JwtHttpBearerAuth";
17
+ import Utils from "../../requiments/Utils";
18
+
19
+ @controller("/public")
20
+ class PublicController extends Controller {
21
+
22
+ public myCheck(token) {
23
+ console.log("myyyyyyyyyyyyyyyyyyyyy")
24
+ }
25
+
26
+ public behaviors(): any[] {
27
+
28
+ return [ ]
29
+ }
30
+
31
+ @get("/")
32
+ Index(req: Request, res: Response) {
33
+
34
+ BaseChyz.logs().info("Site Controller Burası", super.id)
35
+ return res.json({message: "index sayfası"})
36
+ }
37
+
38
+
39
+ error(req: Request, res: Response) {
40
+ BaseChyz.logs().info("Error Sayfası")
41
+ return res.send("Post Controller")
42
+ }
43
+ }
44
+ module.exports=PublicController
@@ -0,0 +1,127 @@
1
+ /*
2
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
3
+ * Author: Cihan Ozturk
4
+ * E-mail: cihan@chy.com.tr
5
+ * Github:https://github.com/cihan53/
6
+ */
7
+
8
+ import {Controller} from "../../base/Controller";
9
+ import BaseChyz from "../../BaseChyz";
10
+ // @ts-ignore
11
+ import {Request, Response} from "express";
12
+ import {get} from "../../decorator/get";
13
+ import {post} from "../../decorator/post";
14
+ import {controller} from "../../decorator/controller";
15
+ import {User} from "../Models/User";
16
+ import {ForbiddenHttpException} from "../../base";
17
+
18
+ const bcrypt = require('bcrypt');
19
+ const JsonWebToken = require("jsonwebtoken");
20
+
21
+
22
+ @controller("/site")
23
+ class SiteController extends Controller {
24
+
25
+ public myCheck(token) {
26
+ console.log("myyyyyyyyyyyyyyyyyyyyy")
27
+ }
28
+
29
+ // public behaviors(): any[] {
30
+ //
31
+ // return [{
32
+ // // 'authenticator': {
33
+ // // "class": JwtHttpBearerAuth,
34
+ // // // "auth": this.myCheck
35
+ // // },
36
+ // 'access': {
37
+ // 'class': AccessControl,
38
+ // 'only': ['login', 'logout','index' ],
39
+ // 'rules': [
40
+ // {
41
+ // 'allow': false,
42
+ // 'actions': ['login', 'index' ],
43
+ // 'roles': ['?'],
44
+ // },
45
+ // {
46
+ // 'allow': true,
47
+ // 'actions': ['logout', "logout2"],
48
+ // 'roles': ['@'],
49
+ // }
50
+ // ]
51
+ // }
52
+ // }]
53
+ // }
54
+
55
+ @get("index")
56
+ Index(req: Request, res: Response) {
57
+
58
+ BaseChyz.logs().info("Site Controller Burası", this.id)
59
+ return res.json({message: "index sayfası"})
60
+ }
61
+
62
+ @post("login")
63
+ async login(req: Request, res: Response) {
64
+ let UserModel: User = new User();
65
+ let token
66
+ let username = req.body.username;
67
+ let password = req.body.password;
68
+
69
+ let user = await UserModel.findOne({where: {username: username}})
70
+ if (user) {
71
+ BaseChyz.debug("Db found user", username)
72
+ const match = await bcrypt.compare(password, user.password);
73
+ if (match) {
74
+ BaseChyz.debug("Db user verify", username)
75
+ //login
76
+ // @ts-ignore
77
+ let xForwardedFor = (req.headers['x-forwarded-for'] || '').replace(/:\d+$/, '');
78
+ let ip = xForwardedFor || req.socket.remoteAddress;
79
+ var source: string = req.headers['user-agent'] || '';
80
+ if (req.headers['x-ucbrowser-ua']) { //special case of UC Browser
81
+ source = req.headers['x-ucbrowser-ua']+"";
82
+ }
83
+ token = await JsonWebToken.sign({
84
+ user: user.id,
85
+ ip: ip,
86
+ agent: source,
87
+ }, user.salt_text, {expiresIn: '1h'});
88
+
89
+ BaseChyz.debug("Db user create access token", username,"expiresIn","1h")
90
+ return res.json({token: token})
91
+ } else {
92
+ let error: any = new ForbiddenHttpException(BaseChyz.t('You are not allowed to perform this action.'))
93
+ res.status(500).json( error.toJSON())
94
+ }
95
+ } else {
96
+ let error: any = new ForbiddenHttpException(BaseChyz.t('You are not allowed to perform this action.'))
97
+ res.status(500).json( error.toJSON())
98
+ }
99
+
100
+
101
+ }
102
+
103
+ @get("logout")
104
+ logout(req: Request, res: Response) {
105
+
106
+ // @ts-ignore
107
+ let identity = req.user ?? BaseChyz.getComponent("user").getIdentity();
108
+ // console.log("logout2", identity.id)
109
+ console.log(identity)
110
+
111
+ BaseChyz.logs().info("Logout Controller")
112
+ return res.send("Logout Controller")
113
+ }
114
+
115
+ @get("signup")
116
+ logout2(req: Request, res: Response) {
117
+
118
+
119
+ return res.send("Logout Controller")
120
+ }
121
+
122
+ error(req: Request, res: Response) {
123
+ BaseChyz.logs().info("Error Sayfası")
124
+ return res.send("Post Controller")
125
+ }
126
+ }
127
+ module.exports=SiteController