├── .babelrc
├── .gitignore
├── .idea
├── encodings.xml
├── jsLibraryMappings.xml
├── misc.xml
├── modules.xml
├── ntask-api.iml
├── vcs.xml
├── watcherTasks.xml
└── workspace.xml
├── 44885970_www.localhost.com.cert
├── 44885970_www.localhost.com.key
├── LICENSE
├── README.md
├── auth.js
├── cluster.js
├── db.js
├── index.js
├── libs
├── boot.js
├── config.development.js
├── config.js
├── config.test.js
├── logger.js
└── middlewares.js
├── logs
└── app.log
├── models
├── tasks.js
└── users.js
├── ntask.sqlite
├── package.json
├── routers
├── index.js
├── tasks.js
├── token.js
└── users.js
└── test
├── helpers.js
├── mocha.opts
└── routes
├── index.js
├── tasks.js
├── token.js
└── users.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["env"]
3 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Build and Release Folders
2 | bin/
3 | bin-debug/
4 | bin-release/
5 | [Oo]bj/ # FlashDevelop obj
6 | [Bb]in/ # FlashDevelop bin
7 |
8 | # Other files and folders
9 | .settings/
10 |
11 | # Executables
12 | *.swf
13 | *.air
14 | *.ipa
15 | *.apk
16 |
17 | node_modules
18 | public/apidoc
19 |
20 | # Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties`
21 | # should NOT be excluded as they contain compiler settings and other important
22 | # information for Eclipse / Flash Builder.
23 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/jsLibraryMappings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | CSS
19 |
20 |
21 | GeneralJavaScript
22 |
23 |
24 | JavaScript
25 |
26 |
27 | Node.jsJavaScript
28 |
29 |
30 |
31 |
32 | CoffeeScript
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/ntask-api.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/watcherTasks.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
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 |
141 |
142 |
143 |
144 | AUTH_HEADER
145 | NTask API
146 | framework
147 | payload
148 | LEGACY_AUTH_SCHEME
149 | err:
150 | chai
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 | true
194 |
195 | false
196 | true
197 |
198 |
199 | true
200 | DEFINITION_ORDER
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 | project
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 | project
430 |
431 |
432 | true
433 |
434 |
435 |
436 | DIRECTORY
437 |
438 | false
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 | 1505472175818
449 |
450 |
451 | 1505472175818
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 |
--------------------------------------------------------------------------------
/44885970_www.localhost.com.cert:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDCzCCAfOgAwIBAgIJAOrSof+ml1tAMA0GCSqGSIb3DQEBBQUAMBwxGjAYBgNV
3 | BAMMEXd3dy5sb2NhbGhvc3QuY29tMB4XDTE3MDkyNTA3MDk0M1oXDTI3MDkyMzA3
4 | MDk0M1owHDEaMBgGA1UEAwwRd3d3LmxvY2FsaG9zdC5jb20wggEiMA0GCSqGSIb3
5 | DQEBAQUAA4IBDwAwggEKAoIBAQDZh9QzTeUtmEbEiNzPx6Kc/qFfhubYcFB8VQhP
6 | wV1VndW3wbXihChChFFn7tWaFo3Rq8/BNoz+ZsS0kEnRO/jrK4XWGeFVqhq24ckC
7 | c97NB1pU+kJHuaru6dUhPpVwgY9rqHvKWh1OWyE7JIkKaMsAadVQ1JF6uNpgQopT
8 | bjEnzVVozdLQgLEZfEsh8JC9bNSjYuKWQZ+982/y/XosGKq2FelCpVt5C+yytTfT
9 | 7WA4EnrcKIejIplWQ9LR0b0rcFx5IZLZipXPj/B13IZbOoP7L4CfTy14x4p6n9eW
10 | Zxv36ACOMmk76SLzvsHH+tMLzQpCh51t6c+ku0o0CJo+P32tAgMBAAGjUDBOMB0G
11 | A1UdDgQWBBSA+7h/WRJjsWgWpHXztIKRk1GmfzAfBgNVHSMEGDAWgBSA+7h/WRJj
12 | sWgWpHXztIKRk1GmfzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDQ
13 | dtDFmk3ZX1KXgFYOMjQnAg+zvIUt38Op9ui9VnplvWhyDv5AXMnrg5eG0Ohsrk3E
14 | XPanNW8wzcfI+jhJjy/ZDAPws14R9OMuqqfcQaXkJhP2gqAEDzbI7jdvKEngToqr
15 | pUUFo5T688BjrXVDSL1nhj/lGFfDRTLgrFKXzQZoc6i6Xb+KMd08cT0ng41dVUPx
16 | Qmlb384QunmZG+b2j/UY620k0/TvDaIzupfHsLcj8cXOQvmgS86Xplwajx6vHz73
17 | Ia7WsMisRHYSQPd5XWYbsadJ2ttwmW7qjNHF1cCPcr/cxvGEBsOUrz7ZEXgaDibQ
18 | K+7WsK9P5qf0j5RCLAGS
19 | -----END CERTIFICATE-----
20 |
--------------------------------------------------------------------------------
/44885970_www.localhost.com.key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEpAIBAAKCAQEA2YfUM03lLZhGxIjcz8einP6hX4bm2HBQfFUIT8FdVZ3Vt8G1
3 | 4oQoQoRRZ+7VmhaN0avPwTaM/mbEtJBJ0Tv46yuF1hnhVaoatuHJAnPezQdaVPpC
4 | R7mq7unVIT6VcIGPa6h7ylodTlshOySJCmjLAGnVUNSRerjaYEKKU24xJ81VaM3S
5 | 0ICxGXxLIfCQvWzUo2LilkGfvfNv8v16LBiqthXpQqVbeQvssrU30+1gOBJ63CiH
6 | oyKZVkPS0dG9K3BceSGS2YqVz4/wddyGWzqD+y+An08teMeKep/Xlmcb9+gAjjJp
7 | O+ki877Bx/rTC80KQoedbenPpLtKNAiaPj99rQIDAQABAoIBAATh7ppkMjOuyk/Y
8 | /pPPWFALyxV40q+i/bt8sR4RKgYk78obF/kInFq525Xon3TA8tf08knU7p87MUkY
9 | P//pR7IHnQ5sMEma8tSOBtP+Q874TkfAAkLX4QVRzE3duL74uX5iHr0w/p1moD1S
10 | mZzZM01EEtyomMdXZNdqRu6Od538DEUpDaW8xjoabVKofEn+Z/G6ivNmAjCfIcE/
11 | ad9TYIfAM2oDXGi95T6YQ/IL56g8Mf4ilvGlHuPKtlRdaodc2w5p7FdkCrSj3vsC
12 | yM9R9NpefgLE+ec59UViYJfJiZCiTlZcdLqSSCUXCc/WHh2ccv4P40W2mUBHkiBC
13 | geUiiqECgYEA+iQWIP2hOvZ6WE4fzChd7vx97PK5GXlLZCxyRRU8cmF3xupz2wvu
14 | RnKAil5V9dUp+lWrqQJhXEFzPZuF2EMerVVC9jCprMyetMAaKnaRXI1SH4R1U3FO
15 | LqUBl/nLOBJnUJmqIKrLf50cqNyGsjlfoTTXjt1NfwgKIJ94iCeKJ/kCgYEA3qAz
16 | o2pheBKI7DMLQGi7uI3sUxqT6Hx251ZDqN2Pf1AjwvApbDiBXyklGEKgV72aq6Cq
17 | Ry4OluWMKt2Vs7H0VJjSeO26brkNfglVy23Wi8neAmLm9gNSSgYPX25LQKAWL2dt
18 | 0KeQX7/j5fNMG/8OHDd53/5yYSqO+1FGxsuf+FUCgYEA1AfCujRDdrd2/WM7kNKm
19 | zO050J/uRqmKPl9ufSCDHHGCFhqmGgcC8rQcQS21r6wA6TG1UI2z+X+BL7ekvKwo
20 | VMTw/b5CFTddT9mGVHgsv0cLVavxx8lDfEZiE3Cp0d3HtYqLqyUbWhDTOk+z3V7E
21 | sOEZ1v+/sO4fp4eFo+PgOAECgYEAyNIegrT9w4CEvvy0k59mZu6vVa/N6JQN9lSc
22 | qAFk5mV2POzDkPnPyfWlnqLLXRqOIW/G6nqjcn8S18AWwIgwbPeGNMvNtv97Kkxl
23 | diJYvLSWbfSlfxoz6s5Yo68sdtlx6cUVDHl7BMRmYhH8f+yt38ozSFmQ+BGZ9R62
24 | B7G7VhkCgYBm7Dpnhm934eizOjgI400YLUzafMuoV89MVcWZHBPx46BVYY5/xe01
25 | A3WRCy8USoXiP/eTZO0AOGe1y//D3BDXFqxyimuaAHrtyFi1wAiZd151fp2DQaLS
26 | gHJ41sp3LcJidRr2kISV/EzJSLpEMB+fof8KmeVUv2azykjP4uv5tg==
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ntask-api
--------------------------------------------------------------------------------
/auth.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/19.
3 | */
4 | import passport from "passport";
5 | import {Strategy, ExtractJwt} from "passport-jwt";
6 |
7 | module.exports = app => {
8 | const Users = app.db.models.Users;
9 | const cfg = app.libs.config;
10 | const params = {
11 | secretOrKey: cfg.jwtSecret,
12 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
13 | };
14 | var opts = {};
15 | opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
16 | opts.secretOrKey = cfg.jwtSecret;
17 |
18 | const strategy = new Strategy(opts, (payload, done) => {
19 | Users.findById(payload.id)
20 | .then(user => {
21 | if (user) {
22 | return done(null, {
23 | id: user.id,
24 | email: user.email
25 | });
26 | }
27 | return done(null, false);
28 | })
29 | .catch(error => done(error, null));
30 | });
31 | passport.use(strategy);
32 |
33 | return {
34 | initialize: () => {
35 | return passport.initialize();
36 | },
37 | authenticate: () => {
38 | return passport.authenticate("jwt", cfg.jwtSession);
39 | }
40 | };
41 | };
42 |
--------------------------------------------------------------------------------
/cluster.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/25.
3 | */
4 | import cluster from "cluster"
5 | import os from "os"
6 |
7 | const CPUS = os.cpus();
8 |
9 | if (cluster.isMaster) {
10 | // Fork
11 | CPUS.forEach(() => cluster.fork());
12 |
13 | // Listening connection event
14 | cluster.on("listening", work => {
15 | "use strict";
16 | console.log(`Cluster ${work.process.pid} connected`);
17 | });
18 |
19 | // Disconnect
20 | cluster.on("disconnect", work => {
21 | "use strict";
22 | console.log(`Cluster ${work.process.pid} disconnected`);
23 | });
24 |
25 | // Exit
26 | cluster.on("exit", worker => {
27 | "use strict";
28 | console.log(`Cluster ${worker.process.pid} is dead`);
29 | cluster.fork();
30 | });
31 |
32 | } else {
33 | require("./index");
34 | }
35 |
--------------------------------------------------------------------------------
/db.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | import fs from "fs"
5 | import path from "path"
6 | import Sequelize from "sequelize"
7 |
8 | let db = null;
9 |
10 |
11 | module.exports = app => {
12 | "use strict";
13 | if (!db) {
14 | const config = app.libs.config;
15 | const sequelize = new Sequelize(
16 | config.database,
17 | config.username,
18 | config.password,
19 | config.params
20 | );
21 |
22 | db = {
23 | sequelize,
24 | Sequelize,
25 | models: {}
26 | };
27 |
28 | const dir = path.join(__dirname, "models");
29 |
30 | fs.readdirSync(dir).forEach(file => {
31 | const modelDir = path.join(dir, file);
32 | const model = sequelize.import(modelDir);
33 | db.models[model.name] = model;
34 | });
35 |
36 | Object.keys(db.models).forEach(key => {
37 | db.models[key].associate(db.models);
38 | });
39 | }
40 | return db;
41 | };
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/14.
3 | */
4 |
5 | import express from "express"
6 | import consign from "consign"
7 |
8 | const app = express();
9 |
10 | /// 在使用include或者then的时候,是有顺序的,如果传入的参数是一个文件夹
11 | /// 那么他会按照文件夹中文件的顺序进行加载
12 | consign({verbose: false})
13 | .include("libs/config.js")
14 | .then("db.js")
15 | .then("auth.js")
16 | .then("libs/middlewares.js")
17 | .then("routers")
18 | .then("libs/boot.js")
19 | .into(app);
20 |
21 | module.exports = app;
22 |
23 |
24 |
--------------------------------------------------------------------------------
/libs/boot.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | import https from "https"
5 | import fs from "fs"
6 |
7 | module.exports = app => {
8 | "use strict";
9 | if (process.env.NODE_ENV !== "test") {
10 |
11 | const credentials = {
12 | key: fs.readFileSync("44885970_www.localhost.com.key", "utf8"),
13 | cert: fs.readFileSync("44885970_www.localhost.com.cert", "utf8")
14 | };
15 |
16 | app.db.sequelize.sync().done(() => {
17 |
18 | https.createServer(credentials, app)
19 | .listen(app.get("port"), () => {
20 | console.log(`NTask API - Port ${app.get("port")}`);
21 | });
22 | });
23 | }
24 | };
--------------------------------------------------------------------------------
/libs/config.development.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | import logger from "./logger.js"
5 |
6 | module.exports = {
7 | database: "ntask",
8 | username: "machao",
9 | password: "123456",
10 | params: {
11 | dialect: "sqlite",
12 | storage: "ntask.sqlite",
13 | logging: (sql) => {
14 | "use strict";
15 | logger.info(`${new Date()} ${sql}`);
16 | },
17 | define: {
18 | underscored: true
19 | }
20 | },
21 | jwtSecret: "asdfsafsafsafsafsafsafsafd",
22 | jwtSession: {session: false}
23 | };
--------------------------------------------------------------------------------
/libs/config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 | module.exports = app => {
5 | "use strict";
6 | const env = process.env.NODE_ENV;
7 | if (env) {
8 | return require(`./config.${env}.js`);
9 | }
10 | return require("./config.development.js");
11 | };
--------------------------------------------------------------------------------
/libs/config.test.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 | module.exports = {
5 | database: "ntask",
6 | username: "machao",
7 | password: "123456",
8 | params: {
9 | dialect: "sqlite",
10 | storage: "ntask.sqlite",
11 | logging: false,
12 | define: {
13 | underscored: true
14 | }
15 | },
16 | jwtSecret: "asdfsafsafsafsafsafsafsafd",
17 | jwtSession: {session: false}
18 | };
--------------------------------------------------------------------------------
/libs/logger.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by machao on 17/9/24.
3 | */
4 | import fs from "fs"
5 | import winston from "winston"
6 |
7 | if (!fs.existsSync("logs")) {
8 | fs.mkdirSync("logs");
9 | }
10 |
11 | module.exports = new winston.Logger({
12 | transports: [
13 | new winston.transports.File({
14 | level: "info",
15 | filename: "logs/app.log",
16 | maxsize: 1048576,
17 | maxFiles: 10,
18 | colorize: false
19 | })
20 | ]
21 | });
--------------------------------------------------------------------------------
/libs/middlewares.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | import bodyParser from "body-parser"
5 | import express from "express"
6 | import cors from "cors"
7 | import morgan from "morgan"
8 | import logger from "./logger"
9 | import compression from "compression"
10 | import helmet from "helmet"
11 |
12 | module.exports = app => {
13 | "use strict";
14 | app.set("port", 3000);
15 | app.set("json spaces", 4);
16 | console.log(`err ${JSON.stringify(app.auth)}`);
17 | app.use(bodyParser.json());
18 | app.use(app.auth.initialize());
19 | app.use(compression());
20 | app.use(helmet());
21 | app.use(morgan("common", {
22 | stream: {
23 | write: (message) => {
24 | logger.info(message);
25 | }
26 | }
27 | }));
28 | app.use(cors({
29 | origin: ["http://localhost:3001"],
30 | methods: ["GET", "POST", "PUT", "DELETE"],
31 | allowedHeaders: ["Content-Type", "Authorization"]
32 | }));
33 | app.use((req, res, next) => {
34 | // console.log(`header: ${JSON.stringify(req.headers)}`);
35 | if (req.body && req.body.id) {
36 | delete req.body.id;
37 | }
38 | next();
39 | });
40 |
41 | app.use(express.static("public"));
42 | };
43 |
--------------------------------------------------------------------------------
/models/tasks.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | module.exports = (sequelize, DataType) => {
5 | "use strict";
6 | const Tasks = sequelize.define("Tasks", {
7 | id: {
8 | type: DataType.INTEGER,
9 | primaryKey: true,
10 | autoIncrement: true
11 | },
12 | title: {
13 | type: DataType.STRING,
14 | allowNull: false,
15 | validate: {
16 | notEmpty: true
17 | }
18 | },
19 | done: {
20 | type: DataType.BOOLEAN,
21 | allowNull: false,
22 | defaultValue: false
23 | }
24 | });
25 | Tasks.associate = (models) => {
26 | Tasks.belongsTo(models.Users);
27 | };
28 | return Tasks;
29 | };
30 |
31 |
--------------------------------------------------------------------------------
/models/users.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 | import bcrypt from "bcrypt"
5 |
6 | module.exports = (sequelize, DataType) => {
7 | "use strict";
8 | const Users = sequelize.define("Users", {
9 | id: {
10 | type: DataType.INTEGER,
11 | primaryKey: true,
12 | autoIncrement: true
13 | },
14 | name: {
15 | type: DataType.STRING,
16 | allowNull: false,
17 | validate: {
18 | notEmpty: true
19 | }
20 | },
21 | password: {
22 | type: DataType.STRING,
23 | allowNull: false,
24 | validate: {
25 | notEmpty: true
26 | }
27 | },
28 | email: {
29 | type: DataType.STRING,
30 | unique: true,
31 | allowNull: false,
32 | validate: {
33 | notEmpty: true
34 | }
35 | }
36 | }, {
37 | hooks: {
38 | beforeCreate: user => {
39 | const salt = bcrypt.genSaltSync();
40 | user.password = bcrypt.hashSync(user.password, salt);
41 | }
42 | }
43 | });
44 | Users.associate = (models) => {
45 | Users.hasMany(models.Tasks);
46 | };
47 | Users.isPassword = (encodedPassword, password) => {
48 | return bcrypt.compareSync(password, encodedPassword);
49 | };
50 |
51 | return Users;
52 | };
--------------------------------------------------------------------------------
/ntask.sqlite:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/agelessman/ntask-api/28a0d887ee30fa89982f76bb295966bee8ff0a00/ntask.sqlite
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ntask-api",
3 | "version": "1.0.0",
4 | "description": "A pilot project for API learnning",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "NODE_ENV=test mocha test/**/*.js",
8 | "start": "npm run apidoc && npm run clusters",
9 | "apidoc": "apidoc -i routers/ -o public/apidoc",
10 | "clusters": "babel-node cluster.js"
11 | },
12 | "apidoc": {
13 | "name": "Node Task API - Documentation",
14 | "template": {
15 | "forceLanguage": "en"
16 | }
17 | },
18 | "author": "",
19 | "license": "ISC",
20 | "dependencies": {
21 | "babel-cli": "^6.26.0",
22 | "babel-preset-env": "^1.6.0",
23 | "bcrypt": "^1.0.3",
24 | "body-parser": "^1.15.0",
25 | "compression": "^1.7.0",
26 | "consign": "^0.1.2",
27 | "cors": "^2.8.4",
28 | "express": "^4.13.4",
29 | "helmet": "^3.8.1",
30 | "jwt-simple": "^0.5.1",
31 | "morgan": "^1.8.2",
32 | "passport": "^0.4.0",
33 | "passport-jwt": "^3.0.0",
34 | "sequelize": "^4.8.4",
35 | "sqlite3": "^3.1.11",
36 | "winston": "^2.3.1"
37 | },
38 | "devDependencies": {
39 | "apidoc": "^0.17.6",
40 | "babel-register": "^6.26.0",
41 | "chai": "^4.1.2",
42 | "mocha": "^3.5.3",
43 | "supertest": "^3.0.0"
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/routers/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 |
5 | module.exports = app => {
6 | "use strict";
7 | /**
8 | * @api {get} / API Status
9 | * @apiGroup Status
10 | * @apiSuccess {String} status API Status' message
11 | * @apiSuccessExample {json} Success
12 | * HTTP/1.1 200 OK
13 | * {"status": "NTask API"}
14 | */
15 | app.get("/", (req, res) => {
16 | res.json({status: "NTask API"});
17 | });
18 | };
--------------------------------------------------------------------------------
/routers/tasks.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/15.
3 | */
4 |
5 | module.exports = app => {
6 | "use strict";
7 | const Tasks = app.db.models.Tasks;
8 |
9 | app.route("/tasks")
10 | .all(app.auth.authenticate())
11 | /**
12 | * @api {get} /tasks List the user's tasks
13 | * @apiGroup Tasks
14 | * @apiHeader {String} Authorization Token of authenticated user
15 | * @apiHeaderExample {json} Header
16 | * {
17 | * "Authorization": "xyz.abc.123.hgf"
18 | * }
19 | * @apiSuccess {Object[]} tasks Task list
20 | * @apiSuccess {Number} tasks.id Task id
21 | * @apiSuccess {String} tasks.title Task title
22 | * @apiSuccess {Boolean} tasks.done Task is done?
23 | * @apiSuccess {Date} tasks.updated_at Update's date
24 | * @apiSuccess {Date} tasks.created_at Register's date
25 | * @apiSuccess {Number} tasks.user_id The id for the user's
26 | * @apiSuccessExample {json} Success
27 | * HTTP/1.1 200 OK
28 | * [{
29 | * "id": 1,
30 | * "title": "Study",
31 | * "done": false,
32 | * "updated_at": "2016-02-10T15:46:51.778Z",
33 | * "created_at": "2016-02-10T15:46:51.778Z",
34 | * "user_id": 1
35 | * }]
36 | * @apiErrorExample {json} List error
37 | * HTTP/1.1 412 Precondition Failed
38 | */
39 | .get((req, res) => {
40 | console.log(`req.body: ${req.body}`);
41 | Tasks.findAll({where: {user_id: req.user.id} })
42 | .then(result => res.json(result))
43 | .catch(error => {
44 | res.status(412).json({msg: error.message});
45 | });
46 | })
47 |
48 | /**
49 | * @api {post} /tasks Register a new task
50 | * @apiGroup Tasks
51 | * @apiHeader {String} Authorization Token of authenticated user
52 | * @apiHeaderExample {json} Header
53 | * {
54 | * "Authorization": "xyz.abc.123.hgf"
55 | * }
56 | * @apiParam {String} title Task title
57 | * @apiParamExample {json} Input
58 | * {"title": "Study"}
59 | * @apiSuccess {Number} id Task id
60 | * @apiSuccess {String} title Task title
61 | * @apiSuccess {Boolean} done Task is done?
62 | * @apiSuccess {Date} updated_at Update's date
63 | * @apiSuccess {Date} created_at Register's date
64 | * @apiSuccess {Number} user_id The id for the user's
65 | * @apiSuccessExample {json} Success
66 | * HTTP/1.1 200 OK
67 | * {
68 | * "id": 1,
69 | * "title": "Study",
70 | * "done": false,
71 | * "updated_at": "2016-02-10T15:46:51.778Z",
72 | * "created_at": "2016-02-10T15:46:51.778Z",
73 | * "user_id": 1
74 | * }
75 | * @apiErrorExample {json} List error
76 | * HTTP/1.1 412 Precondition Failed
77 | */
78 | .post((req, res) => {
79 | req.body.user_id = req.user.id;
80 | Tasks.create(req.body)
81 | .then(result => res.json(result))
82 | .catch(error => {
83 | res.status(412).json({msg: error.message});
84 | });
85 | });
86 |
87 | app.route("/tasks/:id")
88 | .all(app.auth.authenticate())
89 |
90 | /**
91 | * @api {get} /tasks/:id get a task
92 | * @apiGroup Tasks
93 | * @apiHeader {String} Authorization Token of authenticated user
94 | * @apiHeaderExample {json} Header
95 | * {
96 | * "Authorization": "xyz.abc.123.hgf"
97 | * }
98 | * @apiParam {id} id Task id
99 | * @apiSuccess {Number} id Task id
100 | * @apiSuccess {String} title Task title
101 | * @apiSuccess {Boolean} done Task is done?
102 | * @apiSuccess {Date} updated_at Update's date
103 | * @apiSuccess {Date} created_at Register's date
104 | * @apiSuccess {Number} user_id The id for the user's
105 | * @apiSuccessExample {json} Success
106 | * HTTP/1.1 200 OK
107 | * {
108 | * "id": 1,
109 | * "title": "Study",
110 | * "done": false,
111 | * "updated_at": "2016-02-10T15:46:51.778Z",
112 | * "created_at": "2016-02-10T15:46:51.778Z",
113 | * "user_id": 1
114 | * }
115 | * @apiErrorExample {json} Task not found error
116 | * HTTP/1.1 404 Not Found
117 | * @apiErrorExample {json} Find error
118 | * HTTP/1.1 412 Precondition Failed
119 | */
120 | .get((req, res) => {
121 | Tasks.findOne({where: {
122 | id: req.params.id,
123 | user_id: req.user.id
124 | }})
125 | .then(result => {
126 | if (result) {
127 | res.json(result);
128 | } else {
129 | res.sendStatus(412);
130 | }
131 | })
132 | .catch(error => {
133 | res.status(412).json({msg: error.message});
134 | });
135 | })
136 |
137 | /**
138 | * @api {put} /tasks/:id update a task
139 | * @apiGroup Tasks
140 | * @apiHeader {String} Authorization Token of authenticated user
141 | * @apiHeaderExample {json} Header
142 | * {
143 | * "Authorization": "xyz.abc.123.hgf"
144 | * }
145 | * @apiParam {id} id Task id
146 | * @apiParam {String} title Task title
147 | * @apiParam {Boolean} done Task is done?
148 | * @apiParamExample {json} Input
149 | * {
150 | * "title": "Study",
151 | * "done": true,
152 | * }
153 | * @apiSuccessExample {json} Success
154 | * HTTP/1.1 404 Not Found
155 | * @apiErrorExample {json} Update error
156 | * HTTP/1.1 412 Precondition Failed
157 | */
158 | .put((req, res) => {
159 | Tasks.update(req.body, {where: {
160 | id: req.params.id,
161 | user_id: req.user.id
162 | }})
163 | .then(result => res.sendStatus(204))
164 | .catch(error => {
165 | res.status(412).json({msg: error.message});
166 | });
167 | })
168 |
169 | /**
170 | * @api {delete} /tasks/:id delete a task
171 | * @apiGroup Tasks
172 | * @apiHeader {String} Authorization Token of authenticated user
173 | * @apiHeaderExample {json} Header
174 | * {
175 | * "Authorization": "xyz.abc.123.hgf"
176 | * }
177 | * @apiParam {id} id Task id
178 | * @apiSuccessExample {json} Success
179 | * HTTP/1.1 204 Not Content
180 | * @apiErrorExample {json} Delete error
181 | * HTTP/1.1 412 Precondition Failed
182 | */
183 | .delete((req, res) => {
184 | Tasks.destroy({where: {
185 | id: req.params.id,
186 | user_id: req.user.id
187 | }})
188 | .then(result => res.sendStatus(204))
189 | .catch(error => {
190 | res.status(412).json({msg: error.message});
191 | });
192 | });
193 | };
--------------------------------------------------------------------------------
/routers/token.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/19.
3 | */
4 | import jwt from "jwt-simple"
5 |
6 | module.exports = app => {
7 | "use strict";
8 | const cfg = app.libs.config;
9 | const Users = app.db.models.Users;
10 |
11 | /**
12 | * @api {post} /token Authentication Token
13 | * @apiGroup Credentials
14 | * @apiParam {String} email User email
15 | * @apiParam {String} password User password
16 | * @apiParamExample {json} Input
17 | * {
18 | * "emali": "James@mc.com",
19 | * "password": "123456"
20 | * }
21 | * @apiSuccess {String} token Token of authenticated user
22 | * @apiSuccessExample {json} Success
23 | * HTTP/1.1 200 OK
24 | * {"token": "xyz.abc.123.hgf"}
25 | * @apiErrorExample {json} Authentication error
26 | * HTTP/1.1 401 Unauthorized
27 | */
28 | app.post("/token", (req, res) => {
29 | const email = req.body.email;
30 | const password = req.body.password;
31 | if (email && password) {
32 | Users.findOne({where: {email: email}})
33 | .then(user => {
34 | if (Users.isPassword(user.password, password)) {
35 | const payload = {id: user.id};
36 | res.json({
37 | token: jwt.encode(payload, cfg.jwtSecret)
38 | });
39 | } else {
40 | res.sendStatus(401);
41 | }
42 | })
43 | .catch(error => res.sendStatus(401));
44 | } else {
45 | res.sendStatus(401);
46 | }
47 | });
48 | };
--------------------------------------------------------------------------------
/routers/users.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by machao on 17/9/16.
3 | */
4 | module.exports = app => {
5 | "use strict";
6 | const Users = app.db.models.Users;
7 |
8 | app.route("/user")
9 | .all(app.auth.authenticate())
10 | /**
11 | * @api {get} /user Return the authenticated user's data
12 | * @apiGroup User
13 | * @apiHeader {String} Authorization Token of authenticated user
14 | * @apiHeaderExample {json} Header
15 | * {"Authorization": "JWT xyz.abc.123.hgj"}
16 | * @apiSuccess {Number} id User id
17 | * @apiSuccess {String} name User name
18 | * @apiSuccess {String} email User email
19 | * @apiSuccessExample {json} Success
20 | * HTTP/1.1 200 OK
21 | * {
22 | * "id": 1,
23 | * "name": "James",
24 | * "email": "James@mc.com
25 | * }
26 | * @apiErrorExample {json} Find error
27 | * HTTP/1.1 412 Precondition Failed
28 | */
29 | .get((req, res) => {
30 | Users.findById(req.user.id, {
31 | attributes: ["id", "name", "email"]
32 | })
33 | .then(result => res.json(result))
34 | .catch(error => {
35 | res.status(412).json({msg: error.message});
36 | });
37 | })
38 |
39 | /**
40 | * @api {delete} /user Deletes an authenticated user
41 | * @apiGroup User
42 | * @apiHeader {String} Authorization Token of authenticated user
43 | * @apiHeaderExample {josn} Header
44 | * {"Authorization": "JWT xyz.abc.123.hgj"}
45 | * @apiSuccessExample {json} Success
46 | * HTTP/1.1 204 No Content
47 | * @apiErrorExample {json} Delete error
48 | * HTTP/1.1 412 Precondition Failed
49 | */
50 | .delete((req, res) => {
51 | console.log(`delete..........${req.user.id}`);
52 | Users.destroy({where: {id: req.user.id}})
53 | .then(result => {
54 | console.log(`result: ${result}`);
55 | return res.sendStatus(204);
56 | })
57 | .catch(error => {
58 | console.log(`resultfsaddfsf`);
59 | res.status(412).json({msg: error.message});
60 | });
61 | });
62 |
63 | /**
64 | * @api {post} /users Register a new user
65 | * @apiGroup User
66 | * @apiParam {String} name User name
67 | * @apiParam {String} email User email
68 | * @apiParam {String} password User password
69 | * @apiParamExample {json} Input
70 | * {
71 | * "name": "James",
72 | * "email": "James@mc.com",
73 | * "password": "123456"
74 | * }
75 | * @apiSuccess {Number} id User id
76 | * @apiSuccess {String} name User name
77 | * @apiSuccess {String} email User email
78 | * @apiSuccess {String} password User encrypted password
79 | * @apiSuccess {Date} update_at Update's date
80 | * @apiSuccess {Date} create_at Rigister's date
81 | * @apiSuccessExample {json} Success
82 | * {
83 | * "id": 1,
84 | * "name": "James",
85 | * "email": "James@mc.com",
86 | * "updated_at": "2016-02-10T15:20:11.700Z",
87 | * "created_at": "2016-02-10T15:29:11.700Z"
88 | * }
89 | * @apiErrorExample {json} Rergister error
90 | * HTTP/1.1 412 Precondition Failed
91 | */
92 | app.post("/users", (req, res) => {
93 | Users.create(req.body)
94 | .then(result => res.json(result))
95 | .catch(error => {
96 | res.status(412).json({msg: error.message});
97 | });
98 | });
99 | };
--------------------------------------------------------------------------------
/test/helpers.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 | import supertest from "supertest"
5 | import chai from "chai"
6 | import app from "../index"
7 |
8 | global.app = app;
9 | global.request = supertest(app);
10 | global.expect = chai.expect;
11 |
--------------------------------------------------------------------------------
/test/mocha.opts:
--------------------------------------------------------------------------------
1 | --require test/helpers
2 | --reporter spec
3 | --compilers js:babel-register
4 | --slow 5000=
--------------------------------------------------------------------------------
/test/routes/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 |
5 | describe("Routes: Index", () => {
6 | "use strict";
7 | describe("GET /", () => {
8 | it("returns the API status", done => {
9 | request.get("/")
10 | .expect(200)
11 | .end((err, res) => {
12 | const expected = {status: "NTask API"};
13 | expect(res.body).to.eql(expected);
14 | done(err);
15 | });
16 | });
17 | });
18 | });
--------------------------------------------------------------------------------
/test/routes/tasks.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 | import jwt from "jwt-simple"
5 |
6 | describe("Routes: Tasks", () => {
7 | "use strict";
8 |
9 | const Users = app.db.models.Users;
10 | const Tasks = app.db.models.Tasks;
11 | const jwtSecret = app.libs.config.jwtSecret;
12 | let token;
13 | let fakeTask;
14 |
15 | beforeEach(done => {
16 | Users
17 | .destroy({where: {}})
18 | .then(() => Users.create({
19 | name: "James",
20 | email: "James@mc.com",
21 | password: "123456"
22 | }))
23 | .then(user => {
24 | Tasks
25 | .destroy({where:{}})
26 | .then(() => Tasks.bulkCreate([{
27 | id: 1,
28 | title: "Work",
29 | user_id: user.id
30 | }, {
31 | id: 2,
32 | title: "Study",
33 | user_id: user.id
34 | }]))
35 | .then(tasks => {
36 | fakeTask = tasks[0];
37 | token = jwt.encode({id: user.id}, jwtSecret);
38 | // console.log(`fakeTask: ${fakeTask}, token: ${token}`);
39 | done();
40 | });
41 | });
42 | });
43 |
44 | describe("POST /tasks", () => {
45 | describe("status 200", () => {
46 | it("creates a new task", done => {
47 | request.post("/tasks")
48 | .set("Authorization", `JWT ${token}`)
49 | .send({title: "Run"})
50 | .expect(200)
51 | .end((err, res) => {
52 | console.log(`err: ${err}, res: ${JSON.stringify(res.body)}`);
53 | expect(res.body.title).to.eql("Run");
54 | expect(res.body.done).to.be.false;
55 | done(err);
56 | });
57 | });
58 | });
59 | });
60 |
61 | describe("GET /tasks", () => {
62 | describe("status 200", () => {
63 | it("returns a list of tasks", done => {
64 |
65 | request.get("/tasks")
66 | .set("Authorization", `JWT ${token}`)
67 | .expect(200)
68 | .end((err, res) => {
69 | console.log(`err: ${err}, res: ${JSON.stringify(res.body)}`);
70 | expect(res.body).to.have.length(2);
71 | expect(res.body[0].title).to.eql("Work");
72 | expect(res.body[1].title).to.eql("Study");
73 | done(err);
74 | });
75 | });
76 | });
77 | });
78 |
79 |
80 |
81 | describe("GET /tasks/:id", () => {
82 | describe("status 200", () => {
83 | it("returns one tasks", done => {
84 | request.get(`/tasks/${fakeTask.id}`)
85 | .set("Authorization", `JWT ${token}`)
86 | .expect(200)
87 | .end((err, res) => {
88 | expect(res.body.title).to.eql("Work");
89 | done(err);
90 | });
91 | });
92 | });
93 |
94 | describe("status 404", () => {
95 | it("throws error when task not exist", done => {
96 | request.get("/tasks/0")
97 | .set("Authorization", `JWT ${token}`)
98 | .expect(412)
99 | .end((err, res) => {
100 | done(err);
101 | });
102 | });
103 | });
104 | });
105 |
106 | describe("PUT /tasks/:id", () => {
107 | describe("status 204", () => {
108 | it("update a task", done => {
109 | request.put(`/tasks/${fakeTask.id}`)
110 | .set("Authorization", `JWT ${token}`)
111 | .send({
112 | title: "Travel",
113 | done: true
114 | })
115 | .expect(204)
116 | .end((err, res) => done(err));
117 | });
118 | });
119 | });
120 |
121 | describe("DELETE /tasks/:id", () => {
122 | describe("status 204", () => {
123 | it("remove a task", done => {
124 | request.delete(`/tasks/${fakeTask.id}`)
125 | .set("Authorization", `JWT ${token}`)
126 | .expect(204)
127 | .end((err, res) => done(err));
128 | });
129 | });
130 | });
131 | });
--------------------------------------------------------------------------------
/test/routes/token.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/20.
3 | */
4 | describe("Routes: Token", () => {
5 | "use strict";
6 | const Users = app.db.models.Users;
7 |
8 | describe("POST /token", () => {
9 | beforeEach(done => {
10 | Users
11 | .destroy({where: {}})
12 | .then(() => {
13 | Users.create({
14 | name: "James",
15 | email: "James@mc.com",
16 | password: "123456"
17 | });
18 | })
19 | .then(() => done());
20 | });
21 |
22 | describe("status 200", () => {
23 | it("returns authenticated user token", done => {
24 | request.post("/token")
25 | .send({
26 | email: "James@mc.com",
27 | password: "123456"
28 | })
29 | .expect(200)
30 | .end((err, res) => {
31 | expect(res.body).to.include.keys("token");
32 | done(err);
33 | });
34 | });
35 | });
36 |
37 |
38 | describe("status 401", () => {
39 | it("throws error when password is incorrect", done => {
40 | request.post("/token")
41 | .send({
42 | email: "James@mc.com",
43 | password: "wrong_password"
44 | })
45 | .expect(401)
46 | .end((err, res) => {
47 | done(err);
48 | });
49 | });
50 |
51 | it("throws error when email not exist", done => {
52 | request.post("/token")
53 | .send({
54 | email: "wrong@mc.com",
55 | password: "123456"
56 | })
57 | .expect(401)
58 | .end((err, res) => {
59 | done(err);
60 | });
61 | });
62 |
63 | it("throws error when email and password are blank", done => {
64 | request.post("/token")
65 | .expect(401)
66 | .end((err, res) => {
67 | done(err);
68 | });
69 | });
70 | });
71 | });
72 | });
--------------------------------------------------------------------------------
/test/routes/users.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by M.C on 2017/9/21.
3 | */
4 | import jwt from "jwt-simple"
5 |
6 | describe("Routes: Users", () => {
7 | "use strict";
8 | const Users = app.db.models.Users;
9 | const jwtSecret = app.libs.config.jwtSecret;
10 | let token;
11 |
12 | beforeEach(done => {
13 | Users
14 | .destroy({where: {}})
15 | .then(() => {
16 | return Users.create({
17 | name: "Bond",
18 | email: "Bond@mc.com",
19 | password: "123456"
20 | });
21 | })
22 | .then(user => {
23 | token = jwt.encode({id: user.id}, jwtSecret);
24 | done();
25 | });
26 | });
27 |
28 | describe("GET /user", () => {
29 | describe("status 200", () => {
30 | it("returns an authenticated user", done => {
31 | request.get("/user")
32 | .set("Authorization", `JWT ${token}`)
33 | .expect(200)
34 | .end((err, res) => {
35 | expect(res.body.name).to.eql("Bond");
36 | expect(res.body.email).to.eql("Bond@mc.com");
37 | done(err);
38 | });
39 | });
40 | });
41 | });
42 |
43 | describe("DELETE /user", () => {
44 | describe("status 204", () => {
45 | it("deletes an authenticated user", done => {
46 | request.delete("/user")
47 | .set("Authorization", `JWT ${token}`)
48 | .expect(204)
49 | .end((err, res) => {
50 | console.log(`err: ${err}`);
51 | done(err);
52 | });
53 | });
54 | });
55 | });
56 |
57 | describe("POST /users", () => {
58 | describe("status 200", () => {
59 | it("creates a new user", done => {
60 | request.post("/users")
61 | .send({
62 | name: "machao",
63 | email: "machao@mc.com",
64 | password: "123456"
65 | })
66 | .expect(200)
67 | .end((err, res) => {
68 | expect(res.body.name).to.eql("machao");
69 | expect(res.body.email).to.eql("machao@mc.com");
70 | done(err);
71 | });
72 | });
73 | });
74 | });
75 | });
--------------------------------------------------------------------------------