├── .gitignore ├── LICENSE ├── README.md ├── arch ├── app.spec.ts └── dashboard.spec.ts ├── contract ├── index.ts └── verify-budget.pact.ts ├── e2e ├── auth.e2e.ts ├── expenses.e2e.ts └── utils.ts ├── integration └── expenses.controller.it.ts ├── jest.config.js ├── log └── .gitkeep ├── nodemon.json ├── package-lock.json ├── package.json ├── sonar-project.properties ├── src ├── app │ ├── admin │ │ ├── admin.controller.ts │ │ └── admin.service.ts │ ├── auth │ │ ├── auth.controller.ts │ │ ├── auth.validator.ts │ │ ├── external-auth.controller.ts │ │ ├── passport.ts │ │ ├── repositories │ │ │ ├── account.repository.ts │ │ │ ├── in-memory │ │ │ │ ├── in-memory-account.repository.ts │ │ │ │ ├── in-memory-login-failure.repository.ts │ │ │ │ └── in-memory-user.repository.ts │ │ │ ├── login-failure.repository.ts │ │ │ └── user.repository.ts │ │ ├── role.middleware.ts │ │ └── services │ │ │ ├── auth.service.instance.ts │ │ │ ├── auth.service.ts │ │ │ ├── external-auth │ │ │ ├── external-auth.factory.ts │ │ │ ├── external-auth.provider.ts │ │ │ ├── external-auth.service.ts │ │ │ ├── github-auth.provider.ts │ │ │ ├── google-auth.provider.ts │ │ │ └── state.service.ts │ │ │ ├── jwt-auth.service.ts │ │ │ ├── login.throttler.ts │ │ │ ├── otp.service.ts │ │ │ ├── password.service.ts │ │ │ ├── session-auth.service.spec.ts │ │ │ ├── session-auth.service.ts │ │ │ └── signup.service.ts │ ├── auth0 │ │ ├── auth0.api.ts │ │ ├── auth0.controller.ts │ │ └── auth0.service.ts │ ├── dashboard │ │ ├── budget.repository.ts │ │ ├── dashboard.controller.ts │ │ └── in-memory-budget.repository.ts │ ├── expenses │ │ ├── expenses.controller.ts │ │ ├── expenses.middleware.ts │ │ ├── expenses.repository.ts │ │ ├── expenses.validator.ts │ │ └── in-memory-expenses.repository.ts │ └── settings │ │ ├── account │ │ ├── account.controller.ts │ │ ├── account.middleware.ts │ │ └── account.service.ts │ │ ├── categories │ │ ├── categories.controller.ts │ │ ├── categories.middleware.ts │ │ ├── categories.repository.ts │ │ └── in-memory-categories.repository.ts │ │ └── settings.controller.ts ├── config │ ├── index.ts │ └── secret.ts ├── index.ts ├── models │ ├── account.ts │ ├── authRequest.ts │ ├── budget.ts │ ├── budgetDefinition.ts │ ├── budgetSummary.ts │ ├── category.ts │ ├── expense.ts │ ├── login.failure.ts │ ├── period.ts │ ├── token.ts │ ├── types.ts │ ├── user.ts │ └── userInfo.ts ├── routes.ts └── utils │ ├── controller.utils.ts │ ├── error-handler.ts │ ├── logger.ts │ ├── serve-index.ts │ └── set-csrf-cookie.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /log/* 3 | /src/config/secret.ts 4 | /coverage 5 | /.scannerwork 6 | test-report.xml 7 | .dccache 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Budget application 2 | 3 | This is the final project in the training program [Web Security Academy](https://websecurity-academy.com/?utm_source=github&utm_medium=referral&utm_campaign=budget-node-readme). It represents a real-life use case of personal money tracker. There are five main feature modules: *Auth*, *Dashboard*, *Expenses*, *Settings* and *Admin* with many security measures implemented described below. The project implements [role-based access control](https://en.wikipedia.org/wiki/Role-based_access_control) (RBAC), giving different users different permissions. This is the backend part to the accompanying [frontend](https://github.com/bartosz-io/budget-angular) in Angular. 4 | 5 | ## Main modules 6 | 7 | | Auth | Dashboard | Expenses | Settings | Admin | 8 | | ------ | ------ | ------ | ----- | ----- | 9 | | Login, signup and recover password | Read budgets and account summary | List and manage the expenses belonging to the account | Manage account users and expense categories for account | Manage active sessions of logged users | 10 | 11 | ## Roles in the system 12 | 13 | | Role | Permission | 14 | | ------ | ------ | 15 | | Reader | Read expenses and categories for the account. | 16 | | Owner | Create, read, update and delete expenses, categories. Create and delete account's users. | 17 | | Admin | Read and delete active users' sessions. | 18 | 19 | ## Mock users 20 | You can find mock users in [in-memory-user.repository.ts](https://github.com/bartosz-io/budget-node/blob/master/src/app/auth/repositories/in-memory/in-memory-user.repository.ts#L62). 21 | 22 | ## Authentication mechanisms 23 | 24 | There are two authentication mechanism implemented in both Angular and Node.js parts: 25 | 26 | - Session cookies 27 | - JWT Tokens 28 | 29 | In Node part you can select one mechanism with config setting in `src/config/index.ts` as presented below. 30 | Remember that both Angular and Node.js selections must match! 31 | 32 | ```ts 33 | auth: 'session' as 'session' | 'jwt' 34 | ``` 35 | 36 | ## Implemented security measures 37 | 38 | ### Access level logging 39 | 40 | Every HTTP request is logged with [Morgan logger](https://github.com/expressjs/morgan) and you can configure it with config options in `src/config/index.ts` as below. The presented example is using npm package `rotating-file-stream` to save logs to `access.log` with 1 day rotation. 41 | 42 | ```ts 43 | morganPattern: 'common', 44 | morganStream: rfs.createStream('access.log', { 45 | interval: '1d', 46 | path: path.join(process.cwd(), 'log') 47 | }), 48 | ``` 49 | 50 | The logs with `common` morgan pattern look like below. `::1` represents `localhost` address. You can use different configurations prefined in morgan logger (check the docs). 51 | 52 | ```log 53 | ::1 - - [30/Jul/2020:16:58:58 +0000] "GET /login HTTP/1.1" 404 144 54 | ::1 - - [30/Jul/2020:16:59:02 +0000] "GET /auth/user HTTP/1.1" 200 66 55 | ::1 - - [30/Jul/2020:16:59:03 +0000] "GET /api/budgets/3/2020 HTTP/1.1" 304 - 56 | ::1 - - [30/Jul/2020:16:59:03 +0000] "GET /api/budget-summary/3/2020 HTTP/1.1" 404 34 57 | ::1 - - [30/Jul/2020:16:59:04 +0000] "GET /auth/logout HTTP/1.1" 204 - 58 | ``` 59 | 60 | ### Application events logging 61 | 62 | Every meaningful event in application is logged with [Bunyan](https://github.com/trentm/node-bunyan) logger. This allows to trace back what happened in the system from the application logic perspective. For example user signup is logged in `signup.service.ts` as below. Note the `log.info` invocations with a string containing module name as the first segment of the log message (`auth.*` in this case). This helps to analyze logs later on. For example `log.info('auth.confirmation_successful', { email });` is called upon successful user confirmation after signup. 63 | 64 | ```ts 65 | export class SignupService { 66 | 67 | signup(signupRequest: AuthRequest): Promise { 68 | const confirmationCode = randtoken.uid(256); 69 | return bcrypt.hash(signupRequest.password, 10) // 10 is the salt length (implicit salt generation) 70 | .then(hashedPassword => accountRepository.createAccount({}) 71 | .then(accountId => Promise.all([ 72 | categoriesRepository.createDefaultCategories(accountId), 73 | userRepository.createUser({ 74 | accountId: accountId, email: signupRequest.email, 75 | password: hashedPassword, role: 'OWNER', 76 | confirmed: false, confirmationCode 77 | }) 78 | ])).then(() => { 79 | log.info('auth.signup_successful', { email: signupRequest.email }); 80 | this.sendConfirmationEmail(signupRequest.email, confirmationCode); 81 | return Promise.resolve(); 82 | }).catch(error => { 83 | log.error('auth.signup_failed', { email: signupRequest.email }); 84 | throw error; // rethrow the error for the controller 85 | }) 86 | ); 87 | } 88 | 89 | confirm(email: string, confirmationCode: string): Promise { 90 | return userRepository.getUserByEmail(email).then(user => { 91 | if (user && !user.confirmed && user.confirmationCode === confirmationCode) { 92 | user.confirmed = true; 93 | user.confirmationCode = undefined; 94 | log.info('auth.confirmation_successful', { email }); 95 | } else { 96 | log.warn('auth.confirmation_failed', { email }); 97 | return Promise.reject(); 98 | } 99 | }); 100 | } 101 | 102 | private sendConfirmationEmail(email: string, code: string) { 103 | const link = `${CONFIG.clientUrl}/confirm?email=${email}&code=${code}`; 104 | console.log(`>>> LINK >>>: ${link}`); // mock email sending 😎 105 | log.info('auth.signup_confirmation_email_sent', { email }); 106 | } 107 | } 108 | ``` 109 | 110 | ### Throttling failed logins 111 | 112 | In order to prevent brute-force, dictionary attacks or credential suffing application prevents prevents subsequent logins after several failed logins in a defined timeframe. For example you can define login throttling to allow maximum 3 login failures in 10 minutes time window in config as below. Then user needs to wait until the system allows to login with the given username. This feature is implemented in `src/app/auth/services/login.throttler.ts`. 113 | 114 | ```ts 115 | loginThrottle: { 116 | maxFailures: 3, 117 | timeWindowInMinutes: 10 118 | } 119 | ``` 120 | 121 | ### Input sanitization and validation 122 | 123 | Every input that comes from the frontend is sanitizend and validated with [validator.js](https://github.com/validatorjs/validator.js). Here are some examples from `expenses.validator.ts` used in `expenses.controller.ts`. 124 | 125 | ```ts 126 | function value() { 127 | return check('value').isNumeric() 128 | .withMessage('must be a number'); 129 | } 130 | 131 | function datetime() { 132 | return check('datetime').escape(); 133 | } 134 | 135 | function counterparty() { 136 | return check('counterparty').escape(); 137 | } 138 | 139 | function errorParser() { 140 | return function (req: Request, res: Response, next: NextFunction) { 141 | const errors = validationResult(req); 142 | if (!errors.isEmpty()) { 143 | log.warn('expenses.validation_failed', {errors: errors.array()}); 144 | res.status(422).json({ msg: formatErrors(errors.array()) }); 145 | } else { 146 | next(); 147 | } 148 | } 149 | } 150 | 151 | function formatErrors(errors: ValidationError[]) { 152 | return errors.map(e => `${e.param} ${e.msg}`).join(', '); 153 | } 154 | ``` 155 | 156 | ### Preventing calls without the proper role 157 | 158 | The system prevents "fooling" the frontend that the user poses the given role (for example faking `OWNER` role, but in reality this may be just a `READER` role). This kind of misuse of the system must be protected on the backend side. There are some middlewares implemented to check the proper role for a given operation. For example on the router level system checks the role with `router.use('/users', hasRole('OWNER'));`. Below you can find an example function from `role.middleware.ts`. Note, that the in case of system misuse the event is logged with the application logger. 159 | 160 | ```ts 161 | export function hasRole(roleToCheck: UserRole) { 162 | 163 | return function (req: Request, res: Response, next: NextFunction) { 164 | const user = req.user as User; 165 | 166 | if (!isRoleFound(user)) { 167 | handleRoleNotFound(user, res); 168 | } else if (user.role !== roleToCheck) { 169 | log.warn('auth.role_check_failure', { roleToCheck, user }); 170 | res.status(403).json({ msg: 'You are not authorized to perform this operation' }); 171 | next('Unauthorized'); 172 | } else { 173 | next(); 174 | } 175 | } 176 | } 177 | 178 | ``` 179 | 180 | ### License 181 | 182 | GPL-3.0 183 | -------------------------------------------------------------------------------- /arch/app.spec.ts: -------------------------------------------------------------------------------- 1 | import 'tsarch/dist/jest'; 2 | import { filesOfProject } from 'tsarch'; 3 | 4 | describe("Application", () => { 5 | 6 | jest.setTimeout(60000); 7 | 8 | it.skip("controllers should not depend on repositories", async () => { 9 | const rule = filesOfProject() 10 | .matchingPattern('.*controller\.ts') 11 | .shouldNot() 12 | .dependOnFiles() 13 | .matchingPattern('.*repository\.ts'); 14 | 15 | await expect(rule).toPassAsync(); 16 | }); 17 | 18 | it("controllers should not depend on apis", async () => { 19 | const rule = filesOfProject() 20 | .matchingPattern('.*controller\.ts') 21 | .shouldNot() 22 | .dependOnFiles() 23 | .matchingPattern('.*api\.ts'); 24 | 25 | await expect(rule).toPassAsync(); 26 | }); 27 | 28 | it.skip("services should follow naming convention", async () => { 29 | const rule = filesOfProject() 30 | .inFolder('services') 31 | .should() 32 | .matchPattern('.*service(\.spec)?\.ts|.*provider\.ts|.*factory\.ts|.*instance\.ts'); 33 | 34 | await expect(rule).toPassAsync(); 35 | }); 36 | 37 | it("repositories should follow naming convention", async () => { 38 | const rule = filesOfProject() 39 | .inFolder('repositories') 40 | .should() 41 | .matchPattern('.*repository\.ts'); 42 | 43 | await expect(rule).toPassAsync(); 44 | }); 45 | 46 | it("repositories should not depend on services and controllers", async () => { 47 | const rule = filesOfProject() 48 | .matchingPattern('.*repository\.ts') 49 | .shouldNot() 50 | .dependOnFiles() 51 | .matchingPattern('.*service\.ts|.*controller\.ts'); 52 | 53 | await expect(rule).toPassAsync(); 54 | }); 55 | 56 | it("services should not depend on controllers", async () => { 57 | const rule = filesOfProject() 58 | .matchingPattern('.*service\.ts') 59 | .shouldNot() 60 | .dependOnFiles() 61 | .matchingPattern('.*controller\.ts'); 62 | 63 | await expect(rule).toPassAsync(); 64 | }); 65 | 66 | it("application logic should be cycle free", async () => { 67 | const rule = filesOfProject() 68 | .inFolder("app") 69 | .should() 70 | .beFreeOfCycles(); 71 | 72 | await expect(rule).toPassAsync(); 73 | }); 74 | 75 | }); -------------------------------------------------------------------------------- /arch/dashboard.spec.ts: -------------------------------------------------------------------------------- 1 | import 'tsarch/dist/jest'; 2 | import { filesOfProject } from 'tsarch'; 3 | 4 | describe("Dashboard module", () => { 5 | 6 | jest.setTimeout(60000); 7 | 8 | it("should be independent from expenses", async () => { 9 | const rule = filesOfProject() 10 | .inFolder('dashboard') 11 | .shouldNot() 12 | .dependOnFiles() 13 | .inFolder('expenses'); 14 | 15 | await expect(rule).toPassAsync(); 16 | }); 17 | 18 | it.skip("should be independent from settings", async () => { 19 | const rule = filesOfProject() 20 | .inFolder('dashboard') 21 | .shouldNot() 22 | .dependOnFiles() 23 | .inFolder('settings'); 24 | 25 | await expect(rule).toPassAsync(); 26 | }); 27 | 28 | it("should be independent from admin", async () => { 29 | const rule = filesOfProject() 30 | .inFolder('dashboard') 31 | .shouldNot() 32 | .dependOnFiles() 33 | .inFolder('admin'); 34 | 35 | await expect(rule).toPassAsync(); 36 | }); 37 | 38 | it("should be independent from auth", async () => { 39 | const rule = filesOfProject() 40 | .inFolder('dashboard') 41 | .shouldNot() 42 | .dependOnFiles() 43 | .inFolder('auth'); 44 | 45 | await expect(rule).toPassAsync(); 46 | }); 47 | 48 | }); -------------------------------------------------------------------------------- /contract/index.ts: -------------------------------------------------------------------------------- 1 | import "./verify-budget.pact"; -------------------------------------------------------------------------------- /contract/verify-budget.pact.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import express = require('express'); 3 | import { Request, Response, NextFunction } from 'express'; 4 | import { Express } from 'express-serve-static-core'; 5 | import { Server } from 'http'; 6 | import { Verifier } from '@pact-foundation/pact' 7 | 8 | import { DashboardController } from './../src/app/dashboard/dashboard.controller'; 9 | import { InMemoryBudgetRepository } from './../src/app/dashboard/in-memory-budget.repository'; 10 | 11 | describe('Budget Api provider verification', () => { 12 | 13 | const port = 8080; 14 | let app: Express; 15 | let server: Server; 16 | let givenRequest: (req: Request) => void; 17 | 18 | beforeAll((done) => { 19 | app = express(); 20 | app.use(express.json()); 21 | app.use((req: Request, _res: Response, next: NextFunction) => { 22 | givenRequest(req); 23 | next(); 24 | }); 25 | app.use(new DashboardController(new InMemoryBudgetRepository()).getRouter()); 26 | 27 | server = app.listen(port, () => done()); 28 | }); 29 | 30 | afterAll(() => server.close()); 31 | 32 | it('passes for the all interactions', async () => { 33 | 34 | givenRequest = (req) => { 35 | req.user = { accountId: '1' }; 36 | } 37 | 38 | const options = { 39 | providerBaseUrl: 'http://localhost:8080', 40 | pactUrls: [path.resolve(__dirname, './../../pacts/budgetclient-budgetprovider.json')], 41 | // we can also point here to the Pact Broker to get the contracts 42 | } 43 | 44 | await new Verifier(options).verifyProvider(); 45 | }); 46 | 47 | }); 48 | -------------------------------------------------------------------------------- /e2e/auth.e2e.ts: -------------------------------------------------------------------------------- 1 | import { Server } from 'http'; 2 | import * as request from 'supertest'; 3 | import { buildProdServer, getRandomPort } from './utils'; 4 | 5 | describe('Authorization', () => { 6 | 7 | let server: Server; 8 | let port: number; 9 | let apiUrl: string; 10 | let host = 'http://localhost'; 11 | 12 | beforeAll((done) => { 13 | port = getRandomPort(); 14 | apiUrl = `${host}:${port}/api`; 15 | server = buildProdServer(port, () => done()); 16 | }); 17 | 18 | afterAll(() => server.close()); 19 | 20 | it('fails to login with invalid password', (done) => { 21 | 22 | request(apiUrl) 23 | .post('/auth/login') 24 | .send({ email: 'bartosz@app.com', password: 'invalid' }) 25 | .expect(401) // HTTP 401 Unauthorized 26 | .then(() => done()); 27 | 28 | }); 29 | 30 | it('fails to get data without authorization', (done) => { 31 | 32 | request(apiUrl) 33 | .get('/expenses') 34 | .expect(401) // HTTP 401 Unauthorized 35 | .then(() => done()); 36 | 37 | }); 38 | 39 | it('logs in with valid password', (done) => { 40 | 41 | request(apiUrl) 42 | .post('/auth/login') 43 | .send({ email: 'bartosz@app.com', password: '123' }) 44 | .expect(200) // HTTP 200 OK 45 | .then(() => done()); 46 | 47 | }); 48 | 49 | }); -------------------------------------------------------------------------------- /e2e/expenses.e2e.ts: -------------------------------------------------------------------------------- 1 | import { Server } from 'http'; 2 | import * as request from 'supertest'; 3 | import * as faker from 'faker'; 4 | 5 | import { buildProdServer, getRandomPort, login } from './utils'; 6 | import { Expense } from '../src/models/expense'; 7 | import { Period } from '../src/models/period'; 8 | 9 | describe('Expenses', () => { 10 | 11 | let server: Server; 12 | let port: number; 13 | let apiUrl: string; 14 | let host = 'http://localhost'; 15 | 16 | beforeAll((done) => { 17 | port = getRandomPort(); 18 | apiUrl = `${host}:${port}/api`; 19 | server = buildProdServer(port, () => done()); 20 | }); 21 | 22 | afterAll(() => server.close()); 23 | 24 | it('login => get expenses', (done) => { 25 | 26 | login(apiUrl).then((jwt) => { 27 | request(apiUrl) 28 | .get('/expenses/?month=3&year=2020') 29 | .set('Authorization', `Bearer ${jwt}`) 30 | .expect(200) // HTTP 200 OK 31 | .then((response) => { 32 | expect(response.body.length).toEqual(2); 33 | expect(response.body[0].id).toEqual('1'); 34 | expect(response.body[1].id).toEqual('2'); 35 | expect(response.body[0].value).toEqual(expect.any(Number)); 36 | expect(response.body[1].value).toEqual(expect.any(Number)); 37 | done(); 38 | }) 39 | }); 40 | 41 | }); 42 | 43 | it('login => add expense => get expenses', (done) => { 44 | 45 | const period = new Period(10, 2021); 46 | const newExpense: Expense = { 47 | accountId: '1', 48 | value: faker.datatype.number(9999), 49 | // months are indexed from 0, so 9 is actually October (10th month) 50 | datetime: faker.date.between(new Date(2021, 9, 1), new Date(2021, 9, 31)), 51 | period: period, 52 | categoryId: '1', 53 | counterparty: faker.company.companyName() 54 | } 55 | 56 | login(apiUrl).then((jwt) => { 57 | 58 | // add expense 59 | request(apiUrl) 60 | .post('/expenses') 61 | .send(newExpense) 62 | .set('Authorization', `Bearer ${jwt}`) 63 | .expect(201) // HTTP 201 Created 64 | .then(() => { 65 | 66 | // get expenses 67 | request(apiUrl) 68 | .get(`/expenses?month=${period.month}&year=${period.year}`) 69 | .set('Authorization', `Bearer ${jwt}`) 70 | .expect(200) // HTTP 200 OK 71 | .then((response) => { 72 | expect(new Date(response.body[0].datetime)).toEqual(newExpense.datetime); 73 | expect(response.body[0].counterparty).toEqual(newExpense.counterparty); 74 | expect(response.body[0].accountId).toEqual(newExpense.accountId); 75 | expect(response.body[0].period).toEqual(newExpense.period); 76 | expect(response.body[0].value).toEqual(newExpense.value); 77 | done(); 78 | }) 79 | }) 80 | }); 81 | }); 82 | 83 | }); 84 | 85 | -------------------------------------------------------------------------------- /e2e/utils.ts: -------------------------------------------------------------------------------- 1 | import express = require('express'); 2 | import session = require('express-session'); 3 | import morgan = require('morgan'); 4 | import cors = require('cors'); 5 | import passport = require('passport'); 6 | import { Server } from 'http'; 7 | import * as request from 'supertest'; 8 | 9 | import errorHandler from './../src/utils/error-handler'; 10 | import logger from './../src/utils/logger'; 11 | import routes from './../src/routes'; 12 | import config from './../src/config'; 13 | 14 | export function buildProdServer(port: number, callback: () => void): Server { 15 | 16 | const app = express(); 17 | app.use(session(config.sessionConfig)); 18 | app.use(morgan(config.morganPattern, { stream: config.morganStream })); 19 | app.use(express.json()); 20 | app.use(express.urlencoded({ extended: true })); 21 | app.use(passport.initialize()); 22 | app.use(cors()); 23 | app.use(errorHandler()); 24 | app.use(logger.initialize()); 25 | app.use(routes); 26 | 27 | return app.listen(port, () => { 28 | console.log('started production-like server on port: ' + port); 29 | callback(); 30 | }); 31 | 32 | } 33 | 34 | export function getRandomPort() { 35 | return 3000 + Math.floor((5000 * Math.random())) 36 | } 37 | 38 | export function login(apiUrl: string) { 39 | return request(apiUrl) 40 | .post('/auth/login') 41 | .send({ email: 'bartosz@app.com', password: '123' }) 42 | .expect(200) 43 | .then((response) => response.body.jwt); 44 | } -------------------------------------------------------------------------------- /integration/expenses.controller.it.ts: -------------------------------------------------------------------------------- 1 | import express = require('express'); 2 | import { Request, Response, NextFunction } from 'express'; 3 | import { Express } from 'express-serve-static-core'; 4 | import { Server } from 'http'; 5 | import * as request from 'supertest'; 6 | 7 | import { Period } from '../src/models/period'; 8 | import { Expense } from './../src/models/expense'; 9 | import { ExpensesController } from './../src/app/expenses/expenses.controller'; 10 | import { ExpensesRepository } from './../src/app/expenses/expenses.repository'; 11 | 12 | describe('ExpensesController', () => { 13 | 14 | const fakeExpense: Expense = { 15 | accountId: '1', 16 | value: 100, 17 | datetime: new Date(1, 1, 2021), 18 | period: new Period(10, 2021), 19 | categoryId: '1', 20 | counterparty: 'fake' 21 | } 22 | 23 | let expenseRepoStub: ExpensesRepository = { 24 | getExpense: jest.fn(() => Promise.resolve(fakeExpense)), 25 | getExpenses: jest.fn(() => Promise.resolve([fakeExpense])), 26 | getExpensesByCategory: jest.fn(() => Promise.resolve([fakeExpense])), 27 | createExpense: jest.fn(() => Promise.resolve()), 28 | updateExpense: jest.fn(() => Promise.resolve()), 29 | deleteExpense: jest.fn(() => Promise.resolve()) 30 | } 31 | 32 | let app: Express; 33 | let server: Server; 34 | let givenRequest: (req: Request) => void; 35 | const port = 3000; 36 | 37 | beforeAll((done) => { 38 | app = express(); 39 | app.use(express.json()); 40 | app.use((req: Request, _res: Response, next: NextFunction) => { 41 | givenRequest(req); 42 | next(); 43 | }); 44 | app.use(new ExpensesController(expenseRepoStub).getRouter()); 45 | 46 | server = app.listen(port, () => done()); 47 | }); 48 | 49 | afterAll(() => server.close()); 50 | 51 | it('returns error 500 when the user role is missing', (done) => { 52 | // given 53 | givenRequest = (req) => { 54 | req.user = { role: undefined }; 55 | } 56 | 57 | // when & then 58 | request(`http://localhost:${port}`) 59 | .get('/expenses') 60 | .expect('Content-Type', /json/) 61 | .expect(500) 62 | .then(() => done()); 63 | }); 64 | 65 | it('returns expenses for the READER role', (done) => { 66 | // given 67 | givenRequest = (req) => { 68 | req.user = { role: 'READER' }; 69 | } 70 | 71 | // when & then 72 | request(`http://localhost:${port}`) 73 | .get('/expenses') 74 | .expect('Content-Type', /json/) 75 | .expect(200) 76 | .then((response) => { 77 | expect(response.body[0].id).toEqual(fakeExpense.id); 78 | expect(response.body[0].accountId).toEqual(fakeExpense.accountId); 79 | expect(response.body[0].value).toEqual(fakeExpense.value); 80 | done(); 81 | }); 82 | }); 83 | 84 | it('returns 403 error when the READER tries to POST expense', (done) => { 85 | // given 86 | givenRequest = (req) => { 87 | req.user = { role: 'READER' }; 88 | } 89 | 90 | // when & then 91 | request(`http://localhost:${port}`) 92 | .post('/expenses') 93 | .send(fakeExpense) 94 | .expect('Content-Type', /json/) 95 | .expect(403) 96 | .then((response) => { 97 | expect(response.body.msg).toContain('not authorized'); 98 | done(); 99 | }); 100 | }); 101 | 102 | it('returns 201 success code when the OWNER tries to POST expense', (done) => { 103 | // given 104 | givenRequest = (req) => { 105 | req.user = { role: 'OWNER' }; 106 | } 107 | 108 | // when & then 109 | request(`http://localhost:${port}`) 110 | .post('/expenses') 111 | .send(fakeExpense) 112 | .set('Accept', 'application/json') 113 | .expect('Content-Type', /json/) 114 | .expect(201) 115 | .then((response) => { 116 | expect(response.body).toBeFalsy(); 117 | done(); 118 | }); 119 | }); 120 | 121 | }); -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testResultsProcessor: 'jest-sonar-reporter', 6 | 7 | collectCoverage: true, 8 | collectCoverageFrom: [ "src/**/*.{js,ts}" ], 9 | coverageReporters: ["lcov", "text-summary"], 10 | }; -------------------------------------------------------------------------------- /log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bartosz-io/budget-node/ff7311f03d92e4a48eebcc00004fdca97c494fbd/log/.gitkeep -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts", 4 | "exec": "ts-node src/index.ts" 5 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "budget-server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "nodemon --config nodemon.json", 8 | "start:log": "env LOGS=stdout nodemon --config nodemon.json | bunyan", 9 | "start:ci": "ts-node src/index.ts", 10 | "test": "jest", 11 | "test:watch": "jest --watch", 12 | "test:coverage": "jest --coverage", 13 | "test:integration": "jest --testMatch **/integration/*.(it).ts", 14 | "test:e2e": "jest --testMatch **/e2e/*.(e2e).ts", 15 | "test:arch": "jest --testMatch **/arch/*.(spec).ts", 16 | "test:pact": "jest --testMatch **/contract/*.(pact).ts", 17 | "sonar": "sonar-scanner.bat" 18 | }, 19 | "author": "", 20 | "license": "ISC", 21 | "dependencies": { 22 | "@types/bcryptjs": "^2.4.2", 23 | "@types/bunyan": "^1.8.7", 24 | "@types/csurf": "^1.11.2", 25 | "axios": "^0.21.1", 26 | "bcryptjs": "^2.4.3", 27 | "body-parser": "^1.19.0", 28 | "bunyan": "^1.8.15", 29 | "cors": "^2.8.5", 30 | "csurf": "^1.11.0", 31 | "express": "^4.17.3", 32 | "express-session": "^1.17.2", 33 | "express-validator": "^6.13.0", 34 | "jsonwebtoken": "^9.0.0", 35 | "morgan": "^1.10.0", 36 | "otplib": "^12.0.1", 37 | "passport": "^0.6.0", 38 | "passport-jwt": "^4.0.0", 39 | "rand-token": "^0.4.0", 40 | "rotating-file-stream": "^2.1.6" 41 | }, 42 | "devDependencies": { 43 | "@pact-foundation/pact": "^9.16.5", 44 | "@types/cors": "^2.8.12", 45 | "@types/express": "^4.17.13", 46 | "@types/express-session": "^1.17.4", 47 | "@types/faker": "^5.5.9", 48 | "@types/jest": "^27.0.2", 49 | "@types/morgan": "^1.9.3", 50 | "@types/node": "^12.20.36", 51 | "@types/passport": "^1.0.7", 52 | "@types/passport-jwt": "^3.0.6", 53 | "@types/supertest": "^2.0.11", 54 | "faker": "^5.5.3", 55 | "jest": "^27.3.1", 56 | "jest-sonar-reporter": "^2.0.0", 57 | "nodemon": "^2.0.20", 58 | "supertest": "^6.1.6", 59 | "ts-jest": "^27.0.7", 60 | "ts-node": "^8.10.2", 61 | "tsarch": "^5.2.0", 62 | "tslib": "^1.14.1", 63 | "typescript": "^3.9.10" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | # Organization and project keys are displayed in the right sidebar of the project homepage 2 | sonar.host.url=https://sonarcloud.io 3 | sonar.organization=bartosz-io 4 | sonar.projectKey=bartosz-io_budget-node 5 | 6 | sonar.sourceEncoding=UTF-8 7 | 8 | sonar.sources=src 9 | sonar.exclusions=**/*.spec.ts 10 | 11 | sonar.tests=src 12 | sonar.test.inclusions=**/*.spec.ts 13 | 14 | sonar.testExecutionReportPaths=test-report.xml 15 | sonar.javascript.lcov.reportPaths=coverage/lcov.info 16 | -------------------------------------------------------------------------------- /src/app/admin/admin.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { hasRole } from '../auth/role.middleware'; 3 | import { AdminService } from './admin.service'; 4 | 5 | const router = Router(); 6 | const adminService = new AdminService(); 7 | 8 | router.use(hasRole('ADMIN')); 9 | 10 | router.get('/sessions', function (req: Request, res: Response) { 11 | adminService.getActiveSessions().then(sessions => { 12 | res.json(sessions); 13 | }); 14 | }); 15 | 16 | router.delete('/sessions/:sessionId', function (req: Request, res: Response) { 17 | const sessionId = req.params.sessionId; 18 | adminService.destroySession(sessionId).then(() => res.sendStatus(204)); 19 | }); 20 | 21 | export default router; 22 | -------------------------------------------------------------------------------- /src/app/admin/admin.service.ts: -------------------------------------------------------------------------------- 1 | import config from './../../config'; 2 | import { SessionData, Store } from 'express-session'; 3 | 4 | export class AdminService { 5 | 6 | private store: Store = config.sessionConfig.store as Store; 7 | 8 | getActiveSessions(): Promise { 9 | return new Promise((resolve, reject) => { 10 | this.store.all?((err: any, sessions: SessionData[]) => { 11 | if (err) { 12 | return reject(err); 13 | } 14 | 15 | if (sessions) { 16 | const result = Object.entries(sessions).map(([sessionId, session]: [string, SessionData]) => { 17 | return { 18 | sessionId, 19 | user: { 20 | email: session.user?.email, 21 | role: session.user?.role 22 | } 23 | } 24 | }); 25 | resolve(result); 26 | } 27 | }) : []; 28 | }); 29 | } 30 | 31 | destroySession(sessionId: string): Promise { 32 | return new Promise((resolve, reject) => { 33 | this.store.destroy(sessionId, (error) => { 34 | error ? reject(error) : resolve() 35 | }); 36 | }); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /src/app/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { AuthRequest } from '../../models/authRequest'; 3 | import { SignupService } from './services/signup.service'; 4 | import { PasswordService } from './services/password.service'; 5 | import externalAuthCtrl from './external-auth.controller'; 6 | import authService from './services/auth.service.instance'; 7 | import validator from './auth.validator'; 8 | 9 | const router = Router(); 10 | const signupService = new SignupService(); 11 | const passwordService = new PasswordService(); 12 | 13 | router.post('/signup', validator, function (req: Request, res: Response) { 14 | const signupRequest = AuthRequest.buildFromRequest(req); 15 | signupService.signup(signupRequest).then(() => { 16 | res.sendStatus(204); 17 | }).catch(() => { 18 | res.status(400).json({msg: 'Signup failed'}); 19 | }); 20 | }); 21 | 22 | router.post('/confirm', function (req: Request, res: Response) { 23 | let email = req.body.email; // may require "as string"; To check after TypeScript update 24 | let confirmationCode = req.body.code; 25 | signupService.confirm(email, confirmationCode).then(() => { 26 | res.sendStatus(204); 27 | }).catch(() => { 28 | res.status(400).json({msg: 'Confirmation failed'}); 29 | }); 30 | }); 31 | 32 | router.post('/setup', function (req: Request, res: Response) { 33 | let email = req.body.email; 34 | let code = req.body.code; 35 | let password = req.body.password; 36 | 37 | passwordService.setup(email, code, password).then(() => { 38 | res.sendStatus(204); 39 | }).catch(() => { 40 | res.status(400).json({msg: 'Setting password failed'}); 41 | }); 42 | }); 43 | 44 | router.post('/recover-request', function (req: Request, res: Response) { 45 | let email = req.body.email; 46 | 47 | passwordService.requestRecovery(email).then(() => { 48 | res.sendStatus(204); 49 | }).catch(() => { 50 | res.status(400).json({msg: 'Recovery failed'}); 51 | }); 52 | }); 53 | 54 | router.post('/recover', function (req: Request, res: Response) { 55 | let email = req.body.email; 56 | let code = req.body.code; 57 | let password = req.body.password; 58 | 59 | passwordService.recover(email, code, password).then(() => { 60 | res.sendStatus(204); 61 | }).catch(() => { 62 | res.status(400).json({msg: 'Recovery failed failed'}); 63 | }); 64 | }); 65 | 66 | router.post('/login', function (req: Request, res: Response) { 67 | const loginRequest = AuthRequest.buildFromRequest(req); 68 | authService.login(loginRequest).then(result => { 69 | res.json(result); 70 | }).catch((err) => { 71 | res.status(401).json({msg: err ? err : 'Login failed'}); 72 | }); 73 | }); 74 | 75 | router.get('/logout', function (req: Request, res: Response) { 76 | authService.logout(req.session).then(() => { 77 | res.sendStatus(204); 78 | }); 79 | }); 80 | 81 | router.get('/user', function (req: Request, res: Response) { 82 | authService.getCurrentUser(req.session).then((user) => { 83 | res.status(200).json(user); 84 | }); 85 | }); 86 | 87 | router.use('/external', externalAuthCtrl); 88 | 89 | export default router; -------------------------------------------------------------------------------- /src/app/auth/auth.validator.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { check, validationResult, ValidationError } from 'express-validator'; 3 | import log from './../../utils/logger'; 4 | 5 | function passwordValidator() { 6 | return check('password').isLength({ min: 5 }) 7 | .withMessage('must have at least 5 characters'); 8 | } 9 | 10 | function emailValidator() { 11 | return check('email').isEmail() 12 | .withMessage('is not valid'); 13 | } 14 | 15 | function errorParser() { 16 | return function (req: Request, res: Response, next: NextFunction) { 17 | const errors = validationResult(req); 18 | if (!errors.isEmpty()) { 19 | log.warn('auth.signup_validation_failed', {errors: errors.array()}); 20 | res.status(422).json({ msg: formatErrors(errors.array()) }); 21 | } else { 22 | next(); 23 | } 24 | } 25 | } 26 | 27 | function formatErrors(errors: ValidationError[]) { 28 | return errors.map(e => `${e.param} ${e.msg}`).join(', '); 29 | } 30 | 31 | export default [passwordValidator(), emailValidator(), errorParser()]; -------------------------------------------------------------------------------- /src/app/auth/external-auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | import { ExternalAuthService } from './services/external-auth/external-auth.service'; 3 | import stateService from './services/external-auth/state.service'; 4 | import config from '../../config'; 5 | 6 | const router = Router(); 7 | const externalAuthService = new ExternalAuthService(); 8 | 9 | router.get('/:provider/:action', function (req: Request, res: Response) { 10 | const provider = req.params.provider; 11 | const action = req.params.action === 'signup' ? 'signup' : 'login'; 12 | 13 | if (provider in config.externalAuth) { 14 | const providerConfig = (config.externalAuth)[provider]; 15 | const redirect_uri = `${providerConfig.callbackURL}/${action}`; 16 | 17 | res.redirect(`${providerConfig.authorizeUrl}` + 18 | `?client_id=${providerConfig.clientID}` + 19 | `&response_type=code` + 20 | `&state=${stateService.setAndGetNewState(req.session)}` + 21 | // `&access_type=offline` + // INFO: this requests Refresh Token 22 | `&scope=${providerConfig.scope}` + 23 | `&redirect_uri=${redirect_uri}`); 24 | 25 | } else { 26 | res.redirect(`/login?msg=Provider not supported`); 27 | } 28 | 29 | }); 30 | 31 | router.get('/:provider/callback/signup', function (req, res) { 32 | const provider = req.params.provider; 33 | const authCode = req.query.code as string; 34 | const state = req.query.state as string; 35 | stateService.assertStateIsValid(req.session, state).then(() => 36 | externalAuthService.signup(provider, authCode, req.session).then(() => { 37 | res.redirect('/'); 38 | }) 39 | ).catch((err) => { 40 | res.redirect(`/login?msg=${err ? err : 'Signup failed'}`); 41 | }); 42 | }); 43 | 44 | router.get('/:provider/callback/login', function (req, res) { 45 | const provider = req.params.provider; 46 | const authCode = req.query.code as string; 47 | const state = req.query.state as string; 48 | stateService.assertStateIsValid(req.session, state).then(() => 49 | externalAuthService.login(provider, authCode, req.session).then(() => { 50 | res.redirect('/'); 51 | }) 52 | ).catch((err) => { 53 | res.redirect(`/login?msg=${err ? err : 'Login failed'}`); 54 | }); 55 | }); 56 | 57 | export default router; -------------------------------------------------------------------------------- /src/app/auth/passport.ts: -------------------------------------------------------------------------------- 1 | import { VerifiedCallback } from 'passport-jwt'; 2 | import { Strategy as JwtStrategy } from 'passport-jwt'; 3 | import { ExtractJwt } from 'passport-jwt'; 4 | import passport = require('passport'); 5 | import CONFIG from '../../config'; 6 | 7 | const passportOpts = { 8 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 9 | secretOrKey: CONFIG.jwtSecret 10 | }; 11 | 12 | passport.use(new JwtStrategy(passportOpts, function (jwtPayload: any, done: VerifiedCallback) { 13 | done(null, jwtPayload); 14 | })); 15 | 16 | export default passport; -------------------------------------------------------------------------------- /src/app/auth/repositories/account.repository.ts: -------------------------------------------------------------------------------- 1 | import { Account } from 'src/models/account'; 2 | import { Id } from 'src/models/types'; 3 | 4 | export interface AccountRepository { 5 | 6 | createAccount(account: Account): Promise; 7 | 8 | } -------------------------------------------------------------------------------- /src/app/auth/repositories/in-memory/in-memory-account.repository.ts: -------------------------------------------------------------------------------- 1 | import { AccountRepository } from '../account.repository'; 2 | import { Account } from 'src/models/account'; 3 | import { Id } from 'src/models/types'; 4 | 5 | export class InMemoryAccountRepository implements AccountRepository { 6 | 7 | createAccount(account: Account): Promise { 8 | account.id = (ACCOUNTS.length + 1).toString(); 9 | ACCOUNTS.push(account); 10 | return Promise.resolve(account.id); 11 | } 12 | 13 | } 14 | 15 | const ACCOUNTS: Account[] = [ 16 | { 17 | id: '1' 18 | }, 19 | { 20 | id: '2' 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /src/app/auth/repositories/in-memory/in-memory-login-failure.repository.ts: -------------------------------------------------------------------------------- 1 | import { LoginFailureRepository } from '../login-failure.repository'; 2 | import { LoginFailure } from './../../../../models/login.failure'; 3 | 4 | export class InMemoryLoginFailureRepository implements LoginFailureRepository { 5 | 6 | getLastFailures(userEmail: string, number: number): Promise { 7 | const ascendingByTime = (f1: LoginFailure, f2: LoginFailure) => f1.datetime.getTime() - f2.datetime.getTime(); 8 | const lastFailures = LOGIN_FAILURES.sort(ascendingByTime).slice(-number); 9 | return Promise.resolve(lastFailures); 10 | } 11 | registerFailedLogin(userEmail: string, datetime: Date): Promise { 12 | LOGIN_FAILURES.push(new LoginFailure(userEmail, datetime)); 13 | return Promise.resolve(); 14 | } 15 | 16 | } 17 | 18 | const LOGIN_FAILURES: LoginFailure[] = []; -------------------------------------------------------------------------------- /src/app/auth/repositories/in-memory/in-memory-user.repository.ts: -------------------------------------------------------------------------------- 1 | import { UserRepository } from '../user.repository'; 2 | import { Id, UserRole } from 'src/models/types'; 3 | import { User } from 'src/models/user'; 4 | 5 | export class InMemoryUserRepository implements UserRepository { 6 | 7 | getUserById(id: Id, attachAccount = false): Promise { 8 | const user = USERS.find(user => user.id === id); 9 | if (attachAccount) { 10 | // TODO attach account in response 11 | } 12 | return new Promise((resolve, reject) => { 13 | user ? resolve(user) : reject(); 14 | }); 15 | } 16 | 17 | getUserByEmail(email: string): Promise { 18 | const user = USERS.find(user => user.email === email); 19 | return new Promise((resolve, reject) => { 20 | user ? resolve(user) : reject(); 21 | }); 22 | } 23 | 24 | getUserByExternalId(provider: string, externalId: string): Promise { 25 | const user = USERS.find(user => !!externalId && !!user.externalId && user.externalId[provider] === externalId); 26 | return new Promise((resolve, reject) => { 27 | user ? resolve(user) : reject(); 28 | }); 29 | } 30 | 31 | assertUserWithExternalIdNotExist(provider: string, externalId: string): Promise { 32 | return new Promise((resolve, reject) => { 33 | this.getUserByExternalId(provider, externalId) 34 | .then((user) => reject('User already exists')) 35 | .catch(() => resolve()); 36 | }); 37 | } 38 | 39 | getUsers(accountId: Id): Promise { 40 | const users = USERS.filter(user => user.accountId === accountId) 41 | return Promise.resolve(users); 42 | } 43 | 44 | createUser(user: User): Promise { 45 | user.id = (USERS.length + 1).toString(); 46 | USERS.push(user); 47 | return Promise.resolve(user.id); 48 | } 49 | 50 | deleteUser(id: Id): Promise { 51 | USERS = USERS.filter(user => user.id !== id); 52 | return Promise.resolve(); 53 | } 54 | 55 | patchUser(id: Id, data: User): Promise { 56 | return this.getUserById(id) 57 | .then(userToPatch => Object.assign(userToPatch, data)); 58 | } 59 | 60 | } 61 | 62 | let USERS: User[] = [ 63 | { 64 | id: '1', 65 | email: 'admin@app.com', 66 | password: '$2y$10$k.58cTqd/rRbAOc8zc3nCupCC6QkfamoSoO2Hxq6HVs0iXe7uvS3e', // '123' 67 | role: 'ADMIN', 68 | confirmed: true, 69 | createdWith: 'password' 70 | }, 71 | { 72 | id: '2', 73 | accountId: '1', 74 | email: 'bartosz@app.com', 75 | password: '$2y$10$k.58cTqd/rRbAOc8zc3nCupCC6QkfamoSoO2Hxq6HVs0iXe7uvS3e', // '123' 76 | role: 'OWNER', 77 | confirmed: true, 78 | createdWith: 'password', 79 | tfa: true, 80 | tfaSecret: 'FB2S2HQLIE2UIZQDGYLCMS3SNZMXQDSK' 81 | }, 82 | { 83 | id: '3', 84 | accountId: '2', 85 | email: 'john@app.com', 86 | password: '$2y$10$k.58cTqd/rRbAOc8zc3nCupCC6QkfamoSoO2Hxq6HVs0iXe7uvS3e', // '123' 87 | role: 'OWNER', 88 | confirmed: true, 89 | createdWith: 'password' 90 | }, 91 | { 92 | id: '4', 93 | accountId: '2', 94 | email: 'mike@app.com', 95 | password: '$2y$10$k.58cTqd/rRbAOc8zc3nCupCC6QkfamoSoO2Hxq6HVs0iXe7uvS3e', // '123' 96 | role: 'READER', 97 | confirmed: true, 98 | createdWith: 'password' 99 | }, 100 | { 101 | id: '5', 102 | accountId: '1', 103 | email: 'hi@bartosz.io', 104 | role: 'OWNER', 105 | confirmed: true, 106 | externalId: { 107 | github: '8076187' 108 | }, 109 | createdWith: 'github' 110 | } 111 | ]; 112 | -------------------------------------------------------------------------------- /src/app/auth/repositories/login-failure.repository.ts: -------------------------------------------------------------------------------- 1 | import { LoginFailure } from 'src/models/login.failure'; 2 | 3 | export interface LoginFailureRepository { 4 | 5 | // most DB engines provide sorting and limiting number of results 6 | // we need results sorted by time (newest first) and limited by given number 7 | getLastFailures(userEmail: string, number: number): Promise; 8 | 9 | registerFailedLogin(userEmail: string, datetime: Date): Promise; 10 | 11 | } -------------------------------------------------------------------------------- /src/app/auth/repositories/user.repository.ts: -------------------------------------------------------------------------------- 1 | import { Id } from 'src/models/types'; 2 | import { User } from 'src/models/user'; 3 | 4 | export interface UserRepository { 5 | 6 | getUserById(id: Id, attachAccount?: boolean): Promise; 7 | 8 | getUserByEmail(email: string): Promise; 9 | 10 | getUserByExternalId(provider: string, externalId: string): Promise; 11 | 12 | assertUserWithExternalIdNotExist(provider: string, externalId: string): Promise; 13 | 14 | getUsers(accountId: Id): Promise; 15 | 16 | createUser(user: User): Promise; 17 | 18 | patchUser(id: Id, user: User): Promise; 19 | 20 | deleteUser(id: Id): Promise; 21 | 22 | } -------------------------------------------------------------------------------- /src/app/auth/role.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { User } from './../../models/user'; 3 | import { ROLES, UserRole } from '../../models/types'; 4 | import log from './../../utils/logger'; 5 | 6 | export function readerOnlyReads() { 7 | 8 | return function (req: Request, res: Response, next: NextFunction) { 9 | const user = req.user as User; 10 | 11 | if (!isRoleFound(user)) { 12 | handleRoleNotFound(user, res); 13 | } else if (user.role && user.role.toUpperCase() === 'READER' && req.method.toUpperCase() !== 'GET') { 14 | log.warn('auth.reader_check_failure', { user }); 15 | res.status(403).json({ msg: 'You are not authorized to perform this operation' }); 16 | next('Unauthorized'); 17 | } else { 18 | next(); 19 | } 20 | } 21 | 22 | } 23 | 24 | export function hasRole(roleToCheck: UserRole) { 25 | 26 | return function (req: Request, res: Response, next: NextFunction) { 27 | const user = req.user as User; 28 | 29 | if (!isRoleFound(user)) { 30 | handleRoleNotFound(user, res); 31 | } else if (user.role !== roleToCheck) { 32 | log.warn('auth.role_check_failure', { roleToCheck, user }); 33 | res.status(403).json({ msg: 'You are not authorized to perform this operation' }); 34 | } else { 35 | next(); 36 | } 37 | } 38 | 39 | } 40 | 41 | function isRoleFound(user: User) { 42 | return user && ROLES.find(r => r === user.role); 43 | } 44 | 45 | function handleRoleNotFound(user: User, res: Response) { 46 | log.error('auth.role_not_found', { user }); 47 | res.status(500).json({ msg: 'System could not find your permissions' }); 48 | } 49 | -------------------------------------------------------------------------------- /src/app/auth/services/auth.service.instance.ts: -------------------------------------------------------------------------------- 1 | import { OtpService } from './otp.service'; 2 | import { AuthService } from './auth.service'; 3 | import { JwtAuthService } from './jwt-auth.service'; 4 | import { SessionAuthService } from './session-auth.service'; 5 | import { UserRepository } from '../repositories/user.repository'; 6 | import { InMemoryUserRepository } from '../repositories/in-memory/in-memory-user.repository'; 7 | import config from './../../../config'; 8 | 9 | const userRepository: UserRepository = new InMemoryUserRepository(); 10 | const otp = new OtpService(); 11 | 12 | function getAuthService(): AuthService { 13 | switch (config.auth) { 14 | case 'session': 15 | return new SessionAuthService(otp, userRepository); 16 | case 'jwt': 17 | return new JwtAuthService(); 18 | default: 19 | throw 'AuthService not defined'; 20 | } 21 | } 22 | 23 | export default getAuthService(); 24 | 25 | -------------------------------------------------------------------------------- /src/app/auth/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { RequestHandler } from 'express'; 2 | import { AuthRequest } from 'src/models/authRequest'; 3 | 4 | export interface AuthService { 5 | 6 | authenticate(): RequestHandler; 7 | 8 | login(loginRequest: AuthRequest): Promise; 9 | 10 | logout(session?: any): Promise; 11 | 12 | getCurrentUser(session?: any): Promise; 13 | 14 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/external-auth.factory.ts: -------------------------------------------------------------------------------- 1 | import { GithubAuthProvider } from './github-auth.provider'; 2 | import { GoogleAuthProvider } from './google-auth.provider'; 3 | import { ExternalAuthProvider } from './external-auth.provider'; 4 | 5 | export function getExternalAuthProvider(provider: string): ExternalAuthProvider { 6 | switch (provider) { 7 | case 'github': 8 | return new GithubAuthProvider(); 9 | case 'google': 10 | return new GoogleAuthProvider(); 11 | default: 12 | throw 'Auth provider not defined'; 13 | } 14 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/external-auth.provider.ts: -------------------------------------------------------------------------------- 1 | import { UserInfo } from './../../../../models/userInfo'; 2 | 3 | export interface ExternalAuthProvider { 4 | 5 | getAccessToken(authCode: string, action?: string): Promise; 6 | 7 | getUserInfo(accessToken: string): Promise; 8 | 9 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/external-auth.service.ts: -------------------------------------------------------------------------------- 1 | import { UserInfo } from './../../../../models/userInfo'; 2 | import { AuthProvider } from './../../../../models/user'; 3 | import { UserRepository } from '../../repositories/user.repository'; 4 | import { AccountRepository } from '../../repositories/account.repository'; 5 | import { CategoriesRepository } from '../../../settings/categories/categories.repository'; 6 | import { InMemoryUserRepository } from '../../repositories/in-memory/in-memory-user.repository'; 7 | import { InMemoryAccountRepository } from '../../repositories/in-memory/in-memory-account.repository'; 8 | import { InMemoryCategoriesRepository } from '../../../settings/categories/in-memory-categories.repository'; 9 | import { getExternalAuthProvider } from './external-auth.factory'; 10 | import log from '../../../../utils/logger'; 11 | 12 | 13 | // TODO provide configuration for repositories 14 | const userRepository: UserRepository = new InMemoryUserRepository(); 15 | const accountRepository: AccountRepository = new InMemoryAccountRepository(); 16 | const categoriesRepository: CategoriesRepository = new InMemoryCategoriesRepository(); 17 | 18 | export class ExternalAuthService { 19 | 20 | login(provider: string, authCode: string, session: any): Promise { 21 | const authProvider = getExternalAuthProvider(provider); 22 | return authProvider.getAccessToken(authCode, 'login').then((token: string) => 23 | authProvider.getUserInfo(token).then(userInfo => 24 | userRepository.getUserByExternalId(provider, userInfo.id).then(user => { 25 | session.user = user; 26 | log.info(`auth.${provider}.session_login_successful`, { user }); 27 | }).catch(() => { 28 | log.error(`auth.${provider}.session_login_failed`, { userInfo }); 29 | return Promise.reject('User not found'); 30 | }) 31 | ) 32 | ); 33 | } 34 | 35 | signup(provider: string, authCode: string, session: any): Promise { 36 | const authProvider = getExternalAuthProvider(provider); 37 | return authProvider.getAccessToken(authCode, 'signup').then((token: string) => 38 | authProvider.getUserInfo(token).then((userInfo: any) => 39 | userRepository.assertUserWithExternalIdNotExist(provider, userInfo.id).then(() => 40 | this.doSignup(provider, userInfo).then(() => { 41 | log.info(`auth.${provider}.signup_successful`, { email: userInfo.email }); 42 | userRepository.getUserByExternalId(provider, userInfo.id).then(user => { 43 | session.user = user; 44 | log.info(`auth.${provider}.session_login_successful`, { user }); 45 | }); 46 | }).catch(error => { 47 | log.error(`auth.${provider}.signup_failed`, { email: userInfo.email }); 48 | throw error; 49 | }) 50 | ) 51 | )); 52 | } 53 | 54 | private doSignup(provider: string, userInfo: UserInfo) { 55 | return accountRepository.createAccount({}).then(accountId => Promise.all([ 56 | categoriesRepository.createDefaultCategories(accountId), 57 | userRepository.createUser({ 58 | accountId: accountId, 59 | email: userInfo.email, 60 | role: 'OWNER', 61 | confirmed: true, 62 | createdWith: provider as AuthProvider, 63 | externalId: { [provider]: userInfo.id } // for example { github: 123 } 64 | }) 65 | ])); 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/github-auth.provider.ts: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | import config from '../../../../config'; 3 | import { UserInfo } from '../../../../models/userInfo'; 4 | import { ExternalAuthProvider } from './external-auth.provider'; 5 | import log from '../../../../utils/logger'; 6 | 7 | export class GithubAuthProvider implements ExternalAuthProvider { 8 | 9 | getAccessToken(authCode: string): Promise { 10 | const options = { headers: { accept: 'application/json' } }; 11 | const body = { 12 | client_id: config.externalAuth.github.clientID, 13 | client_secret: config.externalAuth.github.clientSecret, 14 | code: authCode 15 | }; 16 | return axios.post(config.externalAuth.github.accessTokenUrl, body, options) 17 | .then((res: any) => res.data['access_token']) 18 | .catch((error: any) => { 19 | log.error('auth.github.getAccessToken_failed', { error }); 20 | throw error; 21 | }) 22 | } 23 | 24 | getUserInfo(accessToken: string): Promise { 25 | const options = { headers: { Authorization: `token ${accessToken}` } }; 26 | return axios.get(config.externalAuth.github.userInfoUrl, options) 27 | .then((res: any) => { 28 | log.info('auth.github.getUserInfo', { githubId: res.data.id }); 29 | return { 30 | id: res.data.id.toString(), 31 | login: res.data.login, 32 | email: res.data.email 33 | } as UserInfo; 34 | }).catch((error: any) => { 35 | log.error('auth.github.getUserInfo_failed', { error }); 36 | return Promise.reject('Could not get UserInfo from GitHub') 37 | }); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/google-auth.provider.ts: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | import config from '../../../../config'; 3 | import { UserInfo } from '../../../../models/userInfo'; 4 | import { ExternalAuthProvider } from './external-auth.provider'; 5 | import log from '../../../../utils/logger'; 6 | 7 | export class GoogleAuthProvider implements ExternalAuthProvider { 8 | 9 | getAccessToken(authCode: string, action?: string): Promise { 10 | const options = { headers: { accept: 'application/json' } }; 11 | const body = { 12 | client_id: config.externalAuth.google.clientID, 13 | client_secret: config.externalAuth.google.clientSecret, 14 | redirect_uri: config.externalAuth.google.callbackURL+`/${action}`, 15 | grant_type: 'authorization_code', 16 | code: authCode 17 | }; 18 | return axios.post(config.externalAuth.google.accessTokenUrl, body, options) 19 | .then((res: any) => res.data['access_token']) // INFO: also `refresh_token` and `expires_in` in res.data 20 | .catch((error: any) => { 21 | log.error('auth.google.getAccessToken_failed', { error }); 22 | throw error; 23 | }) 24 | } 25 | 26 | getUserInfo(accessToken: string): Promise { 27 | const options = { headers: { Authorization: `Bearer ${accessToken}` } }; 28 | return axios.get(config.externalAuth.google.userInfoUrl, options) 29 | .then((res: any) => { 30 | log.info('auth.google.getUserInfo', { googleId: res.data.sub }); 31 | return { 32 | id: res.data.sub, 33 | email: res.data.email 34 | } as UserInfo; 35 | }).catch((error: any) => { 36 | log.error('auth.google.getUserInfo_failed', { error }); 37 | return Promise.reject('Could not get UserInfo from Google') 38 | }); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /src/app/auth/services/external-auth/state.service.ts: -------------------------------------------------------------------------------- 1 | const randtoken = require('rand-token'); 2 | import log from '../../../../utils/logger'; 3 | 4 | const LENGTH = 32; 5 | 6 | export default { 7 | 8 | setAndGetNewState(session: any) { 9 | session.oauthState = randtoken.generate(LENGTH); 10 | return session.oauthState; 11 | }, 12 | 13 | getAndRemoveState(session: any) { 14 | const state = session.oauthState; 15 | session.oauthState = null; 16 | return state; 17 | }, 18 | 19 | assertStateIsValid(session: any, state: string) { 20 | return new Promise((resolve, reject) => { 21 | if (!!state && state.length === LENGTH && state === session.oauthState) { 22 | log.info('auth.external.state.valid_check', { state }); 23 | resolve(); 24 | } else { 25 | log.error('auth.external.state.failed_check', { state: state, expectedState: session.oauthState }); 26 | reject('Invalid state paramater'); 27 | } 28 | }); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/app/auth/services/jwt-auth.service.ts: -------------------------------------------------------------------------------- 1 | import bcrypt = require('bcryptjs'); 2 | import jwt = require('jsonwebtoken'); 3 | import CONFIG from '../../../config'; 4 | import passport from '../passport'; 5 | import { AuthService } from './auth.service'; 6 | import { LoginThrottler } from './login.throttler'; 7 | import { UserRepository } from '../repositories/user.repository'; 8 | import { InMemoryUserRepository } from '../repositories/in-memory/in-memory-user.repository'; 9 | import { AuthRequest } from './../../../models/authRequest'; 10 | import { Token } from './../../../models/token'; 11 | import { User } from './../../../models/user'; 12 | import log from './../../../utils/logger'; 13 | 14 | // TODO provide configuration for repositories 15 | const userRepository: UserRepository = new InMemoryUserRepository(); 16 | const loginThrottler = new LoginThrottler(); 17 | 18 | export class JwtAuthService implements AuthService { 19 | 20 | authenticate() { 21 | return passport.authenticate('jwt', { session: false }); 22 | } 23 | 24 | login(loginRequest: AuthRequest): Promise { 25 | const email = loginRequest.email; 26 | return userRepository.getUserByEmail(email).then(user => { 27 | 28 | return loginThrottler.isLoginBlocked(email).then(isBlocked => { 29 | if (isBlocked) { 30 | log.warn('auth.jwt_login_failed.user_blocked', {email}); 31 | throw `Login blocked. Please try in ${CONFIG.loginThrottle.timeWindowInMinutes} minutes`; 32 | } else { 33 | return bcrypt.compare(loginRequest.password, user.password!).then(match => { 34 | if (match && user.confirmed) { 35 | 36 | const token = createSignedToken(user); 37 | log.info('auth.jwt_login_successful', {user}); 38 | return { jwt: token }; 39 | 40 | } else if (match && !user.confirmed) { 41 | 42 | log.info('auth.jwt_login_failed.not_confirmed', {user}); 43 | return Promise.reject('Please confirm your user profile'); 44 | 45 | } else { 46 | 47 | loginThrottler.registerLoginFailure(email); 48 | log.info('auth.jwt_login_failed.wrong_password', {user}); 49 | return Promise.reject(); 50 | 51 | } 52 | }); 53 | } 54 | }); 55 | 56 | }); 57 | } 58 | 59 | logout() { 60 | log.info('auth.jwt_logout_successful'); 61 | return Promise.resolve(); 62 | } 63 | 64 | getCurrentUser(): Promise { 65 | return Promise.resolve(); 66 | } 67 | 68 | } 69 | 70 | function createSignedToken(user: User) { 71 | const payload = User.toSafeUser(user); 72 | return jwt.sign(payload, CONFIG.jwtSecret, 73 | { expiresIn: 600 }); // 600 seconds = 10 minutes 74 | } 75 | -------------------------------------------------------------------------------- /src/app/auth/services/login.throttler.ts: -------------------------------------------------------------------------------- 1 | import { LoginFailureRepository } from '../repositories/login-failure.repository'; 2 | import { InMemoryLoginFailureRepository } from '../repositories/in-memory/in-memory-login-failure.repository'; 3 | import config from './../../../config'; 4 | 5 | // TODO provide configuration for repositories 6 | let loginFailures: LoginFailureRepository = new InMemoryLoginFailureRepository(); 7 | 8 | export class LoginThrottler { 9 | 10 | private readonly MAX_FAILURES = config.loginThrottle.maxFailures; 11 | private readonly TIME_WINDOW = config.loginThrottle.timeWindowInMinutes; 12 | 13 | isLoginBlocked(userEmail: string): Promise { 14 | return loginFailures.getLastFailures(userEmail, this.MAX_FAILURES).then(failures => { 15 | 16 | if (failures.length >= this.MAX_FAILURES) { 17 | const currentTime = new Date(); 18 | const oldestFailure = failures.reduce((a, b) => a.datetime.getTime() < b.datetime.getTime() ? a : b); 19 | 20 | if (oldestFailure.datetime.getTime() >= currentTime.getTime() - this.TIME_WINDOW * 1000 * 60) { 21 | return Promise.resolve(true); 22 | } 23 | } 24 | 25 | return Promise.resolve(false); 26 | }); 27 | } 28 | 29 | registerLoginFailure(userEmail: string): Promise { 30 | return loginFailures.registerFailedLogin(userEmail, new Date()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/app/auth/services/otp.service.ts: -------------------------------------------------------------------------------- 1 | import { authenticator } from 'otplib'; 2 | 3 | import { User } from 'src/models/user'; 4 | import { AuthRequest } from 'src/models/authRequest'; 5 | import log from './../../../utils/logger'; 6 | 7 | export class OtpService { 8 | 9 | checkOtpIfRequired(loginRequest: AuthRequest, user: User) { 10 | return new Promise((resolve, reject) => { 11 | if (user.tfa) { 12 | 13 | if (!loginRequest.otp) { 14 | return reject('OTP_REQUIRED'); 15 | } 16 | 17 | if (!user.tfaSecret) { 18 | log.error('auth.otp.secret_missing', { user }); 19 | return reject('System error. Contact support.'); 20 | } 21 | 22 | try { 23 | // INFO: async authenticator implementation is also available 24 | const isValid = authenticator.check(loginRequest.otp, user.tfaSecret); 25 | if (!isValid) { 26 | log.error('auth.otp.invalid_code', { user }); 27 | return reject('Invalid one-time code'); 28 | } 29 | } catch (error) { 30 | log.error('auth.otp.error', { user, error }); 31 | return reject(); 32 | } 33 | 34 | log.info('auth.otp.valid', { user }); 35 | } 36 | 37 | resolve(); 38 | }); 39 | } 40 | 41 | getOtpKeyUri(user: User) { 42 | const service = 'BudgetApp'; 43 | return authenticator.keyuri(user.email!, service, user.tfaSecret!); 44 | } 45 | 46 | generateNewSecret() { 47 | const bytes = 20; // 20 * 8 = 160 bits 48 | return authenticator.generateSecret(bytes); // generated secret is Base32 encoded (so will have different length) 49 | } 50 | } -------------------------------------------------------------------------------- /src/app/auth/services/password.service.ts: -------------------------------------------------------------------------------- 1 | const randtoken = require('rand-token'); 2 | import bcrypt = require('bcryptjs'); 3 | import CONFIG from '../../../config'; 4 | import { UserRepository } from '../repositories/user.repository'; 5 | import { InMemoryUserRepository } from '../repositories/in-memory/in-memory-user.repository'; 6 | import log from './../../../utils/logger'; 7 | 8 | const userRepository: UserRepository = new InMemoryUserRepository(); 9 | 10 | export class PasswordService { 11 | 12 | setup(email: string, confirmationCode: string, password: string): Promise { 13 | return userRepository.getUserByEmail(email).then(user => { 14 | if (user && !user.confirmed && user.confirmationCode === confirmationCode) { 15 | 16 | return bcrypt.hash(password, 10).then(hashedPassword => { 17 | user.password = hashedPassword; 18 | user.confirmed = true; 19 | user.confirmationCode = undefined; 20 | log.info('auth.password_setup_successful', { user }); 21 | }); 22 | 23 | } else { 24 | log.warn('auth.password_setup_failed', { user }); 25 | return Promise.reject(); 26 | } 27 | }); 28 | } 29 | 30 | requestRecovery(email: string) { 31 | const recoveryCode = randtoken.uid(256); 32 | return userRepository.getUserByEmail(email).then(user => { 33 | if (user && user.confirmed) { 34 | 35 | user.recovery = { 36 | code: recoveryCode, 37 | requested: new Date() 38 | } 39 | this.sendRecoveryEmail(email, recoveryCode); 40 | log.info('auth.password_recovery_request_successful', { user }); 41 | 42 | } else { 43 | log.warn('auth.password_recovery_request_failed', { user }); 44 | return Promise.reject(); 45 | } 46 | }); 47 | } 48 | 49 | recover(email: string, recoveryCode: string, password: string) { 50 | 51 | return userRepository.getUserByEmail(email).then(user => { 52 | if (user && user.confirmed && user.recovery && user.recovery.code === recoveryCode) { 53 | 54 | // IDEA: use 'user.recovery.requested' date to limit the time validity of recovery code 55 | return bcrypt.hash(password, 10).then(hashedPassword => { 56 | user.password = hashedPassword; 57 | user.recovery = undefined; 58 | log.info('auth.password_recovery_successful', { user }); 59 | }); 60 | 61 | } else { 62 | log.warn('auth.password_recovery_failed', { user }); 63 | return Promise.reject(); 64 | } 65 | }); 66 | 67 | } 68 | 69 | private sendRecoveryEmail(email: string, code: string) { 70 | const link = `${CONFIG.clientUrl}/password?email=${email}&code=${code}&recovery=true`; 71 | console.log(`>>> LINK >>>: ${link}`); // mock email sending :) 72 | log.info('auth.password_recovery_email_sent', { email }); 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/app/auth/services/session-auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { SessionAuthService } from './session-auth.service'; 3 | import { OtpService } from './otp.service'; 4 | import { UserRepository } from './../repositories/user.repository'; 5 | import { AuthRequest } from './../../../models/authRequest'; 6 | import { User } from './../../../models/user'; 7 | 8 | const fakeUser = { 9 | email: 'bartosz@app.com', 10 | password: '$2y$10$k.58cTqd/rRbAOc8zc3nCupCC6QkfamoSoO2Hxq6HVs0iXe7uvS3e', // '123' 11 | confirmed: true, 12 | tfa: true, 13 | tfaSecret: 'abc' 14 | } as User; 15 | 16 | const request = { 17 | session: { user: fakeUser } 18 | } as Request; 19 | 20 | const responseMock = () => { 21 | return { 22 | statusCode: 0, 23 | json: jest.fn() 24 | } as Pick 25 | } 26 | 27 | const nextMock: NextFunction = jest.fn(); 28 | 29 | const otpStub = () => { 30 | return { 31 | checkOtpIfRequired: jest.fn(() => Promise.resolve()) 32 | } as Pick as OtpService; 33 | } 34 | 35 | const userRepoStub = (user = fakeUser) => { 36 | return { 37 | getUserByEmail: jest.fn(() => Promise.resolve(user)) 38 | } as Pick as UserRepository; 39 | } 40 | 41 | describe('SessionAuthService', () => { 42 | 43 | describe('authenticate method', () => { 44 | 45 | it('returns a request handler', () => { 46 | // given 47 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 48 | 49 | // when 50 | const result = sessionAuthService.authenticate(); 51 | 52 | // then 53 | expect(typeof result).toBe('function'); 54 | }); 55 | 56 | it('returns a handler that continues execution when user in session', () => { 57 | // given 58 | const newResponseMock = responseMock() as Response; 59 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 60 | const handler = sessionAuthService.authenticate(); 61 | 62 | // when 63 | handler(request, newResponseMock, nextMock); 64 | 65 | // then 66 | expect(nextMock).toHaveBeenCalled(); 67 | }); 68 | 69 | it('returns a handler that finishes execution when no user in session', () => { 70 | // given 71 | const newResponseMock = responseMock() as Response; 72 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 73 | const requestWithoutUser = { session: { user: null } } as Request; 74 | const handler = sessionAuthService.authenticate(); 75 | 76 | // when 77 | handler(requestWithoutUser, newResponseMock, nextMock); 78 | 79 | // then 80 | expect(newResponseMock.statusCode).toBe(401); 81 | expect(newResponseMock.json).toHaveBeenCalled(); 82 | }); 83 | }); 84 | 85 | describe('login method', () => { 86 | 87 | it('logs in and returns the logged user', (done) => { 88 | // given 89 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 90 | const request = new AuthRequest('bartosz@app.com', '123', '', {}); 91 | 92 | // when 93 | sessionAuthService.login(request).then((user) => { 94 | 95 | // then 96 | expect(user).toBeTruthy(); 97 | done(); // must be called within the timeout (default 5000ms) 98 | }); 99 | }); 100 | 101 | it('fails to login with a wrong password', (done) => { 102 | // given 103 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 104 | const request = new AuthRequest('bartosz@app.com', 'wrong', '', {}); 105 | 106 | // when 107 | sessionAuthService.login(request).catch(() => { 108 | 109 | // then 110 | done(); // must be called within the timeout (default 5000ms) 111 | }); 112 | }); 113 | 114 | it('fails to login unconfirmed user with a valid password', (done) => { 115 | // given 116 | const unconfirmedUser = { ...fakeUser, confirmed: false } as User; 117 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub(unconfirmedUser)); 118 | const request = new AuthRequest('bartosz@app.com', '123', '', {}); 119 | 120 | // when 121 | sessionAuthService.login(request).catch(() => { 122 | 123 | // then 124 | done(); // must be called within the timeout (default 5000ms) 125 | }); 126 | }); 127 | 128 | // classic style => using real collaborator's code 129 | it('fails to login with invalid otp - classic style', (done) => { 130 | // given 131 | const otp = new OtpService(); // production code of OtpService 132 | const sessionAuthService = new SessionAuthService(otp, userRepoStub()); 133 | const request = new AuthRequest('bartosz@app.com', '123', 'invalid', {}); 134 | 135 | // when 136 | sessionAuthService.login(request).catch((error) => { 137 | 138 | // then 139 | expect(error.toString().toLowerCase()).toContain('invalid'); 140 | done(); // must be called within the timeout (default 5000ms) 141 | }); 142 | }); 143 | 144 | // london style => using ONLY class-under-test and mocking every collaborator 145 | it('fails to login with invalid otp - London style', (done) => { 146 | // given 147 | const otpMock = { 148 | checkOtpIfRequired: jest.fn(() => Promise.reject()) 149 | } as Pick; 150 | 151 | const sessionAuthService = new SessionAuthService(otpMock as OtpService, userRepoStub()); 152 | const request = { 153 | email: 'bartosz@app.com', 154 | password: '123' 155 | } as AuthRequest; 156 | 157 | // when 158 | sessionAuthService.login(request).catch(() => { 159 | 160 | // then 161 | expect(otpMock.checkOtpIfRequired).toHaveBeenCalledWith(request, fakeUser); 162 | done(); // must be called within the timeout (default 5000ms) 163 | }); 164 | }); 165 | 166 | it('fails to login without any otp', (done) => { 167 | // given 168 | const otp = new OtpService(); 169 | const sessionAuthService = new SessionAuthService(otp, userRepoStub()); 170 | const request = new AuthRequest('bartosz@app.com', '123', '', {}); 171 | 172 | // when 173 | sessionAuthService.login(request).catch((error) => { 174 | 175 | // then 176 | expect(error).toBe('OTP_REQUIRED'); 177 | done(); // must be called within the timeout (default 5000ms) 178 | }); 179 | }); 180 | }) 181 | 182 | describe('logout method', () => { 183 | 184 | it('logs out successfully', () => { 185 | // given 186 | const session = { 187 | user: fakeUser, 188 | destroy: jest.fn((cb) => cb()) 189 | }; 190 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 191 | 192 | // when 193 | sessionAuthService.logout(session); 194 | 195 | // then 196 | expect(session.destroy).toHaveBeenCalled(); 197 | }); 198 | 199 | it('does nothing when session not found', (done) => { 200 | // given 201 | const session = {}; 202 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 203 | 204 | // when 205 | sessionAuthService.logout(session).then(() => { 206 | 207 | // then 208 | done(); 209 | }); 210 | }); 211 | 212 | it('rejects a promise if error occured', (done) => { 213 | // given 214 | const session = { 215 | user: fakeUser, 216 | destroy: jest.fn((cb) => cb({ error: 'error' })) 217 | }; 218 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 219 | 220 | // when 221 | sessionAuthService.logout(session).catch(() => { 222 | 223 | // then 224 | done(); 225 | }); 226 | }); 227 | }); 228 | 229 | describe('getCurrentUser method', () => { 230 | 231 | it('returns the user', () => { 232 | // given 233 | const session = { 234 | user: fakeUser, 235 | }; 236 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 237 | 238 | // when 239 | sessionAuthService.getCurrentUser(session).then((user) => { 240 | 241 | // then 242 | expect(user).toEqual(User.toSafeUser(fakeUser)); 243 | }); 244 | }); 245 | 246 | it('returns nothing if no user found', (done) => { 247 | // given 248 | const session = {}; 249 | const sessionAuthService = new SessionAuthService(otpStub(), userRepoStub()); 250 | 251 | // when 252 | sessionAuthService.getCurrentUser(session).then((user) => { 253 | 254 | // then 255 | done(); 256 | }); 257 | }); 258 | 259 | }); 260 | 261 | }); -------------------------------------------------------------------------------- /src/app/auth/services/session-auth.service.ts: -------------------------------------------------------------------------------- 1 | import bcrypt = require('bcryptjs'); 2 | import { Request, Response, NextFunction } from 'express'; 3 | import { AuthService } from './auth.service'; 4 | import { OtpService } from './otp.service'; 5 | import { UserRepository } from '../repositories/user.repository'; 6 | import { AuthRequest } from 'src/models/authRequest'; 7 | import { User } from '../../../models/user'; 8 | import log from './../../../utils/logger'; 9 | 10 | export class SessionAuthService implements AuthService { 11 | 12 | constructor(private otp: OtpService, private userRepository: UserRepository) {} 13 | 14 | authenticate() { 15 | return (req: Request, res: Response, next: NextFunction) => { 16 | if (req.session && req.session.user) { 17 | req.user = req.session.user; 18 | next(); 19 | } else { 20 | res.statusCode = 401; 21 | res.json({ msg: 'You are not authorized to perform this operation' }); 22 | } 23 | }; 24 | } 25 | 26 | login(loginRequest: AuthRequest): Promise { 27 | const email = loginRequest.email; 28 | return this.userRepository.getUserByEmail(email).then(user => { 29 | return bcrypt.compare(loginRequest.password, user.password!).then(match => { 30 | if (match && user.confirmed) { 31 | 32 | // IDEA: add login throttler in catch block 33 | return this.otp.checkOtpIfRequired(loginRequest, user).then(() => { 34 | loginRequest.session.user = user; 35 | log.info('auth.session_login_successful', { user }); 36 | return Promise.resolve(User.toSafeUser(user)); 37 | }); 38 | 39 | } else { 40 | log.info('auth.session_login_failed', { user }); 41 | return Promise.reject(); 42 | } 43 | }); 44 | }); 45 | } 46 | 47 | logout(session: any): Promise { 48 | if (session && session.destroy) { 49 | return new Promise((resolve, reject) => { 50 | session.destroy((error: any) => { 51 | if (!error) { 52 | log.info('auth.session_logout_successful', { user: session.user }); 53 | resolve(); 54 | } else { 55 | log.error('auth.session_destroy_failed', { error }); 56 | reject(error); 57 | } 58 | }) 59 | }); 60 | } else { 61 | log.warn('auth.logout_session_not_found'); 62 | return Promise.resolve(); 63 | } 64 | } 65 | 66 | getCurrentUser(session: any): Promise { 67 | if (session && session.user) { 68 | const user = User.build(session.user); 69 | const safeUser = User.toSafeUser(user); 70 | return Promise.resolve(safeUser); 71 | } else { 72 | return Promise.resolve(); 73 | } 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /src/app/auth/services/signup.service.ts: -------------------------------------------------------------------------------- 1 | const randtoken = require('rand-token'); 2 | import bcrypt = require('bcryptjs'); 3 | import CONFIG from '../../../config'; 4 | import { OtpService } from './otp.service'; 5 | import { UserRepository } from '../repositories/user.repository'; 6 | import { AccountRepository } from '../repositories/account.repository'; 7 | import { InMemoryAccountRepository } from '../repositories/in-memory/in-memory-account.repository'; 8 | import { InMemoryUserRepository } from '../repositories/in-memory/in-memory-user.repository'; 9 | import { CategoriesRepository } from '../../settings/categories/categories.repository'; 10 | import { InMemoryCategoriesRepository } from '../../settings/categories/in-memory-categories.repository'; 11 | import { AuthRequest } from 'src/models/authRequest'; 12 | import log from './../../../utils/logger'; 13 | 14 | const userRepository: UserRepository = new InMemoryUserRepository(); 15 | const accountRepository: AccountRepository = new InMemoryAccountRepository(); 16 | const categoriesRepository: CategoriesRepository = new InMemoryCategoriesRepository(); 17 | const otp = new OtpService(); 18 | 19 | /* 20 | >>> Salt prevents from Rainbow Tables attack. How bcrypt generates salt? 21 | >>> Example code with explicit salt generation and hashing: 22 | 23 | bcrypt.genSalt(10).then(salt => { 24 | bcrypt.hash("password here", salt) 25 | .then(hash => console.log({ salt, hash })); 26 | }); 27 | 28 | >>> Results in: 29 | 30 | { 31 | salt: '$2a$10$f8.SA/84vLuIqChGu4Y/6u', 32 | hash: '$2a$10$f8.SA/84vLuIqChGu4Y/6uFZMdQsBSAnYjymCIrXLVsIihRiDN4kS' 33 | } 34 | 35 | >>> Where: 36 | 37 | $2a$ - bcrypt prefix 38 | $10$ - cost factor (2^10 ==> 1,024 iterations) 39 | f8.SA/84vLuIqChGu4Y/6u - salt 40 | FZMdQsBSAnYjymCIrXLVsIihRiDN4kS - hash 41 | 42 | >>> Structure: 43 | 44 | $2a$[cost]$[22 character salt][31 character hash] 45 | \__/\____/ \_________________/\_________________/ 46 | Alg Cost Salt Hash 47 | 48 | */ 49 | export class SignupService { 50 | 51 | signup(signupRequest: AuthRequest): Promise { 52 | const confirmationCode = randtoken.uid(256); 53 | return bcrypt.hash(signupRequest.password, 10) // 10 is the cost factor (implicit salt generation) 54 | .then(hashedPassword => accountRepository.createAccount({}) 55 | .then(accountId => Promise.all([ 56 | categoriesRepository.createDefaultCategories(accountId), 57 | userRepository.createUser({ 58 | accountId: accountId, 59 | email: signupRequest.email, 60 | password: hashedPassword, 61 | role: 'OWNER', 62 | confirmed: false, 63 | confirmationCode, 64 | createdWith: 'password', 65 | tfaSecret: otp.generateNewSecret() 66 | }) 67 | ])).then(() => { 68 | log.info('auth.signup_successful', { email: signupRequest.email }); 69 | this.sendConfirmationEmail(signupRequest.email, confirmationCode); 70 | return Promise.resolve(); 71 | }).catch(error => { 72 | log.error('auth.signup_failed', { email: signupRequest.email }); 73 | throw error; // rethrow the error for the controller 74 | }) 75 | ); 76 | } 77 | 78 | confirm(email: string, confirmationCode: string): Promise { 79 | return userRepository.getUserByEmail(email).then(user => { 80 | if (user && !user.confirmed && user.confirmationCode === confirmationCode) { 81 | user.confirmed = true; 82 | user.confirmationCode = undefined; 83 | log.info('auth.confirmation_successful', { email }); 84 | } else { 85 | log.warn('auth.confirmation_failed', { email }); 86 | return Promise.reject(); 87 | } 88 | }); 89 | } 90 | 91 | private sendConfirmationEmail(email: string, code: string) { 92 | const link = `${CONFIG.clientUrl}/confirm?email=${email}&code=${code}`; 93 | console.log(`>>> LINK >>>: ${link}`); // mock email sending :) 94 | log.info('auth.signup_confirmation_email_sent', { email }); 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /src/app/auth0/auth0.api.ts: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | 3 | import { Id } from '../../models/types'; 4 | import log from '../../utils/logger'; 5 | import config from '../../config'; 6 | 7 | export class Auth0Api { 8 | 9 | getIdToken(authCode: string): Promise { 10 | const options = { headers: { accept: 'application/json' } }; 11 | const body = { 12 | client_id: config.auth0.clientID, 13 | client_secret: config.auth0.clientSecret, 14 | redirect_uri: config.auth0.callbackURL, 15 | grant_type: 'authorization_code', 16 | code: authCode 17 | }; 18 | 19 | return axios.post(config.auth0.accessTokenUrl, body, options) 20 | .then((res: any) => res.data['id_token']) 21 | .catch((error: any) => { 22 | log.error('auth0.getIdToken_failed', { error }); 23 | throw error; 24 | }) 25 | } 26 | 27 | getAccessToken(): Promise { 28 | const options = { headers: { accept: 'application/json' } }; 29 | const body = { 30 | client_id: config.auth0.clientID, 31 | client_secret: config.auth0.clientSecret, 32 | audience: config.auth0.apiUrl, 33 | grant_type: 'client_credentials' 34 | }; 35 | 36 | return axios.post(config.auth0.accessTokenUrl, body, options) 37 | .then((res: any) => res.data['access_token']) 38 | .catch((error: any) => { 39 | log.error('auth0.getAccessToken_failed', { error }); 40 | throw error; 41 | }); 42 | } 43 | 44 | updateUser(accessToken: string, userId: Id, data: any) { 45 | const options = { headers: { Authorization: `Bearer ${accessToken}` } }; 46 | return axios.patch(`${config.auth0.apiUrl}users/${userId}`, data, options) 47 | .then((res: any) => { 48 | log.info('auth0.user.updated', { userId, data }); 49 | return res.data; 50 | }).catch((error: any) => { 51 | log.error('auth0.user.update_failed', { error }); 52 | return Promise.reject('Could not signup user'); 53 | }); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/app/auth0/auth0.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | import { Auth0Service } from './auth0.service'; 3 | import stateService from '../auth/services/external-auth/state.service'; 4 | import config from '../../config'; 5 | 6 | const router = Router(); 7 | const auth0 = new Auth0Service(); 8 | 9 | router.get('/', function (req: Request, res: Response) { 10 | 11 | res.redirect(`${config.auth0.authorizeUrl}` + 12 | `?client_id=${config.auth0.clientID}` + 13 | `&state=${stateService.setAndGetNewState(req.session)}` + 14 | `&response_type=code` + 15 | `&scope=${config.auth0.scope}` + 16 | `&redirect_uri=${config.auth0.callbackURL}`); 17 | 18 | }); 19 | 20 | router.get('/callback', function (req, res) { 21 | const authCode = req.query.code as string; 22 | const state = req.query.state as string; 23 | 24 | stateService.assertStateIsValid(req.session, state) 25 | .then(() => checkErrors(req)) 26 | .then(() => auth0.login(authCode, req.session)) 27 | .then(() => res.redirect('/')) 28 | .catch((err) => res.redirect(`/login?msg=${err}`)); 29 | }); 30 | 31 | function checkErrors(req: Request) { 32 | if (req.query.error) { 33 | throw new Error(req.query.error_description as string); 34 | } 35 | } 36 | 37 | export default router; -------------------------------------------------------------------------------- /src/app/auth0/auth0.service.ts: -------------------------------------------------------------------------------- 1 | import { User } from '../../models/user'; 2 | import { Id, UserRole } from '../../models/types'; 3 | import { AccountRepository } from '../auth/repositories/account.repository'; 4 | import { CategoriesRepository } from '../settings/categories/categories.repository'; 5 | import { InMemoryAccountRepository } from '../auth/repositories/in-memory/in-memory-account.repository'; 6 | import { InMemoryCategoriesRepository } from '../settings/categories/in-memory-categories.repository'; 7 | import { Auth0Api } from './auth0.api'; 8 | import log from '../../utils/logger'; 9 | 10 | // TODO provide configuration for repositories 11 | const accountRepository: AccountRepository = new InMemoryAccountRepository(); 12 | const categoriesRepository: CategoriesRepository = new InMemoryCategoriesRepository(); 13 | const auth0 = new Auth0Api(); 14 | 15 | export class Auth0Service { 16 | 17 | private readonly USER_DATA = 'https://budget.com/userdata'; 18 | 19 | login(authCode: string, session: any): Promise { 20 | 21 | return auth0.getIdToken(authCode) 22 | .then(token => this.getUserFromToken(token)) 23 | .then(user => this.doLogin(user, session)) 24 | .catch((error) => { 25 | log.error(`auth0.session_login_failed`, { error: error.toString() }); 26 | throw error; 27 | }); 28 | 29 | } 30 | 31 | private doLogin(user: any, session: any): Promise { 32 | return this.signupIfNeeded(user, session).then((signedUser) => { 33 | session.user = signedUser ? this.normalizeUserFromApi(signedUser) : user; 34 | log.info(`auth0.session_login_successful`, { user }); 35 | }); 36 | } 37 | 38 | private signupIfNeeded(user: User, session: any): Promise { 39 | if (this.isUserSignedUp(user)) { 40 | return Promise.resolve(); 41 | } else { 42 | 43 | let accountId: Id; 44 | 45 | return accountRepository.createAccount({}) 46 | .then(createdAccountId => { accountId = createdAccountId }) 47 | .then(() => categoriesRepository.createDefaultCategories(accountId)) 48 | .then(() => this.setUserAccountAndRole(user.id, accountId, 'OWNER')) 49 | .then(signedUser => { 50 | log.info(`auth0.signup_successful`, { user: signedUser }); 51 | return signedUser; 52 | }); 53 | 54 | } 55 | } 56 | 57 | private setUserAccountAndRole(userId: Id, accountId: Id, role: UserRole) { 58 | return auth0.getAccessToken() 59 | .then(token => auth0.updateUser(token, userId, { 60 | app_metadata: { 61 | accountId, role, 62 | } 63 | })) 64 | } 65 | 66 | private isUserSignedUp(user: any) { 67 | return user[this.USER_DATA] 68 | && user[this.USER_DATA].role 69 | && user[this.USER_DATA].accountId; 70 | } 71 | 72 | private getUserFromToken(token: string) { 73 | const rawUser = token.split('.')[1]; 74 | const user = JSON.parse(Buffer.from(rawUser, 'base64').toString()); 75 | return this.normalizeUserFromToken(user); 76 | } 77 | 78 | private normalizeUserFromToken(user: any): User { 79 | const userdata = user[this.USER_DATA]; 80 | Object.assign(user, userdata, { id: user.sub }); 81 | return User.build(user); 82 | } 83 | 84 | private normalizeUserFromApi(user: any): User { 85 | const userdata = user.app_metadata; 86 | Object.assign(user, userdata, { id: user.user_id }); 87 | return User.build(user); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/app/dashboard/budget.repository.ts: -------------------------------------------------------------------------------- 1 | import { Id } from '../../models/types'; 2 | import { Period } from '../../models/period'; 3 | import { Budget } from '../../models/budget'; 4 | import { BudgetSummary } from '../../models/budgetSummary'; 5 | 6 | export interface BudgetRepository { 7 | 8 | getBugdets(accountId: Id, period: Period): Promise; 9 | 10 | getBudgetSummary(accountId: Id, period: Period): Promise; 11 | 12 | } -------------------------------------------------------------------------------- /src/app/dashboard/dashboard.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { BudgetRepository } from './budget.repository'; 3 | import { buildPeriodFromRequest } from '../../utils/controller.utils'; 4 | import { User } from '../../models/user'; 5 | 6 | export class DashboardController { 7 | 8 | private readonly router: Router; 9 | 10 | constructor(private repository: BudgetRepository) { 11 | this.router = Router(); 12 | this.initRoutes(); 13 | } 14 | 15 | public getRouter() { 16 | return this.router; 17 | } 18 | 19 | private initRoutes() { 20 | 21 | this.router.get('/budgets', (req: Request, res: Response) => { 22 | const user = req.user as User; 23 | this.repository.getBugdets(user.accountId as string, buildPeriodFromRequest(req)) 24 | .then(budgets => res.json(budgets)) 25 | .catch(() => res.status(404).json({msg: 'Budgets not found'})); 26 | }); 27 | 28 | this.router.get('/budget-summary', (req: Request, res: Response) => { 29 | const user = req.user as User; 30 | this.repository.getBudgetSummary(user.accountId as string, buildPeriodFromRequest(req)) 31 | .then(summary => res.json(summary)) 32 | .catch(() => res.status(404).json({msg: 'Budget summary not found'})); 33 | }); 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /src/app/dashboard/in-memory-budget.repository.ts: -------------------------------------------------------------------------------- 1 | import { BudgetRepository } from './budget.repository'; 2 | import { CATEGORIES } from '../settings/categories/in-memory-categories.repository'; 3 | import { Id } from '../../models/types'; 4 | import { Period } from '../../models/period'; 5 | import { Budget } from '../../models/budget'; 6 | import { BudgetSummary } from '../../models/budgetSummary'; 7 | 8 | export class InMemoryBudgetRepository implements BudgetRepository { 9 | 10 | getBugdets(accountId: Id, period: Period): Promise { 11 | const budgets = BUDGETS.filter(budget => period.equals(budget.period) && budget.accountId === accountId); 12 | return Promise.resolve(budgets ? budgets : []); 13 | } 14 | 15 | getBudgetSummary(accountId: Id, period: Period): Promise { 16 | const summary = BUDGET_SUMMARIES.find(summary => period.equals(summary.period) && summary.accountId === accountId); 17 | return new Promise((resolve, reject) => { 18 | summary ? resolve(summary) : reject(); 19 | }); 20 | } 21 | 22 | } 23 | 24 | const period = new Period(3, 2020); // TODO remove this fixture 25 | 26 | const BUDGETS: Budget[] = [ 27 | Budget.build({ 28 | id: '1', 29 | accountId: '1', 30 | period: period, 31 | category: CATEGORIES[0], 32 | currentExpenses: 100, 33 | maxExpenses: 500 34 | }), 35 | Budget.build({ 36 | id: '2', 37 | accountId: '1', 38 | period: period, 39 | category: CATEGORIES[1], 40 | currentExpenses: 100, 41 | maxExpenses: 300 42 | }), 43 | Budget.build({ 44 | id: '3', 45 | accountId: '2', 46 | period: period, 47 | category: CATEGORIES[2], 48 | currentExpenses: 200, 49 | maxExpenses: 300 50 | }) 51 | ]; 52 | 53 | const summary1 = new BudgetSummary('1', period); 54 | summary1.totalExpenses = 200; 55 | summary1.totalBudget = 800; 56 | 57 | const summary2 = new BudgetSummary('2', period); 58 | summary2.totalExpenses = 200; 59 | summary2.totalBudget = 300; 60 | 61 | const BUDGET_SUMMARIES: BudgetSummary[] = [summary1, summary2]; -------------------------------------------------------------------------------- /src/app/expenses/expenses.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { ExpensesRepository } from './expenses.repository'; 3 | import { buildPeriodFromRequest } from '../../utils/controller.utils'; 4 | import { expenseBelongsToAccount } from './expenses.middleware'; 5 | import { readerOnlyReads } from '../auth/role.middleware'; 6 | import expensesValidator from './expenses.validator'; 7 | import { User } from '../../models/user'; 8 | 9 | export class ExpensesController { 10 | 11 | private readonly router: Router; 12 | 13 | constructor(private repository: ExpensesRepository) { 14 | this.router = Router(); 15 | this.initRoutes(); 16 | } 17 | 18 | public getRouter() { 19 | return this.router; 20 | } 21 | 22 | private initRoutes() { 23 | this.router.use('/expenses', readerOnlyReads()); 24 | 25 | this.router.get('/expenses', (req: Request, res: Response) => { 26 | const user = req.user as User; 27 | const period = buildPeriodFromRequest(req); 28 | const categoryQuery = req.query.categoryName; 29 | 30 | if (!categoryQuery) { 31 | this.repository.getExpenses(user.accountId as string, period).then(expenses => res.json(expenses)); 32 | } else { 33 | this.repository.getExpensesByCategory(user.accountId as string, period, categoryQuery as string) 34 | .then(expenses => res.json(expenses)); 35 | } 36 | }); 37 | 38 | this.router.post('/expenses', expensesValidator, (req: Request, res: Response) => { 39 | const user = req.user as User; 40 | const expense = req.body; 41 | expense.accountId = user.accountId; 42 | 43 | this.repository.createExpense(expense) 44 | .then(() => res.status(201).json()); 45 | }); 46 | 47 | this.router.put('/expenses/:id', expenseBelongsToAccount(), expensesValidator, (req: Request, res: Response) => { 48 | const user = req.user as User; 49 | const expense = req.body; 50 | expense.id = req.params.id; 51 | expense.accountId = user.accountId; 52 | 53 | this.repository.updateExpense(expense) 54 | .then(() => res.status(200).json()); 55 | }); 56 | 57 | this.router.delete('/expenses/:id', expenseBelongsToAccount(), (req: Request, res: Response) => { 58 | const expenseId = req.params.id; 59 | this.repository.deleteExpense(expenseId) 60 | .then(() => res.sendStatus(204)); 61 | }); 62 | 63 | } 64 | 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/app/expenses/expenses.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { ExpensesRepository } from './expenses.repository'; 3 | import { InMemoryExpensesRepository } from './in-memory-expenses.repository'; 4 | import { User } from '../../models/user'; 5 | 6 | const expensesRepository: ExpensesRepository = new InMemoryExpensesRepository(); 7 | 8 | export function expenseBelongsToAccount() { 9 | 10 | return function (req: Request, res: Response, next: NextFunction) { 11 | const user = req.user as User; 12 | const expenseId = req.params.id; 13 | 14 | if (!expenseId) { 15 | return next(); 16 | } 17 | 18 | expensesRepository.getExpense(expenseId).then(expense => { 19 | if (expense.accountId === user.accountId) { 20 | return next(); 21 | } else { 22 | res.status(403).json({ msg: 'You are not authorized to perform this operation' }); 23 | return next('Unauthorized'); 24 | } 25 | }).catch(() => res.sendStatus(404)); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /src/app/expenses/expenses.repository.ts: -------------------------------------------------------------------------------- 1 | import { Id } from '../../models/types'; 2 | import { Period } from '../../models/period'; 3 | import { Expense } from '../../models/expense'; 4 | 5 | export interface ExpensesRepository { 6 | 7 | getExpense(id: Id): Promise; 8 | 9 | getExpenses(accountId: Id, period: Period): Promise; 10 | 11 | getExpensesByCategory(accountId: Id, period: Period, category: string): Promise; 12 | 13 | createExpense(expense: Expense): Promise; 14 | 15 | updateExpense(expense: Expense): Promise; 16 | 17 | deleteExpense(id: Id): Promise; 18 | 19 | } -------------------------------------------------------------------------------- /src/app/expenses/expenses.validator.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { check, validationResult, ValidationError } from 'express-validator'; 3 | import log from './../../utils/logger'; 4 | 5 | function value() { 6 | return check('value').isNumeric() 7 | .withMessage('must be a number'); 8 | } 9 | 10 | function datetime() { 11 | return check('datetime').escape(); 12 | } 13 | 14 | function counterparty() { 15 | return check('counterparty').escape(); 16 | } 17 | 18 | function errorParser() { 19 | return function (req: Request, res: Response, next: NextFunction) { 20 | const errors = validationResult(req); 21 | if (!errors.isEmpty()) { 22 | log.warn('expenses.validation_failed', {errors: errors.array()}); 23 | res.status(422).json({ msg: formatErrors(errors.array()) }); 24 | } else { 25 | next(); 26 | } 27 | } 28 | } 29 | 30 | function formatErrors(errors: ValidationError[]) { 31 | return errors.map(e => `${e.param} ${e.msg}`).join(', '); 32 | } 33 | 34 | export default [value(), datetime(), counterparty(), errorParser()]; -------------------------------------------------------------------------------- /src/app/expenses/in-memory-expenses.repository.ts: -------------------------------------------------------------------------------- 1 | import { ExpensesRepository } from './expenses.repository'; 2 | import { CATEGORIES } from '../settings/categories/in-memory-categories.repository'; 3 | import { Id } from '../../models/types'; 4 | import { Period } from '../../models/period'; 5 | import { Expense } from '../../models/expense'; 6 | 7 | export class InMemoryExpensesRepository implements ExpensesRepository { 8 | 9 | getExpense(id: Id): Promise { 10 | let expense = EXPENSES.find(expense => expense.id === id); 11 | this.attachCategory(expense); 12 | return new Promise((resolve, reject) => { 13 | expense ? resolve(expense) : reject(); 14 | }); 15 | } 16 | 17 | getExpenses(accountId: Id, period: Period): Promise { 18 | const expenses = EXPENSES.filter(expense => period.equals(expense.period) && expense.accountId === accountId); 19 | expenses.forEach(e => this.attachCategory(e)); 20 | return new Promise((resolve, reject) => { 21 | expenses ? resolve(expenses) : reject(); 22 | }); 23 | } 24 | 25 | getExpensesByCategory(accountId: Id, period: Period, category: string): Promise { 26 | const expenses = EXPENSES.filter( 27 | expense => period.equals(expense.period) && 28 | expense.accountId === accountId && 29 | expense.category && expense.category.name.toLowerCase().includes(category)); 30 | return new Promise((resolve, reject) => { 31 | expenses ? resolve(expenses) : reject(); 32 | }); 33 | } 34 | 35 | createExpense(expense: Expense): Promise { 36 | expense.id = (EXPENSES.length + 1).toString(); 37 | EXPENSES.push(expense); 38 | return Promise.resolve(); 39 | } 40 | 41 | updateExpense(expense: Expense): Promise { 42 | return this.getExpense(expense.id) 43 | .then(expenseToUpdate => { 44 | Object.assign(expenseToUpdate, expense); 45 | }); 46 | } 47 | 48 | deleteExpense(id: Id): Promise { 49 | EXPENSES = EXPENSES.filter(expense => expense.id !== id); 50 | return Promise.resolve(); 51 | } 52 | 53 | private attachCategory(expense: Expense | undefined) { 54 | if (expense) { 55 | expense.category = CATEGORIES.find(category => category.id === expense.categoryId);; 56 | } 57 | } 58 | 59 | } 60 | 61 | const period = new Period(3, 2020); 62 | const date1 = new Date('2020-03-02'); 63 | const date2 = new Date('2020-03-11'); 64 | 65 | let EXPENSES: Expense[] = [ 66 | new Expense('1', '1', 21.4, date1, period, '1', 'McDonalds'), 67 | new Expense('2', '1', 31.9, date2, period, '3', 'CinemaCity'), 68 | new Expense('3', '2', 21.5, date2, period, '8', 'CinemaX'), 69 | new Expense('4', '2', 11.5, date1, period, '6', 'KFC'), 70 | ]; 71 | -------------------------------------------------------------------------------- /src/app/settings/account/account.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { AccountService } from './account.service'; 3 | import { denyOwnUserDeletion, userBelongsToAccount, allowOwnUserPatchOnly } from './account.middleware'; 4 | import { OtpService } from './../../auth/services/otp.service'; 5 | import { hasRole } from '../../auth/role.middleware'; 6 | import { User } from '../../../models/user'; 7 | 8 | const accountService = new AccountService(); 9 | const otpService = new OtpService(); 10 | const router = Router(); 11 | 12 | router.use('/users', hasRole('OWNER')); 13 | 14 | router.get('/users', function (req: Request, res: Response) { 15 | const user = req.user as User; 16 | 17 | accountService.getUsers(user.accountId!) 18 | .then(users => res.json(users)); 19 | }); 20 | 21 | router.post('/users', function (req: Request, res: Response) { 22 | const currentUser = req.user as User; 23 | const newUser = req.body as User; 24 | 25 | accountService.createUser(newUser.email!, newUser.role!, currentUser.accountId) 26 | .then(() => res.status(201).json()) 27 | .catch((err) => res.status(401).json({ msg: err ? err : 'Creating user failed' })); 28 | }); 29 | 30 | router.patch('/users/:id', allowOwnUserPatchOnly(), function (req: Request, res: Response) { 31 | const userToPatchId = req.params.id; 32 | const propsToPatch = req.body; 33 | 34 | accountService.patchUser(userToPatchId, propsToPatch, req.session) 35 | .then(() => res.status(201).json()) 36 | .catch((err) => res.status(400).json({ msg: err ? err : 'Editing user failed' })); 37 | }); 38 | 39 | router.delete('/users/:id', denyOwnUserDeletion(), userBelongsToAccount(), function (req: Request, res: Response) { 40 | const userToDeleteId = req.params.id; 41 | 42 | accountService.deleteUser(userToDeleteId) 43 | .then(() => res.sendStatus(204)); 44 | }); 45 | 46 | router.get('/secret', function (req: Request, res: Response) { 47 | const currentUser = req.user as User; 48 | if (currentUser.tfaSecret) { 49 | const keyuri = otpService.getOtpKeyUri(currentUser); 50 | res.status(200).json({ keyuri }); 51 | } else { 52 | res.status(400).json({ msg: 'Error with generating code' }); 53 | } 54 | }); 55 | 56 | export default router; -------------------------------------------------------------------------------- /src/app/settings/account/account.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { UserRepository } from '../../auth/repositories/user.repository'; 3 | import { InMemoryUserRepository } from '../../auth/repositories/in-memory/in-memory-user.repository'; 4 | import { User } from '../../../models/user'; 5 | 6 | const repository: UserRepository = new InMemoryUserRepository(); 7 | 8 | export function userBelongsToAccount() { 9 | 10 | return function (req: Request, res: Response, next: NextFunction) { 11 | const currentUser = req.user as User; 12 | const requestedUserId = req.params.id; 13 | 14 | if (!requestedUserId) { 15 | return next(); 16 | } 17 | 18 | repository.getUserById(requestedUserId).then(requestedUser => { 19 | if (requestedUser.accountId === currentUser.accountId) { 20 | return next(); 21 | } else { 22 | res.status(403).json({ msg: 'You are not authorized to perform this operation' }); 23 | return next('Unauthorized'); 24 | } 25 | }).catch(() => res.sendStatus(404)); 26 | } 27 | 28 | } 29 | 30 | export function denyOwnUserDeletion() { 31 | 32 | return function (req: Request, res: Response, next: NextFunction) { 33 | const user = req.user as User; 34 | const userToDeleteId = req.params.id; 35 | 36 | if (userToDeleteId && userToDeleteId === user.id && req.method.toUpperCase() === 'DELETE') { 37 | res.status(403).json({ msg: 'Cannot delete your own user' }); 38 | } else { 39 | next(); 40 | } 41 | } 42 | 43 | } 44 | 45 | export function allowOwnUserPatchOnly() { 46 | 47 | return function (req: Request, res: Response, next: NextFunction) { 48 | const user = req.user as User; 49 | const userToPatchId = req.params.id; 50 | 51 | if (userToPatchId && userToPatchId === user.id && req.method.toUpperCase() === 'PATCH') { 52 | next(); 53 | } else { 54 | res.status(403).json({ msg: 'Operation not permitted' }); 55 | } 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /src/app/settings/account/account.service.ts: -------------------------------------------------------------------------------- 1 | const randtoken = require('rand-token'); 2 | import CONFIG from '../../../config'; 3 | import log from './../../../utils/logger'; 4 | import { UserRepository } from '../../auth/repositories/user.repository'; 5 | import { InMemoryUserRepository } from '../../auth/repositories/in-memory/in-memory-user.repository'; 6 | import { UserRole, Id } from '../../../models/types'; 7 | import { User } from '../../../models/user'; 8 | 9 | const userRepository: UserRepository = new InMemoryUserRepository(); 10 | 11 | const PATCHABLE_PROPS = ['tfa']; 12 | 13 | export class AccountService { 14 | 15 | getUsers(accountId: string): Promise { 16 | return userRepository.getUsers(accountId) 17 | .then(users => users.map(u => User.toSafeUser(u))); 18 | } 19 | 20 | createUser(userEmail: string, role: UserRole, accountId: Id): Promise { 21 | const confirmationCode = randtoken.uid(256); 22 | return userRepository.createUser({ 23 | accountId: accountId, 24 | email: userEmail, 25 | password: undefined, 26 | role: role, 27 | confirmed: false, 28 | confirmationCode, 29 | createdWith: 'password' 30 | }).then(() => { 31 | log.info('settings.create_user_successful', { email: userEmail }); 32 | this.sendConfirmationEmail(userEmail, confirmationCode); 33 | return Promise.resolve(); 34 | }).catch(error => { 35 | log.error('settings.create_user_failed', { email: userEmail }); 36 | throw error; // rethrow the error for the controller 37 | }); 38 | } 39 | 40 | patchUser(userId: Id, data: any, session?: any): Promise { 41 | const filteredUser = Object.keys(data) 42 | .filter(property => PATCHABLE_PROPS.includes(property)) 43 | .reduce((user: any, property) => { 44 | user[property] = data[property]; 45 | return user; 46 | }, {}); 47 | 48 | return userRepository.patchUser(userId, filteredUser) 49 | .then(patchedUser => { 50 | if (session && session.user && session.user.id === userId) { 51 | session.user = patchedUser; 52 | } 53 | }) 54 | } 55 | 56 | deleteUser(userId: Id): Promise { 57 | return userRepository.deleteUser(userId); 58 | } 59 | 60 | private sendConfirmationEmail(email: string, code: string) { 61 | const link = `${CONFIG.clientUrl}/password?email=${email}&code=${code}`; 62 | console.log(`>>> LINK >>>: ${link}`); // mock email sending :) 63 | log.info('settings.create_user_confirmation_email_sent', { email }); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/app/settings/categories/categories.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response } from 'express'; 2 | import { CategoriesRepository } from './categories.repository'; 3 | import { InMemoryCategoriesRepository } from './in-memory-categories.repository'; 4 | import { categoryBelongsToAccount } from './categories.middleware'; 5 | import { User } from '../../../models/user'; 6 | 7 | const repository: CategoriesRepository = new InMemoryCategoriesRepository(); // TODO use DI container 8 | const router = Router(); 9 | 10 | // TODO implement role checks in all routes 11 | 12 | router.get('/expense-categories/:id', categoryBelongsToAccount(), function (req: Request, res: Response) { 13 | repository.getCategory(req.params.id) 14 | .then(category => res.json(category)); 15 | }); 16 | 17 | router.get('/expense-categories', function (req: Request, res: Response) { 18 | const user = req.user as User; 19 | 20 | repository.getCategories(user.accountId as string) 21 | .then(categories => res.json(categories)); 22 | }); 23 | 24 | export default router; -------------------------------------------------------------------------------- /src/app/settings/categories/categories.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { CategoriesRepository } from './categories.repository'; 3 | import { InMemoryCategoriesRepository } from './in-memory-categories.repository'; 4 | import { User } from '../../../models/user'; 5 | 6 | const repository: CategoriesRepository = new InMemoryCategoriesRepository(); 7 | 8 | export function categoryBelongsToAccount() { 9 | 10 | return function (req: Request, res: Response, next: NextFunction) { 11 | const user = req.user as User; 12 | const categoryId = req.params.id; 13 | 14 | if (!categoryId) { 15 | return next(); 16 | } 17 | 18 | repository.getCategory(categoryId).then(category => { 19 | if (category.accountId === user.accountId) { 20 | return next(); 21 | } else { 22 | res.status(401).json({ error: 'You are not authorized to perform this operation' }); 23 | return next('Unauthorized'); 24 | } 25 | }).catch(() => res.sendStatus(404)); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /src/app/settings/categories/categories.repository.ts: -------------------------------------------------------------------------------- 1 | import { Id } from 'src/models/types'; 2 | import { Category } from 'src/models/category'; 3 | 4 | export interface CategoriesRepository { 5 | 6 | getCategory(id: Id): Promise; 7 | 8 | getCategories(accountId: Id): Promise; 9 | 10 | createDefaultCategories(accountId: Id): Promise; 11 | 12 | } -------------------------------------------------------------------------------- /src/app/settings/categories/in-memory-categories.repository.ts: -------------------------------------------------------------------------------- 1 | import { CategoriesRepository } from './categories.repository'; 2 | import { Category } from '../../../models/category'; 3 | import { Id } from '../../../models/types'; 4 | 5 | export class InMemoryCategoriesRepository implements CategoriesRepository { 6 | 7 | getCategory(id: Id): Promise { 8 | const category = CATEGORIES.find(c => c.id === id); 9 | return new Promise((resolve, reject) => { 10 | category ? resolve(category) : reject(); 11 | }); 12 | } 13 | 14 | getCategories(accountId: Id): Promise { 15 | const categories = CATEGORIES.filter(category => category.accountId === accountId); 16 | return new Promise((resolve, reject) => { 17 | categories ? resolve(categories) : reject(); 18 | }); 19 | } 20 | 21 | createDefaultCategories(accountId: Id): Promise { 22 | let nextId = CATEGORIES.length + 1; 23 | const newCategories = DEFAULT_CATEGORIES_NAMES.map(name => 24 | new Category((nextId++).toString(), accountId, name) 25 | ); 26 | CATEGORIES.push(...newCategories); 27 | return Promise.resolve(); 28 | } 29 | 30 | } 31 | 32 | export const CATEGORIES: Category[] = [ 33 | // accountId: 1 34 | new Category('1', '1', 'Food', ['mcdonalds']), 35 | new Category('2', '1', 'Shopping'), 36 | new Category('3', '1', 'Entertainment'), 37 | new Category('4', '1', 'Transport'), 38 | new Category('5', '1', 'Cloths'), 39 | 40 | // accountId: 2 41 | new Category('6', '2', 'Food'), 42 | new Category('7', '2', 'Shopping'), 43 | new Category('8', '2', 'Entertainment'), 44 | ]; 45 | 46 | const DEFAULT_CATEGORIES_NAMES: string[] = [ 47 | 'Food', 'Shopping', 'Entertainment' 48 | ]; 49 | -------------------------------------------------------------------------------- /src/app/settings/settings.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import accountCtrl from './account/account.controller'; 3 | import categoriesCtrl from './categories/categories.controller'; 4 | 5 | const router = Router(); 6 | 7 | router.use(accountCtrl); 8 | router.use(categoriesCtrl); 9 | 10 | export default router; -------------------------------------------------------------------------------- /src/config/index.ts: -------------------------------------------------------------------------------- 1 | import path = require('path'); 2 | import rfs = require('rotating-file-stream'); 3 | import { MemoryStore, SessionOptions } from 'express-session'; 4 | import { secret } from './secret'; 5 | 6 | const jwtSecret = 'VERY_SECRET_KEY!'; // TODO change in prod 7 | const cookieSecret = 'VERY_SECRET_KEY!'; // TODO change in prod 8 | 9 | const externalAuth = { 10 | github: { 11 | authorizeUrl: 'https://github.com/login/oauth/authorize', 12 | accessTokenUrl: 'https://github.com/login/oauth/access_token', 13 | userInfoUrl: 'https://api.github.com/user', 14 | callbackURL: 'http://localhost:8080/api/auth/external/github/callback', 15 | scope: 'user:email', 16 | clientID: secret.github.clientID, 17 | clientSecret: secret.github.clientSecret 18 | }, 19 | google: { 20 | authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth', 21 | accessTokenUrl: 'https://oauth2.googleapis.com/token', 22 | userInfoUrl: 'https://openidconnect.googleapis.com/v1/userinfo', 23 | callbackURL: 'http://localhost:8080/api/auth/external/google/callback', 24 | scope: 'openid email profile', 25 | clientID: secret.google.clientID, 26 | clientSecret: secret.google.clientSecret 27 | } 28 | } 29 | 30 | const auth0Config = { 31 | apiUrl: 'https://dev-5qi53ez9.eu.auth0.com/api/v2/', 32 | authorizeUrl: 'https://dev-5qi53ez9.eu.auth0.com/authorize', 33 | accessTokenUrl: 'https://dev-5qi53ez9.eu.auth0.com/oauth/token', 34 | userInfoUrl: 'https://dev-5qi53ez9.eu.auth0.com/authorize/userinfo', 35 | callbackURL: 'http://localhost:8080/api/auth0/callback', 36 | scope: 'openid email profile', 37 | clientID: secret.auth0.clientID, 38 | clientSecret: secret.auth0.clientSecret 39 | } 40 | 41 | const bunyanStreamSetting = process.env.LOGS || 'file'; 42 | const bunyanStdoutStream = { stream: process.stdout }; 43 | const bunyanFileStream = { 44 | type: 'rotating-file', 45 | path: path.join(process.cwd(), 'log', 'app'), 46 | period: '1d', 47 | count: 3 48 | }; 49 | 50 | export default { 51 | jwtSecret, 52 | externalAuth, 53 | auth0: auth0Config, 54 | auth: 'jwt' as 'session' | 'jwt', 55 | loginThrottle: { 56 | maxFailures: 3, 57 | timeWindowInMinutes: 10 58 | }, 59 | clientUrl: 'http://localhost:8080', 60 | sessionConfig: { 61 | name: 'session_id', 62 | secret: cookieSecret, 63 | saveUninitialized: true, 64 | resave: false, 65 | cookie: { 66 | sameSite: 'lax' as 'lax', 67 | maxAge: 3600000 68 | }, 69 | store: new MemoryStore() 70 | } as SessionOptions, 71 | morganPattern: 'common', 72 | morganStream: rfs.createStream('access.log', { 73 | interval: '1d', 74 | path: path.join(process.cwd(), 'log') 75 | }), 76 | bunyanStream: bunyanStreamSetting === 'stdout' ? bunyanStdoutStream : bunyanFileStream 77 | } -------------------------------------------------------------------------------- /src/config/secret.ts: -------------------------------------------------------------------------------- 1 | export const secret = { 2 | github: { 3 | clientID: '', 4 | clientSecret: '' 5 | }, 6 | google: { 7 | clientID: '', 8 | clientSecret: '' 9 | }, 10 | auth0: { 11 | clientID: '', 12 | clientSecret: '' 13 | } 14 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import cors = require('cors'); 2 | import morgan = require('morgan'); 3 | import express = require('express'); 4 | import session = require('express-session'); 5 | import * as csrf from 'csurf'; 6 | import csrfCookieSetter from './utils/set-csrf-cookie'; 7 | import passport from './app/auth/passport'; 8 | import routes from './routes'; 9 | import config from './config'; 10 | import errorHandler from './utils/error-handler'; 11 | import serveIndex from './utils/serve-index'; 12 | import logger from './utils/logger'; 13 | import { User } from './models/user'; 14 | 15 | declare module 'express-session' { 16 | interface SessionData { user: User | null | undefined } 17 | } 18 | 19 | const app = express(); 20 | // app.use(express.static('../angular/dist/')); 21 | app.use(session(config.sessionConfig)); 22 | app.use(morgan(config.morganPattern, { stream: config.morganStream })); 23 | app.use(express.json()); 24 | app.use(express.urlencoded({ extended: true })); 25 | app.use(passport.initialize()); 26 | app.use(cors()); 27 | // app.use(csrf()); 28 | // app.use(csrfCookieSetter()); 29 | app.use(errorHandler()); 30 | app.use(logger.initialize()); 31 | app.use(routes); 32 | // app.get('*', serveIndex()); 33 | app.listen(8080, () => logger.info('main.app_start')); -------------------------------------------------------------------------------- /src/models/account.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | import { User } from './user'; 3 | 4 | export class Account { 5 | constructor( 6 | public id?: Id, 7 | users: User[] = []) { } 8 | } -------------------------------------------------------------------------------- /src/models/authRequest.ts: -------------------------------------------------------------------------------- 1 | import { Request } from 'express'; 2 | 3 | export class AuthRequest { 4 | 5 | constructor( 6 | public email: string, 7 | public password: string, 8 | public otp?: string, 9 | public session?: any) { } 10 | 11 | static buildFromRequest(req: Request): AuthRequest { 12 | return new AuthRequest( 13 | req.body.email, 14 | req.body.password, 15 | req.body.otp, 16 | req.session); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /src/models/budget.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | import { Period } from './period'; 3 | import { Category } from './category'; 4 | import { BudgetDefinition } from './budgetDefinition'; 5 | 6 | export class Budget { 7 | id?: string | number; 8 | accountId?: string | number; 9 | period!: Period; 10 | categoryId?: string; 11 | category?: Category; 12 | maxExpenses = 0; 13 | currentExpenses = 0; // updated during adding/removing expense 14 | get left(): number { return this.maxExpenses - this.currentExpenses; } 15 | get leftPercentage(): string { return 100 * this.currentExpenses / this.maxExpenses + '%'; } 16 | 17 | static build(input: BudgetInput): Budget { 18 | const budget = new Budget(); 19 | return Object.assign(budget, input); 20 | } 21 | 22 | static buildFromJson(json: any): Budget { 23 | const budget = new Budget(); 24 | return Object.assign(budget, json); 25 | } 26 | 27 | static buildFromDefinition(accountId: Id, period: Period, definition: BudgetDefinition): Budget { 28 | const budget = new Budget(); 29 | budget.accountId = accountId; 30 | budget.period = period; 31 | budget.maxExpenses = definition.maxExpenses; 32 | budget.category = definition.category; 33 | return budget; 34 | } 35 | } 36 | 37 | export interface BudgetInput { 38 | id?: string | number; 39 | accountId?: string | number; 40 | period?: Period; 41 | categoryId?: string; 42 | category?: Category; 43 | currentExpenses?: number; 44 | maxExpenses?: number; 45 | } 46 | -------------------------------------------------------------------------------- /src/models/budgetDefinition.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | import { Period } from './period'; 3 | import { Category } from './category'; 4 | 5 | export class BudgetDefinition { 6 | constructor(public id: Id, 7 | public period: Period, 8 | public category: Category, 9 | public maxExpenses: number) { } 10 | } 11 | -------------------------------------------------------------------------------- /src/models/budgetSummary.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | import { Period } from './period'; 3 | 4 | export class BudgetSummary { 5 | totalExpenses = 0; 6 | totalBudget = 0; 7 | get totalLeft() { return this.totalBudget - this.totalExpenses }; 8 | 9 | constructor (public accountId: Id, public period: Period) {} 10 | 11 | static buildFromJson(json: any): BudgetSummary { 12 | const budgetSummary = new BudgetSummary(json.accountId, json.period); 13 | return Object.assign(budgetSummary, json); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/models/category.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | 3 | export class Category { 4 | constructor( 5 | public id?: Id, 6 | public accountId?: Id, 7 | public name = '', 8 | public counterpartyPatterns: string[] = []) { } 9 | } 10 | -------------------------------------------------------------------------------- /src/models/expense.ts: -------------------------------------------------------------------------------- 1 | import { Id } from './types'; 2 | import { Period } from './period'; 3 | import { Category } from './category'; 4 | 5 | export class Expense { 6 | public category?: Category; 7 | 8 | constructor( 9 | public id?: Id, 10 | public accountId: Id = '', 11 | public value: number = 0, 12 | public datetime: Date = new Date(), 13 | public period: Period | null = null, 14 | public categoryId: Id = '', 15 | public counterparty: string = '') { } 16 | } 17 | -------------------------------------------------------------------------------- /src/models/login.failure.ts: -------------------------------------------------------------------------------- 1 | export class LoginFailure { 2 | 3 | constructor (public userEmail: string, public datetime: Date) {} 4 | 5 | } -------------------------------------------------------------------------------- /src/models/period.ts: -------------------------------------------------------------------------------- 1 | export class Period { 2 | constructor(public month: number, public year: number) { } 3 | 4 | public equals(period: Period | null) { 5 | if (period == null) { 6 | return false; 7 | } 8 | 9 | return this.month === period.month && 10 | this.year === period.year; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/models/token.ts: -------------------------------------------------------------------------------- 1 | export class Token { 2 | constructor (public jwt: string) {} 3 | } 4 | -------------------------------------------------------------------------------- /src/models/types.ts: -------------------------------------------------------------------------------- 1 | export const ROLES = ['OWNER', 'READER', 'ADMIN'] as const; 2 | export type Id = string | undefined; 3 | export type UserRole = typeof ROLES[number]; -------------------------------------------------------------------------------- /src/models/user.ts: -------------------------------------------------------------------------------- 1 | import { Id, UserRole } from './types'; 2 | import { Account } from './account'; 3 | 4 | export type AuthProvider = 'password' | 'github'; 5 | 6 | export class User { 7 | id?: Id; 8 | accountId?: Id; 9 | account?: Account; 10 | email?: string; 11 | password?: string; 12 | role?: UserRole; 13 | confirmed = false; 14 | confirmationCode? : string; 15 | recovery?: { 16 | code: string; 17 | requested: Date; 18 | }; 19 | 20 | tfa? = false; 21 | tfaSecret?: string; 22 | createdWith: AuthProvider = 'password'; 23 | externalId?: {[keyof: string]: string}; 24 | 25 | static toSafeUser(user: User): User { 26 | const { id, accountId, email, role, confirmed, tfa } = user; 27 | return { id, accountId, email, role, confirmed, tfa } as User; 28 | } 29 | 30 | static build(data: any): User { 31 | const user = new User(); 32 | return Object.assign(user, data); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/models/userInfo.ts: -------------------------------------------------------------------------------- 1 | export class UserInfo { 2 | id!: string; 3 | login!: string 4 | email!: string 5 | } -------------------------------------------------------------------------------- /src/routes.ts: -------------------------------------------------------------------------------- 1 | 2 | import { Router } from 'express'; 3 | import authCtrl from './app/auth/auth.controller'; 4 | import auth0Ctrl from './app/auth0/auth0.controller'; 5 | import adminCtrl from './app/admin/admin.controller'; 6 | import { DashboardController } from './app/dashboard/dashboard.controller'; 7 | import { ExpensesController } from './app/expenses/expenses.controller'; 8 | import settingsCtrl from './app/settings/settings.controller'; 9 | import authService from './app/auth/services/auth.service.instance'; 10 | 11 | import { InMemoryBudgetRepository } from './app/dashboard/in-memory-budget.repository'; 12 | import { InMemoryExpensesRepository } from './app/expenses/in-memory-expenses.repository'; 13 | 14 | const dashboardCtrl = new DashboardController(new InMemoryBudgetRepository()); 15 | const expensesCtrl = new ExpensesController(new InMemoryExpensesRepository()); 16 | 17 | const api = Router() 18 | .use(dashboardCtrl.getRouter()) 19 | .use(expensesCtrl.getRouter()) 20 | .use(settingsCtrl); 21 | 22 | export default Router() 23 | .use('/api/auth', authCtrl) 24 | .use('/api/auth0', auth0Ctrl) 25 | .use('/api/admin', authService.authenticate(), adminCtrl) 26 | .use('/api', authService.authenticate(), api); 27 | -------------------------------------------------------------------------------- /src/utils/controller.utils.ts: -------------------------------------------------------------------------------- 1 | import { Request } from 'express'; 2 | import { Period } from '../models/period'; 3 | 4 | export function buildPeriodFromRequest(req: Request) { 5 | const month = parseInt(req.query.month as string); 6 | const year = parseInt(req.query.year as string); 7 | return new Period(month, year); 8 | } -------------------------------------------------------------------------------- /src/utils/error-handler.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import log from './logger'; 3 | 4 | export default () => (err: any, req: Request, res: Response, next: NextFunction) => { 5 | if (err && err.code == "EBADCSRFTOKEN") { // csurf error code 6 | log.info('auth.invalid_csrf_token'); 7 | res.status(401).json({msg: 'Invalid CSRF Token - refresh the page!'}); 8 | } else if (err) { 9 | next(err); 10 | } else { 11 | next(); 12 | } 13 | } -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import bunyan = require('bunyan'); 2 | import { Request, Response, NextFunction } from 'express'; 3 | import { User } from './../models/user'; 4 | import CONFIG from './../config'; 5 | 6 | const serializers = { 7 | user: (user: User) => User.toSafeUser(user), 8 | req: (req: Request) => { 9 | return { 10 | ip: req.ip, 11 | method: req.method, 12 | url: req.url 13 | // add necessary properties to log 14 | } 15 | } 16 | } 17 | 18 | class Logger { 19 | 20 | private static req?: Request; 21 | private static bunyanLogger = bunyan.createLogger( 22 | { 23 | name: 'budget', 24 | streams: [CONFIG.bunyanStream], 25 | serializers 26 | } 27 | ) 28 | 29 | static initialize() { 30 | return (req: Request, res: Response, next: NextFunction) => { 31 | this.req = req; 32 | next(); 33 | } 34 | } 35 | 36 | static info(msg: string, fields?: any) { 37 | fields = { ...fields, req: this.req }; 38 | this.bunyanLogger.info(fields, msg); 39 | } 40 | 41 | static warn(msg: string, fields?: any) { 42 | fields = { ...fields, req: this.req }; 43 | this.bunyanLogger.warn(fields, msg); 44 | } 45 | 46 | static error(msg: string, fields?: any) { 47 | fields = { ...fields, req: this.req }; 48 | this.bunyanLogger.error(fields, msg); 49 | } 50 | 51 | } 52 | 53 | export default Logger; -------------------------------------------------------------------------------- /src/utils/serve-index.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import path = require('path'); 3 | 4 | export default () => (req: Request, res: Response, next: NextFunction) => { 5 | // this allows Angular Router find the route after refreshing the page 6 | res.sendFile(path.resolve('../angular/dist/index.html')) 7 | } -------------------------------------------------------------------------------- /src/utils/set-csrf-cookie.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | 3 | export default () => (req: Request, res: Response, next: NextFunction) => { 4 | res.cookie('XSRF-Token', req.csrfToken()); 5 | next(); 6 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "strict": true, 5 | "baseUrl": "./", 6 | "outDir": "build", 7 | "removeComments": true, 8 | "experimentalDecorators": true, 9 | "target": "es6", 10 | "emitDecoratorMetadata": true, 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "types": [ 14 | "node", 15 | "jest" 16 | ], 17 | "typeRoots": [ 18 | "node_modules/@types" 19 | ] 20 | }, 21 | "include": [ 22 | "./src/**/*.ts", 23 | "./declarations/*.ts" 24 | ] 25 | } --------------------------------------------------------------------------------