-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathhints-module.patch
More file actions
903 lines (882 loc) · 62.1 KB
/
Copy pathhints-module.patch
File metadata and controls
903 lines (882 loc) · 62.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
From 9969ce070b7244b74d4afb5cd0823b5f86b0610f Mon Sep 17 00:00:00 2001
From: martinshub-tech <jambemail2003@gmail.com>
Date: Wed, 17 Jun 2026 00:08:17 +0100
Subject: [PATCH 1/3] Add hints module with hint reveal endpoints and scoring
integration placeholder
---
src/auth/guards/admin.guard.ts | 9 +++++
src/hints/dto/reveal-hint.dto.ts | 4 +++
src/hints/entities/hint.entity.ts | 13 +++++++
src/hints/hints.controller.ts | 21 ++++++++++++
src/hints/hints.module.ts | 10 ++++++
src/hints/hints.service.ts | 56 +++++++++++++++++++++++++++++++
6 files changed, 113 insertions(+)
create mode 100644 src/auth/guards/admin.guard.ts
create mode 100644 src/hints/dto/reveal-hint.dto.ts
create mode 100644 src/hints/entities/hint.entity.ts
create mode 100644 src/hints/hints.controller.ts
create mode 100644 src/hints/hints.module.ts
create mode 100644 src/hints/hints.service.ts
diff --git a/src/auth/guards/admin.guard.ts b/src/auth/guards/admin.guard.ts
new file mode 100644
index 0000000..bc1a204
--- /dev/null
+++ b/src/auth/guards/admin.guard.ts
@@ -0,0 +1,9 @@
+import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
+
+@Injectable()
+export class AdminGuard implements CanActivate {
+ canActivate(context: ExecutionContext): boolean {
+ // Placeholder: allow all requests. Replace with real admin check.
+ return true;
+ }
+}
diff --git a/src/hints/dto/reveal-hint.dto.ts b/src/hints/dto/reveal-hint.dto.ts
new file mode 100644
index 0000000..40ffb07
--- /dev/null
+++ b/src/hints/dto/reveal-hint.dto.ts
@@ -0,0 +1,4 @@
+export class RevealHintDto {
+ sessionId: string;
+ puzzleId: string;
+}
diff --git a/src/hints/entities/hint.entity.ts b/src/hints/entities/hint.entity.ts
new file mode 100644
index 0000000..b654f20
--- /dev/null
+++ b/src/hints/entities/hint.entity.ts
@@ -0,0 +1,13 @@
+export class Hint {
+ id: string;
+ puzzleId: string;
+ order: number; // 1-3
+ content: string;
+
+ constructor(id: string, puzzleId: string, order: number, content: string) {
+ this.id = id;
+ this.puzzleId = puzzleId;
+ this.order = order;
+ this.content = content;
+ }
+}
diff --git a/src/hints/hints.controller.ts b/src/hints/hints.controller.ts
new file mode 100644
index 0000000..b9a2281
--- /dev/null
+++ b/src/hints/hints.controller.ts
@@ -0,0 +1,21 @@
+import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
+import { HintsService } from './hints.service';
+import { RevealHintDto } from './dto/reveal-hint.dto';
+import { AdminGuard } from '../auth/guards/admin.guard';
+
+@Controller('hints')
+export class HintsController {
+ constructor(private readonly hintsService: HintsService) {}
+
+ @Post('reveal')
+ async revealHint(@Body() revealHintDto: RevealHintDto) {
+ const { sessionId, puzzleId } = revealHintDto;
+ return this.hintsService.revealNextHint(sessionId, puzzleId);
+ }
+
+ @UseGuards(AdminGuard)
+ @Get('puzzle/:puzzleId')
+ async getHintsForPuzzle(@Param('puzzleId') puzzleId: string) {
+ return this.hintsService.getHintsForPuzzle(puzzleId);
+ }
+}
diff --git a/src/hints/hints.module.ts b/src/hints/hints.module.ts
new file mode 100644
index 0000000..10f5c1a
--- /dev/null
+++ b/src/hints/hints.module.ts
@@ -0,0 +1,10 @@
+import { Module } from '@nestjs/common';
+import { HintsService } from './hints.service';
+import { HintsController } from './hints.controller';
+
+@Module({
+ providers: [HintsService],
+ controllers: [HintsController],
+ exports: [HintsService],
+})
+export class HintsModule {}
diff --git a/src/hints/hints.service.ts b/src/hints/hints.service.ts
new file mode 100644
index 0000000..73bed82
--- /dev/null
+++ b/src/hints/hints.service.ts
@@ -0,0 +1,56 @@
+import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
+import { Hint } from './entities/hint.entity';
+import { v4 as uuidv4 } from 'uuid';
+// Placeholder for scoring integration
+interface ScoringService {
+ penalize(sessionId: string, points: number): void;
+}
+
+@Injectable()
+export class HintsService {
+ private hints: Hint[] = [];
+ private sessionHints: Map<string, Set<number>> = new Map(); // sessionId -> set of revealed orders
+ private scoringService: ScoringService; // Assume injected elsewhere or set later
+
+ constructor() {
+ // Initialize with sample hints (in real app, would be persisted)
+ this.hints = [
+ new Hint(uuidv4(), 'puzzle1', 1, 'First hint for puzzle 1'),
+ new Hint(uuidv4(), 'puzzle1', 2, 'Second hint for puzzle 1'),
+ new Hint(uuidv4(), 'puzzle1', 3, 'Third hint for puzzle 1'),
+ ];
+ }
+
+ setScoringService(service: ScoringService) {
+ this.scoringService = service;
+ }
+
+ getHintsForPuzzle(puzzleId: string): Hint[] {
+ return this.hints.filter(h => h.puzzleId === puzzleId).sort((a, b) => a.order - b.order);
+ }
+
+ revealNextHint(sessionId: string, puzzleId: string): Hint {
+ if (this.isSessionCompletedOrAbandoned(sessionId)) {
+ throw new BadRequestException('Cannot reveal hints for completed or abandoned session');
+ }
+ const revealed = this.sessionHints.get(sessionId) || new Set<number>();
+ const puzzleHints = this.getHintsForPuzzle(puzzleId);
+ const nextHint = puzzleHints.find(h => !revealed.has(h.order));
+ if (!nextHint) {
+ throw new BadRequestException('All hints already revealed');
+ }
+ // Track reveal
+ revealed.add(nextHint.order);
+ this.sessionHints.set(sessionId, revealed);
+ // Apply penalty (example: 10 points per hint)
+ if (this.scoringService) {
+ this.scoringService.penalize(sessionId, 10);
+ }
+ return nextHint;
+ }
+
+ private isSessionCompletedOrAbandoned(sessionId: string): boolean {
+ // Placeholder logic; integrate with actual session service
+ return false;
+ }
+}
--
2.54.0.windows.1
From cc3427df39fb3386e1a5e3829cc407375623a913 Mon Sep 17 00:00:00 2001
From: martinshub-tech <jambemail2003@gmail.com>
Date: Wed, 17 Jun 2026 00:29:11 +0100
Subject: [PATCH 2/3] feat: integrate hints with sessions and scoring modules
and add unit tests
---
src/app.module.ts | 11 +++-
src/hints/dto/reveal-hint.dto.ts | 1 -
src/hints/hints.controller.spec.ts | 30 ++++++++++
src/hints/hints.controller.ts | 4 +-
src/hints/hints.module.ts | 3 +
src/hints/hints.service.spec.ts | 96 ++++++++++++++++++++++++++++++
src/hints/hints.service.ts | 83 +++++++++++++++-----------
src/scoring/scoring.module.ts | 8 +++
src/scoring/scoring.service.ts | 19 ++++++
src/sessions/sessions.module.ts | 8 +++
src/sessions/sessions.service.ts | 33 ++++++++++
11 files changed, 256 insertions(+), 40 deletions(-)
create mode 100644 src/hints/hints.controller.spec.ts
create mode 100644 src/hints/hints.service.spec.ts
create mode 100644 src/scoring/scoring.module.ts
create mode 100644 src/scoring/scoring.service.ts
create mode 100644 src/sessions/sessions.module.ts
create mode 100644 src/sessions/sessions.service.ts
diff --git a/src/app.module.ts b/src/app.module.ts
index 01068c5..5bb567c 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -1,4 +1,13 @@
import { Module } from '@nestjs/common';
+import { HintsModule } from './hints/hints.module';
+import { SessionsModule } from './sessions/sessions.module';
+import { ScoringModule } from './scoring/scoring.module';
-@Module({})
+@Module({
+ imports: [
+ SessionsModule,
+ ScoringModule,
+ HintsModule,
+ ],
+})
export class AppModule {}
diff --git a/src/hints/dto/reveal-hint.dto.ts b/src/hints/dto/reveal-hint.dto.ts
index 40ffb07..87bc7fc 100644
--- a/src/hints/dto/reveal-hint.dto.ts
+++ b/src/hints/dto/reveal-hint.dto.ts
@@ -1,4 +1,3 @@
export class RevealHintDto {
sessionId: string;
- puzzleId: string;
}
diff --git a/src/hints/hints.controller.spec.ts b/src/hints/hints.controller.spec.ts
new file mode 100644
index 0000000..43c0904
--- /dev/null
+++ b/src/hints/hints.controller.spec.ts
@@ -0,0 +1,30 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { HintsController } from './hints.controller';
+import { HintsService } from './hints.service';
+import { SessionsService } from '../sessions/sessions.service';
+import { ScoringService } from '../scoring/scoring.service';
+import { AdminGuard } from '../auth/guards/admin.guard';
+
+describe('HintsController', () => {
+ let controller: HintsController;
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ controllers: [HintsController],
+ providers: [
+ HintsService,
+ SessionsService,
+ ScoringService,
+ ],
+ })
+ .overrideGuard(AdminGuard)
+ .useValue({ canActivate: () => true })
+ .compile();
+
+ controller = module.get<HintsController>(HintsController);
+ });
+
+ it('should be defined', () => {
+ expect(controller).toBeDefined();
+ });
+});
diff --git a/src/hints/hints.controller.ts b/src/hints/hints.controller.ts
index b9a2281..632d637 100644
--- a/src/hints/hints.controller.ts
+++ b/src/hints/hints.controller.ts
@@ -9,8 +9,8 @@ export class HintsController {
@Post('reveal')
async revealHint(@Body() revealHintDto: RevealHintDto) {
- const { sessionId, puzzleId } = revealHintDto;
- return this.hintsService.revealNextHint(sessionId, puzzleId);
+ const { sessionId } = revealHintDto;
+ return this.hintsService.revealNextHint(sessionId);
}
@UseGuards(AdminGuard)
diff --git a/src/hints/hints.module.ts b/src/hints/hints.module.ts
index 10f5c1a..ac09409 100644
--- a/src/hints/hints.module.ts
+++ b/src/hints/hints.module.ts
@@ -1,8 +1,11 @@
import { Module } from '@nestjs/common';
import { HintsService } from './hints.service';
import { HintsController } from './hints.controller';
+import { SessionsModule } from '../sessions/sessions.module';
+import { ScoringModule } from '../scoring/scoring.module';
@Module({
+ imports: [SessionsModule, ScoringModule],
providers: [HintsService],
controllers: [HintsController],
exports: [HintsService],
diff --git a/src/hints/hints.service.spec.ts b/src/hints/hints.service.spec.ts
new file mode 100644
index 0000000..0dc5d3a
--- /dev/null
+++ b/src/hints/hints.service.spec.ts
@@ -0,0 +1,96 @@
+import { Test, TestingModule } from '@nestjs/testing';
+import { HintsService } from './hints.service';
+import { SessionsService } from '../sessions/sessions.service';
+import { ScoringService } from '../scoring/scoring.service';
+import { BadRequestException } from '@nestjs/common';
+
+describe('HintsService', () => {
+ let service: HintsService;
+ let sessionsService: SessionsService;
+ let scoringService: ScoringService;
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ HintsService,
+ SessionsService,
+ ScoringService,
+ ],
+ }).compile();
+
+ service = module.get<HintsService>(HintsService);
+ sessionsService = module.get<SessionsService>(SessionsService);
+ scoringService = module.get<ScoringService>(ScoringService);
+ });
+
+ it('should be defined', () => {
+ expect(service).toBeDefined();
+ });
+
+ describe('revealNextHint', () => {
+ const sessionId = 'test-session';
+ const puzzleId = 'puzzle-1';
+
+ beforeEach(() => {
+ sessionsService.createSession(sessionId, puzzleId);
+ });
+
+ it('should deliver hints in order (1 -> 2 -> 3) (ordered reveal)', () => {
+ // Reveal 1
+ const hint1 = service.revealNextHint(sessionId);
+ expect(hint1.order).toBe(1);
+ expect(hint1.puzzleId).toBe(puzzleId);
+
+ // Reveal 2
+ const hint2 = service.revealNextHint(sessionId);
+ expect(hint2.order).toBe(2);
+
+ // Reveal 3
+ const hint3 = service.revealNextHint(sessionId);
+ expect(hint3.order).toBe(3);
+ });
+
+ it('should prevent repeated hints and throw 400 when all are revealed (repeat prevention)', () => {
+ // Reveal all 3 hints
+ service.revealNextHint(sessionId);
+ service.revealNextHint(sessionId);
+ service.revealNextHint(sessionId);
+
+ // 4th reveal attempt should fail with BadRequestException (400)
+ expect(() => service.revealNextHint(sessionId)).toThrow(BadRequestException);
+ });
+
+ it('should trigger score penalty via the scoring module (penalty trigger)', () => {
+ // Starting score is 100
+ expect(scoringService.getScore(sessionId)).toBe(100);
+
+ // Reveal 1
+ service.revealNextHint(sessionId);
+ expect(scoringService.getScore(sessionId)).toBe(90); // 100 - 10
+
+ // Reveal 2
+ service.revealNextHint(sessionId);
+ expect(scoringService.getScore(sessionId)).toBe(80); // 90 - 10
+ });
+
+ it('should throw 400 for completed session (invalid session states)', () => {
+ sessionsService.updateSessionStatus(sessionId, 'COMPLETED');
+ expect(() => service.revealNextHint(sessionId)).toThrow(BadRequestException);
+ });
+
+ it('should throw 400 for abandoned session (invalid session states)', () => {
+ sessionsService.updateSessionStatus(sessionId, 'ABANDONED');
+ expect(() => service.revealNextHint(sessionId)).toThrow(BadRequestException);
+ });
+ });
+
+ describe('getHintsForPuzzle', () => {
+ it('should return all hints for a puzzle sorted by order (admin endpoint)', () => {
+ const hints = service.getHintsForPuzzle('puzzle-1');
+ expect(hints.length).toBe(3);
+ expect(hints[0].order).toBe(1);
+ expect(hints[1].order).toBe(2);
+ expect(hints[2].order).toBe(3);
+ });
+ });
+});
diff --git a/src/hints/hints.service.ts b/src/hints/hints.service.ts
index 73bed82..89be264 100644
--- a/src/hints/hints.service.ts
+++ b/src/hints/hints.service.ts
@@ -1,56 +1,67 @@
-import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
+import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { Hint } from './entities/hint.entity';
-import { v4 as uuidv4 } from 'uuid';
-// Placeholder for scoring integration
-interface ScoringService {
- penalize(sessionId: string, points: number): void;
-}
+import { SessionsService } from '../sessions/sessions.service';
+import { ScoringService } from '../scoring/scoring.service';
@Injectable()
export class HintsService {
private hints: Hint[] = [];
- private sessionHints: Map<string, Set<number>> = new Map(); // sessionId -> set of revealed orders
- private scoringService: ScoringService; // Assume injected elsewhere or set later
+ private sessionHints: Map<string, Set<number>> = new Map(); // sessionId -> Set of revealed hint orders (1-3)
- constructor() {
- // Initialize with sample hints (in real app, would be persisted)
+ constructor(
+ private readonly sessionsService: SessionsService,
+ private readonly scoringService: ScoringService,
+ ) {
+ // Seed some initial hints for puzzles
+ // Supporting up to three tiered hints per puzzle (orders 1, 2, 3)
this.hints = [
- new Hint(uuidv4(), 'puzzle1', 1, 'First hint for puzzle 1'),
- new Hint(uuidv4(), 'puzzle1', 2, 'Second hint for puzzle 1'),
- new Hint(uuidv4(), 'puzzle1', 3, 'Third hint for puzzle 1'),
+ new Hint('hint1-1', 'puzzle-1', 1, 'Puzzle 1: First Hint (Easy)'),
+ new Hint('hint1-2', 'puzzle-1', 2, 'Puzzle 1: Second Hint (Medium)'),
+ new Hint('hint1-3', 'puzzle-1', 3, 'Puzzle 1: Final Hint (Hard)'),
+ new Hint('hint2-1', 'puzzle-2', 1, 'Puzzle 2: First Hint (Easy)'),
+ new Hint('hint2-2', 'puzzle-2', 2, 'Puzzle 2: Second Hint (Medium)'),
+ new Hint('hint2-3', 'puzzle-2', 3, 'Puzzle 2: Final Hint (Hard)'),
];
}
- setScoringService(service: ScoringService) {
- this.scoringService = service;
- }
-
+ // Admin‑only endpoint retrieves all hints for a puzzle
getHintsForPuzzle(puzzleId: string): Hint[] {
- return this.hints.filter(h => h.puzzleId === puzzleId).sort((a, b) => a.order - b.order);
+ const puzzleHints = this.hints.filter(h => h.puzzleId === puzzleId);
+ return puzzleHints.sort((a, b) => a.order - b.order);
}
- revealNextHint(sessionId: string, puzzleId: string): Hint {
- if (this.isSessionCompletedOrAbandoned(sessionId)) {
- throw new BadRequestException('Cannot reveal hints for completed or abandoned session');
+ // Reveals next unrevealed hint for a session
+ revealNextHint(sessionId: string): Hint {
+ // 1. Retrieve the session & validate status (completed or abandoned sessions return 400)
+ const session = this.sessionsService.getSession(sessionId);
+ if (session.status === 'COMPLETED' || session.status === 'ABANDONED') {
+ throw new BadRequestException('Cannot reveal hints in a completed or abandoned session');
}
- const revealed = this.sessionHints.get(sessionId) || new Set<number>();
+
+ const puzzleId = session.puzzleId;
const puzzleHints = this.getHintsForPuzzle(puzzleId);
- const nextHint = puzzleHints.find(h => !revealed.has(h.order));
- if (!nextHint) {
- throw new BadRequestException('All hints already revealed');
+ if (puzzleHints.length === 0) {
+ throw new NotFoundException(`No hints configured for puzzle ${puzzleId}`);
}
- // Track reveal
- revealed.add(nextHint.order);
- this.sessionHints.set(sessionId, revealed);
- // Apply penalty (example: 10 points per hint)
- if (this.scoringService) {
- this.scoringService.penalize(sessionId, 10);
+
+ // 2. Track reveal and ensure repeat prevention
+ if (!this.sessionHints.has(sessionId)) {
+ this.sessionHints.set(sessionId, new Set<number>());
+ }
+ const revealedOrders = this.sessionHints.get(sessionId)!;
+
+ // Find next unrevealed hint (ordered 1 to 3)
+ const nextHint = puzzleHints.find(h => !revealedOrders.has(h.order));
+ if (!nextHint) {
+ throw new BadRequestException('All hints for this puzzle have already been revealed');
}
- return nextHint;
- }
- private isSessionCompletedOrAbandoned(sessionId: string): boolean {
- // Placeholder logic; integrate with actual session service
- return false;
+ // Mark as revealed
+ revealedOrders.add(nextHint.order);
+
+ // 3. Trigger score penalty via the scoring module (hints cost points)
+ this.scoringService.penalize(sessionId, 10);
+
+ return nextHint;
}
}
diff --git a/src/scoring/scoring.module.ts b/src/scoring/scoring.module.ts
new file mode 100644
index 0000000..9c1f7e1
--- /dev/null
+++ b/src/scoring/scoring.module.ts
@@ -0,0 +1,8 @@
+import { Module } from '@nestjs/common';
+import { ScoringService } from './scoring.service';
+
+@Module({
+ providers: [ScoringService],
+ exports: [ScoringService],
+})
+export class ScoringModule {}
diff --git a/src/scoring/scoring.service.ts b/src/scoring/scoring.service.ts
new file mode 100644
index 0000000..a6b2914
--- /dev/null
+++ b/src/scoring/scoring.service.ts
@@ -0,0 +1,19 @@
+import { Injectable } from '@nestjs/common';
+
+@Injectable()
+export class ScoringService {
+ private sessionScores: Map<string, number> = new Map(); // sessionId -> score
+
+ penalize(sessionId: string, points: number): void {
+ const currentScore = this.sessionScores.get(sessionId) || 100; // start score at 100
+ this.sessionScores.set(sessionId, Math.max(0, currentScore - points));
+ }
+
+ getScore(sessionId: string): number {
+ return this.sessionScores.get(sessionId) ?? 100;
+ }
+
+ setScore(sessionId: string, score: number): void {
+ this.sessionScores.set(sessionId, score);
+ }
+}
diff --git a/src/sessions/sessions.module.ts b/src/sessions/sessions.module.ts
new file mode 100644
index 0000000..ac751c4
--- /dev/null
+++ b/src/sessions/sessions.module.ts
@@ -0,0 +1,8 @@
+import { Module } from '@nestjs/common';
+import { SessionsService } from './sessions.service';
+
+@Module({
+ providers: [SessionsService],
+ exports: [SessionsService],
+})
+export class SessionsModule {}
diff --git a/src/sessions/sessions.service.ts b/src/sessions/sessions.service.ts
new file mode 100644
index 0000000..4af8de7
--- /dev/null
+++ b/src/sessions/sessions.service.ts
@@ -0,0 +1,33 @@
+import { Injectable, NotFoundException } from '@nestjs/common';
+
+export interface Session {
+ id: string;
+ puzzleId: string;
+ status: 'ACTIVE' | 'COMPLETED' | 'ABANDONED';
+}
+
+@Injectable()
+export class SessionsService {
+ private sessions: Map<string, Session> = new Map();
+
+ createSession(id: string, puzzleId: string): Session {
+ const session: Session = { id, puzzleId, status: 'ACTIVE' };
+ this.sessions.set(id, session);
+ return session;
+ }
+
+ getSession(id: string): Session {
+ const session = this.sessions.get(id);
+ if (!session) {
+ throw new NotFoundException(`Session with ID ${id} not found`);
+ }
+ return session;
+ }
+
+ updateSessionStatus(id: string, status: 'ACTIVE' | 'COMPLETED' | 'ABANDONED'): Session {
+ const session = this.getSession(id);
+ session.status = status;
+ this.sessions.set(id, session);
+ return session;
+ }
+}
--
2.54.0.windows.1
From f9b69972c922398a4f03e1cff22db2a1b4c19374 Mon Sep 17 00:00:00 2001
From: martinshub-tech <jambemail2003@gmail.com>
Date: Wed, 17 Jun 2026 01:18:33 +0100
Subject: [PATCH 3/3] feat: add users module with CRUD, auth, role guards
---
package.json | 5 ++-
src/app.module.ts | 10 ++++++
src/auth/guards/auth.guard.ts | 16 ++++++++++
src/auth/guards/roles.guard.ts | 13 ++++++++
src/users/dto/create-user.dto.ts | 12 ++++++++
src/users/dto/update-user.dto.ts | 14 +++++++++
src/users/entities/user.entity.ts | 30 ++++++++++++++++++
src/users/users.controller.ts | 32 +++++++++++++++++++
src/users/users.module.ts | 13 ++++++++
src/users/users.service.ts | 51 +++++++++++++++++++++++++++++++
10 files changed, 195 insertions(+), 1 deletion(-)
create mode 100644 src/auth/guards/auth.guard.ts
create mode 100644 src/auth/guards/roles.guard.ts
create mode 100644 src/users/dto/create-user.dto.ts
create mode 100644 src/users/dto/update-user.dto.ts
create mode 100644 src/users/entities/user.entity.ts
create mode 100644 src/users/users.controller.ts
create mode 100644 src/users/users.module.ts
create mode 100644 src/users/users.service.ts
diff --git a/package.json b/package.json
index dda7360..667efc2 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,10 @@
"@nestjs/common": "^11.1.27",
"@nestjs/core": "^11.1.27",
"@nestjs/platform-express": "^11.1.27",
- "reflect-metadata": "^0.2.2"
+ "reflect-metadata": "^0.2.2",
+ "@nestjs/typeorm": "^11.0.0",
+ "typeorm": "^0.3.20",
+ "bcrypt": "^5.1.1"
},
"devDependencies": {
"@nestjs/cli": "^11.0.23",
diff --git a/src/app.module.ts b/src/app.module.ts
index 5bb567c..0bbdaa2 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -1,13 +1,23 @@
import { Module } from '@nestjs/common';
import { HintsModule } from './hints/hints.module';
+import { TypeOrmModule } from '@nestjs/typeorm';
+import { UsersModule } from './users/users.module';
+import { User } from './users/entities/user.entity';
import { SessionsModule } from './sessions/sessions.module';
import { ScoringModule } from './scoring/scoring.module';
@Module({
imports: [
+ TypeOrmModule.forRoot({
+ type: 'sqlite',
+ database: ':memory:',
+ entities: [User],
+ synchronize: true,
+ }),
SessionsModule,
ScoringModule,
HintsModule,
+ UsersModule,
],
})
export class AppModule {}
diff --git a/src/auth/guards/auth.guard.ts b/src/auth/guards/auth.guard.ts
new file mode 100644
index 0000000..da4388d
--- /dev/null
+++ b/src/auth/guards/auth.guard.ts
@@ -0,0 +1,16 @@
+import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
+
+@Injectable()
+export class AuthGuard implements CanActivate {
+ canActivate(context: ExecutionContext): boolean {
+ const request = context.switchToHttp().getRequest();
+ // Placeholder: In real scenario, extract and validate JWT/token
+ // For now, assume a user is attached to request for testing purposes
+ if (!request.headers['authorization']) {
+ throw new UnauthorizedException('Missing auth token');
+ }
+ // Mock user extraction
+ request.user = { id: 'test-user-id', role: 'player' };
+ return true;
+ }
+}
diff --git a/src/auth/guards/roles.guard.ts b/src/auth/guards/roles.guard.ts
new file mode 100644
index 0000000..edbeb66
--- /dev/null
+++ b/src/auth/guards/roles.guard.ts
@@ -0,0 +1,13 @@
+import { CanActivate, ExecutionContext, Injectable, ForbiddenException } from '@nestjs/common';
+
+@Injectable()
+export class RolesGuard implements CanActivate {
+ canActivate(context: ExecutionContext): boolean {
+ const request = context.switchToHttp().getRequest();
+ const user = request.user;
+ if (!user || user.role !== 'admin') {
+ throw new ForbiddenException('Admin role required');
+ }
+ return true;
+ }
+}
diff --git a/src/users/dto/create-user.dto.ts b/src/users/dto/create-user.dto.ts
new file mode 100644
index 0000000..5880aa0
--- /dev/null
+++ b/src/users/dto/create-user.dto.ts
@@ -0,0 +1,12 @@
+import { IsEmail, IsNotEmpty, MinLength } from 'class-validator';
+
+export class CreateUserDto {
+ @IsNotEmpty()
+ username: string;
+
+ @IsEmail()
+ email: string;
+
+ @MinLength(8)
+ password: string; // plaintext, will be hashed
+}
diff --git a/src/users/dto/update-user.dto.ts b/src/users/dto/update-user.dto.ts
new file mode 100644
index 0000000..9c1e503
--- /dev/null
+++ b/src/users/dto/update-user.dto.ts
@@ -0,0 +1,14 @@
+import { IsOptional, IsEmail, MinLength } from 'class-validator';
+
+export class UpdateUserDto {
+ @IsOptional()
+ username?: string;
+
+ @IsOptional()
+ @IsEmail()
+ email?: string;
+
+ @IsOptional()
+ @MinLength(8)
+ password?: string; // will be re‑hashed if provided
+}
diff --git a/src/users/entities/user.entity.ts b/src/users/entities/user.entity.ts
new file mode 100644
index 0000000..df7362c
--- /dev/null
+++ b/src/users/entities/user.entity.ts
@@ -0,0 +1,30 @@
+import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
+
+export enum UserRole {
+ ADMIN = 'admin',
+ PLAYER = 'player',
+}
+
+@Entity('users')
+export class User {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({ unique: true })
+ username: string;
+
+ @Column({ unique: true })
+ email: string;
+
+ @Column()
+ passwordHash: string;
+
+ @Column({ type: 'enum', enum: UserRole, default: UserRole.PLAYER })
+ role: UserRole;
+
+ @CreateDateColumn()
+ createdAt: Date;
+
+ @UpdateDateColumn()
+ updatedAt: Date;
+}
diff --git a/src/users/users.controller.ts b/src/users/users.controller.ts
new file mode 100644
index 0000000..6536504
--- /dev/null
+++ b/src/users/users.controller.ts
@@ -0,0 +1,32 @@
+import { Controller, Get, Param, Patch, Delete, Body, UseGuards, Request } from '@nestjs/common';
+import { UsersService } from './users.service';
+import { UpdateUserDto } from './dto/update-user.dto';
+import { UserDto } from './dto/user.dto';
+import { AuthGuard } from '../auth/guards/auth.guard';
+import { RolesGuard } from '../auth/guards/roles.guard';
+
+@Controller('users')
+export class UsersController {
+ constructor(private readonly service: UsersService) {}
+
+ @Get(':id')
+ async getProfile(@Param('id') id: string): Promise<UserDto> {
+ const user = await this.service.findOne(id);
+ const { passwordHash, ...rest } = user as any;
+ return rest as any;
+ }
+
+ @Patch(':id')
+ @UseGuards(AuthGuard)
+ async updateProfile(@Param('id') id: string, @Body() dto: UpdateUserDto, @Request() req): Promise<UserDto> {
+ const updated = await this.service.update(id, dto, req.user.id, req.user.role);
+ const { passwordHash, ...rest } = updated as any;
+ return rest as any;
+ }
+
+ @Delete(':id')
+ @UseGuards(AuthGuard, RolesGuard)
+ async deleteUser(@Param('id') id: string, @Request() req): Promise<void> {
+ await this.service.remove(id, req.user.role);
+ }
+}
diff --git a/src/users/users.module.ts b/src/users/users.module.ts
new file mode 100644
index 0000000..327171c
--- /dev/null
+++ b/src/users/users.module.ts
@@ -0,0 +1,13 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+import { UsersService } from './users.service';
+import { UsersController } from './users.controller';
+import { User } from './entities/user.entity';
+
+@Module({
+ imports: [TypeOrmModule.forFeature([User])],
+ providers: [UsersService],
+ controllers: [UsersController],
+ exports: [UsersService],
+})
+export class UsersModule {}
diff --git a/src/users/users.service.ts b/src/users/users.service.ts
new file mode 100644
index 0000000..1ea97f4
--- /dev/null
+++ b/src/users/users.service.ts
@@ -0,0 +1,51 @@
+import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { User, UserRole } from './entities/user.entity';
+import { CreateUserDto } from './dto/create-user.dto';
+import { UpdateUserDto } from './dto/update-user.dto';
+import * as bcrypt from 'bcrypt';
+
+@Injectable()
+export class UsersService {
+ constructor(@InjectRepository(User) private readonly repo: Repository<User>) {}
+
+ async create(dto: CreateUserDto): Promise<User> {
+ const hash = await bcrypt.hash(dto.password, 10);
+ const user = this.repo.create({
+ username: dto.username,
+ email: dto.email,
+ passwordHash: hash,
+ role: UserRole.PLAYER,
+ });
+ return this.repo.save(user);
+ }
+
+ async findOne(id: string): Promise<User> {
+ const user = await this.repo.findOne({ where: { id } });
+ if (!user) throw new NotFoundException('User not found');
+ return user;
+ }
+
+ async update(id: string, dto: UpdateUserDto, requesterId: string, requesterRole: UserRole): Promise<User> {
+ if (id !== requesterId && requesterRole !== UserRole.ADMIN) {
+ throw new ForbiddenException('Cannot edit other users');
+ }
+ const user = await this.findOne(id);
+ if (dto.password) {
+ const passwordHash = await bcrypt.hash(dto.password, 10);
+ (dto as any).passwordHash = passwordHash;
+ delete (dto as any).password;
+ }
+ Object.assign(user, dto);
+ return this.repo.save(user);
+ }
+
+ async remove(id: string, requesterRole: UserRole): Promise<void> {
+ if (requesterRole !== UserRole.ADMIN) {
+ throw new ForbiddenException('Only admins can delete users');
+ }
+ const user = await this.findOne(id);
+ await this.repo.remove(user);
+ }
+}
--
2.54.0.windows.1