chyz 2.0.1-rc.4 → 2.0.1-rc.6

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/README.md CHANGED
@@ -1,518 +1,518 @@
1
- Hızlı şekilde microservis hazırlama için geliştirmeye başladım<br>
2
-
3
- Temel olarak yii2 php framework'ten örnekler alındı<br>
4
-
5
- Temel olarak basit bir Controller geliştirildi, ayrıca authentication geliştirildi.<br>
6
-
7
- Klasör Yapısı<br>
8
- *---Controllers <br>
9
- *---Models<br>
10
- *---Log<br>
11
- index.ts<br>
12
-
13
- `##Başlangıç<br>
14
- yarn start
15
-
16
- ## index.ts alanlar düzenlenmeli.
17
-
18
- ```typescript
19
-
20
- import {BaseChyz} from "../index";
21
-
22
- require('dotenv-flow').config();
23
- import Chyz ,{ DbConnection, BaseChyz} from "chyz/dist/";
24
- import {AuthManager} from "chyz/dist/rbac/AuthManager"
25
- import {WebUser} from "chyz/dist/web/WebUser";
26
- import {User as Identity} from "./Models/User";
27
-
28
-
29
- let config = {
30
- port: process.env.PORT || 8870,
31
- controllerpath: "Examples\\Controllers",
32
- components: {
33
- authManager: {
34
- class: AuthManager,
35
- },
36
- db: {
37
- class: DbConnection,
38
- database: process.env.DBDATABASE,
39
- username: process.env.DBUSER,
40
- password: process.env.DBPASS,
41
- options: {
42
- host: process.env.DBHOST,
43
- dialect: 'postgres', /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
44
- // disable logging; default: console.log
45
- logging: (msg: any) => BaseChyz.debug(msg)
46
- }
47
- },
48
- user: {
49
- 'class': WebUser,
50
- 'identityClass': User
51
- }
52
- }
53
-
54
- }
55
- Chyz.app(config).then((server)=>server.Start());
56
- ```
57
-
58
- ##Controller
59
- Basit şekilde kontroller oluşturulabilir.
60
- ```typescript
61
- /*
62
- *
63
- * Copyright (c) 2021-2021.. Chy Bilgisayar Bilisim
64
- * Author: Cihan Ozturk
65
- * E-mail: cihan@chy.com.tr
66
- * Github:https://github.com/cihan53/
67
- *
68
- */
69
-
70
- import {AccessControl, BaseChyz, JwtHttpBearerAuth, ModelManager, Request, Response,} from "chyz/dist";
71
- import {ForbiddenHttpException, Model, NotFoundHttpException, ValidationHttpException} from "chyz/dist/base";
72
-
73
- import Utils from 'chyz/dist/requiments/Utils';
74
- import {controller, get, post} from "chyz/dist/decorator";
75
- import {Controller} from "chyz/dist/base/Controller";
76
- import * as Util from "util";
77
- import {uid} from "uid";
78
-
79
- import {User} from "../Models/User";
80
- import {AuthManager} from "../Lib/AuthManager";
81
- import {CategoriesClass} from "../Models/Categories";
82
-
83
-
84
- const keygen = require('ssh-keygen');
85
- const os = require('os');
86
- const bcrypt = require('bcrypt');
87
- const JsonWebToken = require("jsonwebtoken");
88
- const {Op} = require("sequelize");
89
-
90
-
91
- @controller("/api")
92
- class ApiController extends Controller {
93
-
94
- public myCheck(token) {
95
- console.log("myyyyyyyyyyyyyyyyyyyyy")
96
- }
97
-
98
- public behaviors(): any[] {
99
-
100
- return [{
101
- 'authenticator': {
102
- "class": JwtHttpBearerAuth,
103
- // "auth": this.myCheck
104
- },
105
- 'access': {
106
- 'class': AccessControl,
107
- 'only': ['order/list' ],
108
- 'rules': [
109
-
110
- {
111
- 'allow': true,
112
- 'actions': ['order/list' ],
113
- 'roles': ['editor'],
114
- }
115
- ]
116
- }
117
- }]
118
- }
119
-
120
- @get("/")
121
- Index(req: Request, res: Response) {
122
-
123
- BaseChyz.logs().info("Site Controller Burası", this.id)
124
- return res.json({message: "index sayfası"})
125
- }
126
-
127
- @post("orderCreate")
128
- async Login(req: Request, res: Response) {
129
- let data = req.body;
130
- data.Customer.status = "true";
131
-
132
- //Customer Model Create
133
- let customer = ModelManager.Customer.save();
134
- //Order Model Create
135
- let order = ModelManager.Order;
136
-
137
-
138
- let transaction
139
- try {
140
- // get transaction
141
- transaction = await BaseChyz.getComponent("db").transaction();
142
- customer.load(data, "Customer");//load customer data
143
- let cus: any = await customer.save({}, {transaction});
144
-
145
- if (!cus) {
146
- throw new ValidationHttpException(customer.errors);
147
- }
148
-
149
- data.Order.customer_id = cus.id;
150
-
151
- order.load(data, "Order");
152
- let res1 = await order.save({}, {transaction});
153
- if (!res1) {
154
- throw new ValidationHttpException(order.errors);
155
- }
156
-
157
- // commit
158
- await transaction.commit();
159
-
160
- } catch (e) {
161
- if (transaction) {
162
- await transaction.rollback();
163
- BaseChyz.warn("Rollback transaction")
164
- }
165
-
166
- if (e instanceof ValidationHttpException)
167
- throw new ValidationHttpException(e.message)
168
- else
169
- throw new ForbiddenHttpException(e.message)
170
- }
171
- return res.send("Post Controller")
172
- }
173
-
174
-
175
- @get("order/list")
176
- async listOrder(req: Request, res: Response) {
177
- const {Products}: { Products: ProductsClass } = ModelManager;
178
- let product = await Products.findAll( );
179
- return res.json(product)
180
-
181
- }
182
-
183
- @get("categories")
184
- async Categories(req: Request, res: Response) {
185
- let product = await ModelManager.Categories.findAll({
186
- include: [
187
- {
188
- model: ModelManager.Products.model(),
189
- }
190
- ]
191
- });
192
- return res.json(product)
193
-
194
- }
195
-
196
- error(req: Request, res: Response) {
197
- BaseChyz.logs().info("Error Sayfası")
198
- return res.send("Post Controller")
199
- }
200
- }
201
-
202
- module.exports = ApiController
203
-
204
- ```
205
-
206
-
207
- ## Create Model
208
-
209
- Veritabanı işlemleri için model oluşturma, sequelize desteklidir.
210
-
211
- Model adı "**Class**" şeklinde bitmeli.
212
-
213
- Örnek = "ModelName**Class**"
214
-
215
- ```typescript
216
- import {Model, DataTypes} from "chyz/base/Model";
217
-
218
- export class CustomerCLass extends Model {
219
- public tableName() {
220
- return 'customer';
221
- }
222
-
223
- public attributes() {
224
- return {
225
- username: {
226
- type: DataTypes.STRING,
227
- allowNull: false,
228
- validate: {
229
- notEmpty: true,
230
- len: [4, 255],
231
- }
232
- },
233
- email: {
234
- type: DataTypes.STRING,
235
- validate: {
236
- isEmail: true
237
- }
238
- },
239
- firstname: {
240
- type: DataTypes.STRING,
241
- allowNull: false
242
- },
243
- lastname: {
244
- type: DataTypes.STRING,
245
- },
246
- }
247
- }
248
-
249
- }
250
-
251
-
252
- ```
253
- ````typescript
254
-
255
- export class ProductsClass extends Model {
256
- [x: string]: any;
257
-
258
- tableName() {
259
- return 'products';
260
- }
261
-
262
- attributes() {
263
- return {
264
- // Model attributes are defined here
265
- title: {
266
- type: DataTypes.STRING,
267
- allowNull: false
268
- },
269
- model_id: {
270
- type: DataTypes.INTEGER,
271
- allowNull: false
272
- },
273
- properties: {
274
- type: DataTypes.STRING,
275
- allowNull: false
276
- }
277
-
278
- }
279
- }
280
-
281
- relations(): Relation[] {
282
- return [
283
- {
284
- type: "hasOne",
285
- foreignKey: "id",
286
- sourceKey: "customer_id",
287
- model: Customer.model()
288
- }
289
- ]
290
- }
291
- }
292
-
293
- /**
294
- *
295
- */
296
- export class CategoriesClass extends Model {
297
- [x: string]: any;
298
-
299
- alias() {
300
- return "c"
301
- }
302
-
303
- tableName() {
304
- return 'categories';
305
- }
306
- attributes() {
307
- return {
308
- // Model attributes are defined here
309
- title: {
310
- type: DataTypes.STRING,
311
- allowNull: false
312
- },
313
- properties: {
314
- type: DataTypes.STRING,
315
- allowNull: false
316
- }
317
-
318
- }
319
- }
320
- relations(): Relation[] {
321
- return [
322
- {
323
- type: "belongsToMany",
324
- foreignKey: "category_id",
325
- sourceKey: "id",
326
- as: 'product',
327
- model: ModelManager.Products.model(),
328
- through: ModelManager.ProductToCategories.model()
329
- }
330
- ]
331
- }
332
-
333
- }
334
-
335
-
336
- ````
337
-
338
- ## Http POST ve GET verilerini model'e yükleme
339
-
340
- ````typescript
341
-
342
- /**
343
- * post data
344
- * {
345
- * "Customer":{
346
- * "firstname":"cihan",
347
- * "lastname":"ozturk"
348
- * ....
349
- * }
350
- * }
351
- * @type {Customer}
352
- */
353
- import { ModelManager} from "chyz/dist";
354
- import {Customer} from "./Customer";
355
-
356
- //Customer Model Create
357
- let customer: Customer = ModelManager.Customer;
358
- customer.load(req.body, "Customer");//load customer data
359
- let cus: any = await customer.save();
360
-
361
-
362
- ````
363
- ## Transaction
364
- Transaction oluşturma
365
-
366
-
367
- ```typescript
368
- let transaction
369
- try {
370
- // get transaction
371
- transaction = await BaseChyz.getComponent("db").transaction();
372
- //Customer Model Create
373
- let customer: Customer = ModelManager.Customer;
374
- customer.load(data, "Customer");//load customer data
375
- let cus: any = await customer.save({}, {transaction});
376
- if (!cus) {
377
- throw new ValidationHttpException(customer.errors);
378
- }
379
- } catch (e) {
380
- if (transaction) {
381
- await transaction.rollback();
382
- BaseChyz.warn("Rollback transaction");
383
- }
384
-
385
- }
386
- ```
387
-
388
- ## Yetkilendirme için kullanıcı modeli
389
-
390
- ```typescript
391
- /*
392
- * Copyright (c) 2021. Chy Bilgisayar Bilisim
393
- * Author: Cihan Ozturk
394
- * E-mail: cihan@chy.com.tr
395
- * Github:https://github.com/cihan53/
396
- */
397
- import {IdentityInterface} from "chyz/web/IdentityInterface";
398
- // @ts-ignore
399
- import {DataTypes} from "chyz/base";
400
- import {Model} from "chyz/base";
401
- import BaseChyz from "chyz/BaseChyz";
402
-
403
- const bcrypt = require('bcrypt');
404
- const JsonWebToken = require("jsonwebtoken");
405
-
406
- export class User extends Model implements IdentityInterface {
407
- public tableName() {
408
- return 'users';
409
- }
410
- findIdentity(id: number) {
411
- throw new Error("Method not implemented.");
412
- }
413
-
414
- getId(): number {
415
- throw new Error("Method not implemented.");
416
- }
417
-
418
- getAuthKey(): string {
419
- throw new Error("Method not implemented.");
420
- }
421
-
422
- validateAuthKey(authKey: string): boolean {
423
- throw new Error("Method not implemented.");
424
- }
425
-
426
- /**
427
- * Returns auth manager associated with the user component.
428
- *
429
- * By default this is the `authManager` application component.
430
- * You may override this method to return a different auth manager instance if needed.
431
- */
432
- protected getAuthManager() {
433
- return BaseChyz.getComponent("authManager");
434
- }
435
-
436
- /**
437
- * Returns the access checker used for checking access.
438
- * @return CheckAccessInterface
439
- */
440
- protected getAccessChecker() {
441
- return this.accessChecker !== null ? this.accessChecker : this.getAuthManager();
442
- }
443
-
444
- /**
445
- *
446
- * @param permissionName
447
- * @param params
448
- * @param allowCaching
449
- */
450
- public async can(permissionName, params: any[] = [], allowCaching: boolean = true) {
451
- let accessChecker;
452
- if ((accessChecker = this.getAccessChecker()) === null) {
453
- return false;
454
- }
455
-
456
- let access = await accessChecker.checkAccess(this.getId(), permissionName, params);
457
- this._access[permissionName] = access;
458
- if (allowCaching && Utils.isEmpty(params)) {
459
-
460
- }
461
- return access;
462
- }
463
-
464
- public attributes() {
465
- return {
466
- // Model attributes are defined here
467
- username: {
468
- type: DataTypes.STRING,
469
- allowNull: false
470
- },
471
- password: {
472
- type: DataTypes.STRING,
473
- allowNull: false
474
- },
475
- user_role: {
476
- type: DataTypes.STRING,
477
- allowNull: false
478
- },
479
- salt_text: {
480
- type: DataTypes.STRING
481
- // allowNull defaults to true
482
- }
483
- }
484
- }
485
-
486
- async findIdentityByAccessToken(token, type) {
487
-
488
-
489
- let decoded = JsonWebToken.decode(token, {complete: true})
490
- if (!decoded.payload.user) {
491
- return null;
492
- }
493
- let identity = await this.findOne({where: {id: parseInt(decoded.payload.user)}});
494
- if(identity){
495
- BaseChyz.debug("Find Identity By AccessToken: User Found", decoded.payload)
496
- try {
497
- JsonWebToken.verify(token, identity.salt_text);
498
- this.setIdentity(identity);
499
- BaseChyz.debug("Find Identity By AccessToken: User Verify Success")
500
- return this;
501
- } catch(err) {
502
- if (err.name == "TokenExpiredError")
503
- BaseChyz.debug("Find Identity By AccessToken: Token Expired")
504
- else
505
- BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
506
- return null;
507
- }
508
- }
509
- BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
510
- return null;
511
- }
512
-
513
-
514
- }
515
-
516
-
517
-
518
- ```
1
+ Hızlı şekilde microservis hazırlama için geliştirmeye başladım<br>
2
+
3
+ Temel olarak yii2 php framework'ten örnekler alındı<br>
4
+
5
+ Temel olarak basit bir Controller geliştirildi, ayrıca authentication geliştirildi.<br>
6
+
7
+ Klasör Yapısı<br>
8
+ *---Controllers <br>
9
+ *---Models<br>
10
+ *---Log<br>
11
+ index.ts<br>
12
+
13
+ `##Başlangıç<br>
14
+ yarn start
15
+
16
+ ## index.ts alanlar düzenlenmeli.
17
+
18
+ ```typescript
19
+
20
+ import {BaseChyz} from "../index";
21
+
22
+ require('dotenv-flow').config();
23
+ import Chyz ,{ DbConnection, BaseChyz} from "chyz/dist/";
24
+ import {AuthManager} from "chyz/dist/rbac/AuthManager"
25
+ import {WebUser} from "chyz/dist/web/WebUser";
26
+ import {User as Identity} from "./Models/User";
27
+
28
+
29
+ let config = {
30
+ port: process.env.PORT || 8870,
31
+ controllerpath: "Examples\\Controllers",
32
+ components: {
33
+ authManager: {
34
+ class: AuthManager,
35
+ },
36
+ db: {
37
+ class: DbConnection,
38
+ database: process.env.DBDATABASE,
39
+ username: process.env.DBUSER,
40
+ password: process.env.DBPASS,
41
+ options: {
42
+ host: process.env.DBHOST,
43
+ dialect: 'postgres', /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
44
+ // disable logging; default: console.log
45
+ logging: (msg: any) => BaseChyz.debug(msg)
46
+ }
47
+ },
48
+ user: {
49
+ 'class': WebUser,
50
+ 'identityClass': User
51
+ }
52
+ }
53
+
54
+ }
55
+ Chyz.app(config).then((server)=>server.Start());
56
+ ```
57
+
58
+ ##Controller
59
+ Basit şekilde kontroller oluşturulabilir.
60
+ ```typescript
61
+ /*
62
+ *
63
+ * Copyright (c) 2021-2021.. Chy Bilgisayar Bilisim
64
+ * Author: Cihan Ozturk
65
+ * E-mail: cihan@chy.com.tr
66
+ * Github:https://github.com/cihan53/
67
+ *
68
+ */
69
+
70
+ import {AccessControl, BaseChyz, JwtHttpBearerAuth, ModelManager, Request, Response,} from "chyz/dist";
71
+ import {ForbiddenHttpException, Model, NotFoundHttpException, ValidationHttpException} from "chyz/dist/base";
72
+
73
+ import Utils from 'chyz/dist/requiments/Utils';
74
+ import {controller, get, post} from "chyz/dist/decorator";
75
+ import {Controller} from "chyz/dist/base/Controller";
76
+ import * as Util from "util";
77
+ import {uid} from "uid";
78
+
79
+ import {User} from "../Models/User";
80
+ import {AuthManager} from "../Lib/AuthManager";
81
+ import {CategoriesClass} from "../Models/Categories";
82
+
83
+
84
+ const keygen = require('ssh-keygen');
85
+ const os = require('os');
86
+ const bcrypt = require('bcrypt');
87
+ const JsonWebToken = require("jsonwebtoken");
88
+ const {Op} = require("sequelize");
89
+
90
+
91
+ @controller("/api")
92
+ class ApiController extends Controller {
93
+
94
+ public myCheck(token) {
95
+ console.log("myyyyyyyyyyyyyyyyyyyyy")
96
+ }
97
+
98
+ public behaviors(): any[] {
99
+
100
+ return [{
101
+ 'authenticator': {
102
+ "class": JwtHttpBearerAuth,
103
+ // "auth": this.myCheck
104
+ },
105
+ 'access': {
106
+ 'class': AccessControl,
107
+ 'only': ['order/list' ],
108
+ 'rules': [
109
+
110
+ {
111
+ 'allow': true,
112
+ 'actions': ['order/list' ],
113
+ 'roles': ['editor'],
114
+ }
115
+ ]
116
+ }
117
+ }]
118
+ }
119
+
120
+ @get("/")
121
+ Index(req: Request, res: Response) {
122
+
123
+ BaseChyz.logs().info("Site Controller Burası", this.id)
124
+ return res.json({message: "index sayfası"})
125
+ }
126
+
127
+ @post("orderCreate")
128
+ async Login(req: Request, res: Response) {
129
+ let data = req.body;
130
+ data.Customer.status = "true";
131
+
132
+ //Customer Model Create
133
+ let customer = ModelManager.Customer.save();
134
+ //Order Model Create
135
+ let order = ModelManager.Order;
136
+
137
+
138
+ let transaction
139
+ try {
140
+ // get transaction
141
+ transaction = await BaseChyz.getComponent("db").transaction();
142
+ customer.load(data, "Customer");//load customer data
143
+ let cus: any = await customer.save({}, {transaction});
144
+
145
+ if (!cus) {
146
+ throw new ValidationHttpException(customer.errors);
147
+ }
148
+
149
+ data.Order.customer_id = cus.id;
150
+
151
+ order.load(data, "Order");
152
+ let res1 = await order.save({}, {transaction});
153
+ if (!res1) {
154
+ throw new ValidationHttpException(order.errors);
155
+ }
156
+
157
+ // commit
158
+ await transaction.commit();
159
+
160
+ } catch (e) {
161
+ if (transaction) {
162
+ await transaction.rollback();
163
+ BaseChyz.warn("Rollback transaction")
164
+ }
165
+
166
+ if (e instanceof ValidationHttpException)
167
+ throw new ValidationHttpException(e.message)
168
+ else
169
+ throw new ForbiddenHttpException(e.message)
170
+ }
171
+ return res.send("Post Controller")
172
+ }
173
+
174
+
175
+ @get("order/list")
176
+ async listOrder(req: Request, res: Response) {
177
+ const {Products}: { Products: ProductsClass } = ModelManager;
178
+ let product = await Products.findAll( );
179
+ return res.json(product)
180
+
181
+ }
182
+
183
+ @get("categories")
184
+ async Categories(req: Request, res: Response) {
185
+ let product = await ModelManager.Categories.findAll({
186
+ include: [
187
+ {
188
+ model: ModelManager.Products.model(),
189
+ }
190
+ ]
191
+ });
192
+ return res.json(product)
193
+
194
+ }
195
+
196
+ error(req: Request, res: Response) {
197
+ BaseChyz.logs().info("Error Sayfası")
198
+ return res.send("Post Controller")
199
+ }
200
+ }
201
+
202
+ module.exports = ApiController
203
+
204
+ ```
205
+
206
+
207
+ ## Create Model
208
+
209
+ Veritabanı işlemleri için model oluşturma, sequelize desteklidir.
210
+
211
+ Model adı "**Class**" şeklinde bitmeli.
212
+
213
+ Örnek = "ModelName**Class**"
214
+
215
+ ```typescript
216
+ import {Model, DataTypes} from "chyz/base/Model";
217
+
218
+ export class CustomerCLass extends Model {
219
+ public tableName() {
220
+ return 'customer';
221
+ }
222
+
223
+ public attributes() {
224
+ return {
225
+ username: {
226
+ type: DataTypes.STRING,
227
+ allowNull: false,
228
+ validate: {
229
+ notEmpty: true,
230
+ len: [4, 255],
231
+ }
232
+ },
233
+ email: {
234
+ type: DataTypes.STRING,
235
+ validate: {
236
+ isEmail: true
237
+ }
238
+ },
239
+ firstname: {
240
+ type: DataTypes.STRING,
241
+ allowNull: false
242
+ },
243
+ lastname: {
244
+ type: DataTypes.STRING,
245
+ },
246
+ }
247
+ }
248
+
249
+ }
250
+
251
+
252
+ ```
253
+ ````typescript
254
+
255
+ export class ProductsClass extends Model {
256
+ [x: string]: any;
257
+
258
+ tableName() {
259
+ return 'products';
260
+ }
261
+
262
+ attributes() {
263
+ return {
264
+ // Model attributes are defined here
265
+ title: {
266
+ type: DataTypes.STRING,
267
+ allowNull: false
268
+ },
269
+ model_id: {
270
+ type: DataTypes.INTEGER,
271
+ allowNull: false
272
+ },
273
+ properties: {
274
+ type: DataTypes.STRING,
275
+ allowNull: false
276
+ }
277
+
278
+ }
279
+ }
280
+
281
+ relations(): Relation[] {
282
+ return [
283
+ {
284
+ type: "hasOne",
285
+ foreignKey: "id",
286
+ sourceKey: "customer_id",
287
+ model: Customer.model()
288
+ }
289
+ ]
290
+ }
291
+ }
292
+
293
+ /**
294
+ *
295
+ */
296
+ export class CategoriesClass extends Model {
297
+ [x: string]: any;
298
+
299
+ alias() {
300
+ return "c"
301
+ }
302
+
303
+ tableName() {
304
+ return 'categories';
305
+ }
306
+ attributes() {
307
+ return {
308
+ // Model attributes are defined here
309
+ title: {
310
+ type: DataTypes.STRING,
311
+ allowNull: false
312
+ },
313
+ properties: {
314
+ type: DataTypes.STRING,
315
+ allowNull: false
316
+ }
317
+
318
+ }
319
+ }
320
+ relations(): Relation[] {
321
+ return [
322
+ {
323
+ type: "belongsToMany",
324
+ foreignKey: "category_id",
325
+ sourceKey: "id",
326
+ as: 'product',
327
+ model: ModelManager.Products.model(),
328
+ through: ModelManager.ProductToCategories.model()
329
+ }
330
+ ]
331
+ }
332
+
333
+ }
334
+
335
+
336
+ ````
337
+
338
+ ## Http POST ve GET verilerini model'e yükleme
339
+
340
+ ````typescript
341
+
342
+ /**
343
+ * post data
344
+ * {
345
+ * "Customer":{
346
+ * "firstname":"cihan",
347
+ * "lastname":"ozturk"
348
+ * ....
349
+ * }
350
+ * }
351
+ * @type {Customer}
352
+ */
353
+ import { ModelManager} from "chyz/dist";
354
+ import {Customer} from "./Customer";
355
+
356
+ //Customer Model Create
357
+ let customer: Customer = ModelManager.Customer;
358
+ customer.load(req.body, "Customer");//load customer data
359
+ let cus: any = await customer.save();
360
+
361
+
362
+ ````
363
+ ## Transaction
364
+ Transaction oluşturma
365
+
366
+
367
+ ```typescript
368
+ let transaction
369
+ try {
370
+ // get transaction
371
+ transaction = await BaseChyz.getComponent("db").transaction();
372
+ //Customer Model Create
373
+ let customer: Customer = ModelManager.Customer;
374
+ customer.load(data, "Customer");//load customer data
375
+ let cus: any = await customer.save({}, {transaction});
376
+ if (!cus) {
377
+ throw new ValidationHttpException(customer.errors);
378
+ }
379
+ } catch (e) {
380
+ if (transaction) {
381
+ await transaction.rollback();
382
+ BaseChyz.warn("Rollback transaction");
383
+ }
384
+
385
+ }
386
+ ```
387
+
388
+ ## Yetkilendirme için kullanıcı modeli
389
+
390
+ ```typescript
391
+ /*
392
+ * Copyright (c) 2021. Chy Bilgisayar Bilisim
393
+ * Author: Cihan Ozturk
394
+ * E-mail: cihan@chy.com.tr
395
+ * Github:https://github.com/cihan53/
396
+ */
397
+ import {IdentityInterface} from "chyz/web/IdentityInterface";
398
+ // @ts-ignore
399
+ import {DataTypes} from "chyz/base";
400
+ import {Model} from "chyz/base";
401
+ import BaseChyz from "chyz/BaseChyz";
402
+
403
+ const bcrypt = require('bcrypt');
404
+ const JsonWebToken = require("jsonwebtoken");
405
+
406
+ export class User extends Model implements IdentityInterface {
407
+ public tableName() {
408
+ return 'users';
409
+ }
410
+ findIdentity(id: number) {
411
+ throw new Error("Method not implemented.");
412
+ }
413
+
414
+ getId(): number {
415
+ throw new Error("Method not implemented.");
416
+ }
417
+
418
+ getAuthKey(): string {
419
+ throw new Error("Method not implemented.");
420
+ }
421
+
422
+ validateAuthKey(authKey: string): boolean {
423
+ throw new Error("Method not implemented.");
424
+ }
425
+
426
+ /**
427
+ * Returns auth manager associated with the user component.
428
+ *
429
+ * By default this is the `authManager` application component.
430
+ * You may override this method to return a different auth manager instance if needed.
431
+ */
432
+ protected getAuthManager() {
433
+ return BaseChyz.getComponent("authManager");
434
+ }
435
+
436
+ /**
437
+ * Returns the access checker used for checking access.
438
+ * @return CheckAccessInterface
439
+ */
440
+ protected getAccessChecker() {
441
+ return this.accessChecker !== null ? this.accessChecker : this.getAuthManager();
442
+ }
443
+
444
+ /**
445
+ *
446
+ * @param permissionName
447
+ * @param params
448
+ * @param allowCaching
449
+ */
450
+ public async can(permissionName, params: any[] = [], allowCaching: boolean = true) {
451
+ let accessChecker;
452
+ if ((accessChecker = this.getAccessChecker()) === null) {
453
+ return false;
454
+ }
455
+
456
+ let access = await accessChecker.checkAccess(this.getId(), permissionName, params);
457
+ this._access[permissionName] = access;
458
+ if (allowCaching && Utils.isEmpty(params)) {
459
+
460
+ }
461
+ return access;
462
+ }
463
+
464
+ public attributes() {
465
+ return {
466
+ // Model attributes are defined here
467
+ username: {
468
+ type: DataTypes.STRING,
469
+ allowNull: false
470
+ },
471
+ password: {
472
+ type: DataTypes.STRING,
473
+ allowNull: false
474
+ },
475
+ user_role: {
476
+ type: DataTypes.STRING,
477
+ allowNull: false
478
+ },
479
+ salt_text: {
480
+ type: DataTypes.STRING
481
+ // allowNull defaults to true
482
+ }
483
+ }
484
+ }
485
+
486
+ async findIdentityByAccessToken(token, type) {
487
+
488
+
489
+ let decoded = JsonWebToken.decode(token, {complete: true})
490
+ if (!decoded.payload.user) {
491
+ return null;
492
+ }
493
+ let identity = await this.findOne({where: {id: parseInt(decoded.payload.user)}});
494
+ if(identity){
495
+ BaseChyz.debug("Find Identity By AccessToken: User Found", decoded.payload)
496
+ try {
497
+ JsonWebToken.verify(token, identity.salt_text);
498
+ this.setIdentity(identity);
499
+ BaseChyz.debug("Find Identity By AccessToken: User Verify Success")
500
+ return this;
501
+ } catch(err) {
502
+ if (err.name == "TokenExpiredError")
503
+ BaseChyz.debug("Find Identity By AccessToken: Token Expired")
504
+ else
505
+ BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
506
+ return null;
507
+ }
508
+ }
509
+ BaseChyz.debug("Find Identity By AccessToken: User Verify Failed")
510
+ return null;
511
+ }
512
+
513
+
514
+ }
515
+
516
+
517
+
518
+ ```