Add
This commit is contained in:
commit
74d0a47648
26
typescript/lunargame/api/.eslintrc.json
Normal file
26
typescript/lunargame/api/.eslintrc.json
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
{
|
||||||
|
"parser": "@typescript-eslint/parser",
|
||||||
|
"env": {
|
||||||
|
"es6": true,
|
||||||
|
"node": true,
|
||||||
|
"jest": true
|
||||||
|
},
|
||||||
|
"extends": [
|
||||||
|
"plugin:@typescript-eslint/recommended",
|
||||||
|
"prettier/@typescript-eslint",
|
||||||
|
"plugin:prettier/recommended"
|
||||||
|
],
|
||||||
|
"globals": {
|
||||||
|
"Atomics": "readonly",
|
||||||
|
"SharedArrayBuffer": "readonly"
|
||||||
|
},
|
||||||
|
"parserOptions": {
|
||||||
|
"ecmaVersion": 2018,
|
||||||
|
"sourceType": "module"
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
"@typescript-eslint/explicit-function-return-type": 0,
|
||||||
|
"@typescript-eslint/no-object-literal-type-assertion": 0,
|
||||||
|
"@typescript-eslint/no-parameter-properties": 0
|
||||||
|
}
|
||||||
|
}
|
5
typescript/lunargame/api/.gitignore
vendored
Normal file
5
typescript/lunargame/api/.gitignore
vendored
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
node_modules
|
||||||
|
.env
|
||||||
|
test/db.sqlite
|
||||||
|
db/db.sqlite
|
||||||
|
coverage
|
7
typescript/lunargame/api/.prettierrc.json
Normal file
7
typescript/lunargame/api/.prettierrc.json
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
{
|
||||||
|
"trailingComma": "none",
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 100,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"semi": false
|
||||||
|
}
|
8
typescript/lunargame/api/.vscode/settings.json
vendored
Normal file
8
typescript/lunargame/api/.vscode/settings.json
vendored
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"eslint.enable": true,
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"prettier.eslintIntegration": true,
|
||||||
|
"explorer.autoReveal": false,
|
||||||
|
"eslint.autoFixOnSave": true,
|
||||||
|
"eslint.validate": ["javascript", { "language": "typescript", "autoFix": true }]
|
||||||
|
}
|
201
typescript/lunargame/api/LICENSE
Normal file
201
typescript/lunargame/api/LICENSE
Normal file
|
@ -0,0 +1,201 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
3
typescript/lunargame/api/Readme.md
Normal file
3
typescript/lunargame/api/Readme.md
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
# Lunarbox
|
||||||
|
|
||||||
|
The lunarbox-api
|
26
typescript/lunargame/api/db/migrations/create_account.js
Normal file
26
typescript/lunargame/api/db/migrations/create_account.js
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
// in case i want to change it
|
||||||
|
// it's alwys a pain to change it everywhere
|
||||||
|
const tableName = 'account'
|
||||||
|
|
||||||
|
exports.up = knex => {
|
||||||
|
return knex.schema.createTable(tableName, table => {
|
||||||
|
// this is the id of the simulation
|
||||||
|
table.increments()
|
||||||
|
|
||||||
|
// the name of the user
|
||||||
|
table.text('name').notNullable()
|
||||||
|
|
||||||
|
// the email of the user
|
||||||
|
table.text('email').notNullable()
|
||||||
|
|
||||||
|
// the password of the user
|
||||||
|
table.text('password').notNullable()
|
||||||
|
|
||||||
|
// the password encryption
|
||||||
|
table.text('passwordEncryption').notNullable()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.down = knex => {
|
||||||
|
return knex.schema.dropTable(tableName)
|
||||||
|
}
|
11
typescript/lunargame/api/jest.config.js
Normal file
11
typescript/lunargame/api/jest.config.js
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
module.exports = {
|
||||||
|
roots: ['<rootDir>/src'],
|
||||||
|
transform: {
|
||||||
|
'^.+\\.tsx?$': 'ts-jest'
|
||||||
|
},
|
||||||
|
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
|
||||||
|
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
|
||||||
|
testEnvironment: 'node',
|
||||||
|
collectCoverage: true,
|
||||||
|
coverageReporters: ['json', 'html']
|
||||||
|
}
|
56
typescript/lunargame/api/knexfile.ts
Normal file
56
typescript/lunargame/api/knexfile.ts
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
import { iNode_env } from './src/modules/core/node_env'
|
||||||
|
import { Config } from 'knex'
|
||||||
|
import { resolve } from 'path'
|
||||||
|
|
||||||
|
// This is the name of the db file
|
||||||
|
const dbName = 'db.sqlite'
|
||||||
|
|
||||||
|
// Ive made those to prevent repetition
|
||||||
|
const dbFolder = resolve(__dirname, 'db')
|
||||||
|
const testFolder = resolve(__dirname, 'test')
|
||||||
|
|
||||||
|
// This is used in all configs
|
||||||
|
const commonConfig: Partial<Config> = {
|
||||||
|
migrations: {
|
||||||
|
directory: resolve(dbFolder, 'migrations'),
|
||||||
|
tableName: 'migrations'
|
||||||
|
},
|
||||||
|
useNullAsDefault: true
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is the confg we are going to esport
|
||||||
|
// Im making a separate variable instead of
|
||||||
|
// default exporting it because i want to
|
||||||
|
// also eport each prop by name
|
||||||
|
const config: Partial<Record<iNode_env, Config>> = {
|
||||||
|
development: {
|
||||||
|
client: 'sqlite3',
|
||||||
|
connection: {
|
||||||
|
filename: resolve(dbFolder, dbName)
|
||||||
|
},
|
||||||
|
...commonConfig,
|
||||||
|
seeds: {
|
||||||
|
directory: resolve(dbFolder, 'seeds')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
test: {
|
||||||
|
client: 'sqlite3',
|
||||||
|
connection: {
|
||||||
|
filename: resolve(testFolder, dbName)
|
||||||
|
},
|
||||||
|
...commonConfig,
|
||||||
|
seeds: {
|
||||||
|
directory: resolve(testFolder, 'seeds')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// These are exposed to knex
|
||||||
|
const { development, test } = config
|
||||||
|
|
||||||
|
// This is the export wich should be used in th eactua app
|
||||||
|
export default config
|
||||||
|
|
||||||
|
// For migartions to work
|
||||||
|
// If i dont include this knex will throw an error
|
||||||
|
export { development, test }
|
6
typescript/lunargame/api/nodemon.json
Normal file
6
typescript/lunargame/api/nodemon.json
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"watch": ["src"],
|
||||||
|
"ext": "ts",
|
||||||
|
"ignore": ["src/**/*.spec.ts"],
|
||||||
|
"exec": "ts-node ./src/index.ts"
|
||||||
|
}
|
7986
typescript/lunargame/api/package-lock.json
generated
Normal file
7986
typescript/lunargame/api/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
59
typescript/lunargame/api/package.json
Normal file
59
typescript/lunargame/api/package.json
Normal file
|
@ -0,0 +1,59 @@
|
||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"scripts": {
|
||||||
|
"start": "nodemon",
|
||||||
|
"reset-db": "knex migrate:rollback && knex migrate:latest && knex seed:run",
|
||||||
|
"reset-db:test": "(knex migrate:rollback --env test) && (knex migrate:latest --env test) && (knex seed:run --env test)",
|
||||||
|
"test": "cross-env NODE_ENV=test && jest",
|
||||||
|
"show": "gource -f --start-date \"2019-07-01 12:00\" --key --hide dirnames,filenames,bloom -s 0.3"
|
||||||
|
},
|
||||||
|
"main": "index.js",
|
||||||
|
"private": true,
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bcryptjs": "^2.4.2",
|
||||||
|
"@types/dotenv": "^6.1.1",
|
||||||
|
"@types/faker": "^4.1.5",
|
||||||
|
"@types/jest": "^24.0.17",
|
||||||
|
"@types/joi": "^14.3.3",
|
||||||
|
"@types/koa": "^2.0.49",
|
||||||
|
"@types/koa-bodyparser": "^4.3.0",
|
||||||
|
"@types/koa-router": "^7.0.42",
|
||||||
|
"@types/koa-session": "^5.10.1",
|
||||||
|
"@types/koa__cors": "^2.2.3",
|
||||||
|
"@types/node": "^12.0.10",
|
||||||
|
"@types/supertest": "^2.0.8",
|
||||||
|
"@types/uuid": "^3.4.5",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^1.13.0",
|
||||||
|
"@typescript-eslint/parser": "^1.13.0",
|
||||||
|
"cross-env": "^5.2.0",
|
||||||
|
"eslint": "^6.1.0",
|
||||||
|
"eslint-config-prettier": "^6.0.0",
|
||||||
|
"eslint-plugin-prettier": "^3.1.0",
|
||||||
|
"faker": "^4.1.0",
|
||||||
|
"jest": "^24.8.0",
|
||||||
|
"nodemon": "^1.19.1",
|
||||||
|
"prettier": "^1.18.2",
|
||||||
|
"sqlite3": "^4.0.9",
|
||||||
|
"ts-jest": "^24.0.2",
|
||||||
|
"ts-node": "^8.3.0",
|
||||||
|
"typescript": "^3.5.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@koa/cors": "^3.0.0",
|
||||||
|
"@sendgrid/mail": "^6.4.0",
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"dotenv": "^8.0.0",
|
||||||
|
"joi": "^14.3.1",
|
||||||
|
"joi-extract-type": "^15.0.0",
|
||||||
|
"knex": "^0.19.5",
|
||||||
|
"koa": "^2.7.0",
|
||||||
|
"koa-bodyparser": "^4.2.1",
|
||||||
|
"koa-router": "^7.4.0",
|
||||||
|
"koa-session": "^5.12.0",
|
||||||
|
"koa-session-knex-store": "^1.1.2",
|
||||||
|
"pg": "^7.11.0",
|
||||||
|
"supertest": "^4.0.2",
|
||||||
|
"uuid": "^3.3.2"
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { randomElement } from './randomElement'
|
||||||
|
|
||||||
|
describe('The randomElement function', () => {
|
||||||
|
test('should return the only element in an array of length 1', () => {
|
||||||
|
const element = 7
|
||||||
|
|
||||||
|
expect(randomElement([element])).toBe(element)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should throw an error when passing an empty array', () => {
|
||||||
|
expect(() => {
|
||||||
|
randomElement([])
|
||||||
|
}).toThrow()
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,13 @@
|
||||||
|
/**
|
||||||
|
* Returns a random element from an array
|
||||||
|
*
|
||||||
|
* @param arr The array to select the element from
|
||||||
|
* @throws Error if the array has length 0
|
||||||
|
*/
|
||||||
|
export const randomElement = <T>(arr: T[]): T => {
|
||||||
|
if (!arr.length) {
|
||||||
|
throw new Error('Cannot choose a random element from array of length 0')
|
||||||
|
}
|
||||||
|
|
||||||
|
return arr[Math.floor(arr.length * Math.random())]
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
export interface CountData {
|
||||||
|
count: string
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
import Joi from 'joi'
|
||||||
|
import { validate, validationField } from './validate'
|
||||||
|
import { Context } from 'koa'
|
||||||
|
import { fakeNext } from '../../../../test/utils/fakeNext'
|
||||||
|
|
||||||
|
describe('The validate middleware', () => {
|
||||||
|
const schema = Joi.object({
|
||||||
|
name: Joi.required()
|
||||||
|
})
|
||||||
|
|
||||||
|
const fields: validationField[] = ['body', 'params', 'query']
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
describe(`The request ${field} validator`, () => {
|
||||||
|
const middleware = validate(schema, field)
|
||||||
|
|
||||||
|
const getContext = (name?: number) => {
|
||||||
|
if (field === 'body') {
|
||||||
|
return {
|
||||||
|
request: {
|
||||||
|
body: {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} as Context
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
[field]: {
|
||||||
|
name
|
||||||
|
}
|
||||||
|
} as Context
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('should throw an error if the validation fails', () => {
|
||||||
|
// arrange
|
||||||
|
const context = getContext()
|
||||||
|
|
||||||
|
// act
|
||||||
|
const check = () => {
|
||||||
|
middleware(context, fakeNext())
|
||||||
|
}
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(check).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should call next if the validation passed', () => {
|
||||||
|
// arrange
|
||||||
|
const context = getContext(7)
|
||||||
|
|
||||||
|
const next = jest.fn(fakeNext())
|
||||||
|
|
||||||
|
// act
|
||||||
|
middleware(context, next)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(next).toBeCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { ObjectSchema } from 'joi'
|
||||||
|
import { Middleware } from 'koa'
|
||||||
|
import { HttpError } from '../../../modules/network/classes/HttpError'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The field wich the validate validator can use
|
||||||
|
*/
|
||||||
|
export type validationField = 'params' | 'body' | 'query'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middlware to validate a joi schema against a request
|
||||||
|
*
|
||||||
|
* @param schema The joi shcema to use for the validation
|
||||||
|
* @param field The field to validate the schema against
|
||||||
|
*
|
||||||
|
* @throws HttpError if the validation fails
|
||||||
|
*/
|
||||||
|
export const validate = (schema: ObjectSchema, field: validationField): Middleware => (
|
||||||
|
context,
|
||||||
|
next
|
||||||
|
) => {
|
||||||
|
const result = schema.validate(field === 'body' ? context.request.body : context[field], {
|
||||||
|
abortEarly: true
|
||||||
|
})
|
||||||
|
|
||||||
|
if (result.error !== null) {
|
||||||
|
throw new HttpError(422, result.error.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
return next()
|
||||||
|
}
|
7
typescript/lunargame/api/src/index.ts
Normal file
7
typescript/lunargame/api/src/index.ts
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
import { app } from './server'
|
||||||
|
|
||||||
|
const port = process.env.PORT
|
||||||
|
|
||||||
|
export const server = app.listen(Number(port), () => {
|
||||||
|
console.log(`Listening on port ${port}`)
|
||||||
|
})
|
4
typescript/lunargame/api/src/modules/auth/constants.ts
Normal file
4
typescript/lunargame/api/src/modules/auth/constants.ts
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
import { passwordEncryption } from './types/passwordEncryption'
|
||||||
|
|
||||||
|
// i made a separate constant to prevent duplication
|
||||||
|
export const defaultEncryptionMethod: passwordEncryption = 'bcrypt'
|
|
@ -0,0 +1,59 @@
|
||||||
|
import { checkPassword } from './checkPassword'
|
||||||
|
import { passwordEncryption } from '../types/passwordEncryption'
|
||||||
|
import { hash, genSalt } from 'bcryptjs'
|
||||||
|
|
||||||
|
describe('The checkPassword helper', () => {
|
||||||
|
const pass = 'this is a test password'
|
||||||
|
|
||||||
|
test("should throw an error if the encryption method doesn't exist", async () => {
|
||||||
|
// arrange
|
||||||
|
const check = checkPassword(pass, pass, '12212' as passwordEncryption)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
await expect(check).rejects.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("The 'plain' encryption", () => {
|
||||||
|
test('should return true if the password is correct', async () => {
|
||||||
|
// act
|
||||||
|
const check = await checkPassword(pass, pass, 'plain')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(check).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shoud return false if the password is wrong', async () => {
|
||||||
|
// act
|
||||||
|
const check = await checkPassword(pass, pass + 'something', 'plain')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(check).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("The 'bcrypt' encryption", () => {
|
||||||
|
let passwordHash: string
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const salt = await genSalt(3)
|
||||||
|
|
||||||
|
passwordHash = await hash(pass, salt)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return true if the password is correct', async () => {
|
||||||
|
// act
|
||||||
|
const check = await checkPassword(passwordHash, pass, 'bcrypt')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(check).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shoud return false if the password is wrong', async () => {
|
||||||
|
// act
|
||||||
|
const check = await checkPassword(passwordHash, pass + 'something', 'bcrypt')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(check).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { passwordEncryption } from '../types/passwordEncryption'
|
||||||
|
import { HttpError } from '../../network/classes/HttpError'
|
||||||
|
import { compare } from 'bcryptjs'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comparesa apssword with it's hash
|
||||||
|
*
|
||||||
|
* @param hash The hash of the password
|
||||||
|
* @param password The actual password
|
||||||
|
* @param encryption The encription of the password
|
||||||
|
*/
|
||||||
|
export const checkPassword = async (
|
||||||
|
hash: string,
|
||||||
|
password: string,
|
||||||
|
encryption: passwordEncryption = 'plain'
|
||||||
|
) => {
|
||||||
|
if (encryption === 'plain') {
|
||||||
|
return hash === password
|
||||||
|
} else if (encryption === 'bcrypt') {
|
||||||
|
return await compare(password, hash)
|
||||||
|
} else {
|
||||||
|
throw new HttpError(400, `Encription ${encryption} doesn't exist`)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { internet } from 'faker'
|
||||||
|
import { encryptPassword } from './encryptPassword'
|
||||||
|
import { compare } from 'bcryptjs'
|
||||||
|
|
||||||
|
describe('The encryptPassword helper', () => {
|
||||||
|
test("should return the same password if the method is 'plain'", async () => {
|
||||||
|
// arrange
|
||||||
|
const password = internet.password()
|
||||||
|
|
||||||
|
// act
|
||||||
|
const hash = await encryptPassword(password, 'plain')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(hash).toBe(password)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("should return a mactching hash if the method is 'bcrypt'", async () => {
|
||||||
|
// arrange
|
||||||
|
const password = internet.password()
|
||||||
|
const hash = await encryptPassword(password, 'bcrypt', 3)
|
||||||
|
|
||||||
|
// act
|
||||||
|
const match = await compare(password, hash)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(match).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { passwordEncryption } from '../types/passwordEncryption'
|
||||||
|
import { genSalt, hash } from 'bcryptjs'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encypts a string
|
||||||
|
*
|
||||||
|
* @param password The password to encrypt
|
||||||
|
* @param method The method to encrypt the password with
|
||||||
|
* @param rounds The salting rounds (for bcrypt only)
|
||||||
|
*/
|
||||||
|
export const encryptPassword = async (
|
||||||
|
password: string,
|
||||||
|
method: passwordEncryption,
|
||||||
|
rounds = 10
|
||||||
|
) => {
|
||||||
|
if (method === 'bcrypt') {
|
||||||
|
const salt = await genSalt(rounds)
|
||||||
|
const result = await hash(password, salt)
|
||||||
|
|
||||||
|
return result
|
||||||
|
} else {
|
||||||
|
return password
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { Context } from 'koa'
|
||||||
|
import { requireAnonymous } from './requireAnonymous'
|
||||||
|
import { fakeNext } from '../../../../test/utils/fakeNext'
|
||||||
|
|
||||||
|
describe('The requireAnonymous middleware', () => {
|
||||||
|
test('should throw an error if the user is logged in', () => {
|
||||||
|
// act
|
||||||
|
const fakeContext = ({
|
||||||
|
session: {
|
||||||
|
uid: 7
|
||||||
|
}
|
||||||
|
} as unknown) as Context
|
||||||
|
|
||||||
|
// arrange
|
||||||
|
const runMiddleware = () => requireAnonymous()(fakeContext, fakeNext())
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(runMiddleware).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
test("should call next if the user isn't logged in", () => {
|
||||||
|
// arrange
|
||||||
|
const fakeContext = {
|
||||||
|
session: {}
|
||||||
|
} as Context
|
||||||
|
|
||||||
|
const next = jest.fn(fakeNext())
|
||||||
|
|
||||||
|
// act
|
||||||
|
requireAnonymous()(fakeContext, next)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(next).toBeCalled()
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Middleware } from 'koa'
|
||||||
|
import { HttpError } from '../../network/classes/HttpError'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middleware wich throws an error if the user is logged in
|
||||||
|
*/
|
||||||
|
export const requireAnonymous = (): Middleware => (context, next) => {
|
||||||
|
if (context.session.uid === undefined) {
|
||||||
|
return next()
|
||||||
|
} else {
|
||||||
|
throw new HttpError(401)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { requireAuthenticated } from './requireAuthenticated'
|
||||||
|
import { Context } from 'koa'
|
||||||
|
import { fakeNext } from '../../../../test/utils/fakeNext'
|
||||||
|
|
||||||
|
describe('The requireAuthenticated middleware', () => {
|
||||||
|
test("should throw an error if the user isn't logged in", () => {
|
||||||
|
// arrange
|
||||||
|
const fakeContext = {
|
||||||
|
session: {}
|
||||||
|
} as Context
|
||||||
|
|
||||||
|
// arrange
|
||||||
|
const runMiddleware = () => requireAuthenticated()(fakeContext, fakeNext())
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(runMiddleware).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should call next if the user is logged in', () => {
|
||||||
|
// arrange
|
||||||
|
const fakeContext = ({
|
||||||
|
session: {
|
||||||
|
uid: Math.random()
|
||||||
|
}
|
||||||
|
} as unknown) as Context
|
||||||
|
|
||||||
|
const next = jest.fn(fakeNext())
|
||||||
|
|
||||||
|
// act
|
||||||
|
requireAuthenticated()(fakeContext, next)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(next).toBeCalled()
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Middleware } from 'koa'
|
||||||
|
import { HttpError } from '../../network/classes/HttpError'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middlware wich throws an error if the user isn't logged in
|
||||||
|
*/
|
||||||
|
export const requireAuthenticated = (): Middleware => (context, next) => {
|
||||||
|
if (context.session.uid !== undefined) {
|
||||||
|
return next()
|
||||||
|
} else {
|
||||||
|
throw new HttpError(401)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||||
|
import { name, random, internet } from 'faker'
|
||||||
|
import { createAccount } from './createAccount'
|
||||||
|
import { connection } from '../../db/connection'
|
||||||
|
import { SignupBody } from '../schemas/SignupBody'
|
||||||
|
|
||||||
|
describe('The createAccount query', () => {
|
||||||
|
test('should return the id of the account and add it to the db', async () => {
|
||||||
|
const email = internet.email()
|
||||||
|
const username = name.firstName()
|
||||||
|
const password = random.alphaNumeric(10)
|
||||||
|
|
||||||
|
const result = await createAccount({
|
||||||
|
email,
|
||||||
|
name: username,
|
||||||
|
password,
|
||||||
|
passwordEncryption: 'plain'
|
||||||
|
})
|
||||||
|
|
||||||
|
const account = await connection
|
||||||
|
.from('account')
|
||||||
|
.select<Required<SignupBody>>(['email', 'name', 'password'])
|
||||||
|
.where({
|
||||||
|
id: result
|
||||||
|
})
|
||||||
|
.first()
|
||||||
|
|
||||||
|
expect(account.name).toBe(username)
|
||||||
|
expect(account.email).toBe(email)
|
||||||
|
expect(account.password).toBe(password)
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,15 @@
|
||||||
|
import { connection } from '../../db/connection'
|
||||||
|
import { DbAccount } from '../types/Account'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves a new user into the db
|
||||||
|
*
|
||||||
|
* @param user The user object to insert
|
||||||
|
*/
|
||||||
|
export const createAccount = async (user: DbAccount): Promise<number> => {
|
||||||
|
const result = await connection.from('account').insert({
|
||||||
|
...user
|
||||||
|
})
|
||||||
|
|
||||||
|
return result[0]
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { getPasswordByEmail } from './getPasswordByEmail'
|
||||||
|
import { mockAccounts } from '../../../../test/seeds/01_create-account'
|
||||||
|
import { connection } from '../../db/connection'
|
||||||
|
|
||||||
|
describe('The getPasswordByName query', () => {
|
||||||
|
test('should return the correct password & encryption for a mock account', async () => {
|
||||||
|
await connection.seed.run()
|
||||||
|
|
||||||
|
for (const account of mockAccounts) {
|
||||||
|
const result = await getPasswordByEmail(account.email)
|
||||||
|
|
||||||
|
expect(result.password).toBe(account.password)
|
||||||
|
expect(result.passwordEncryption).toBe(account.passwordEncryption)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,26 @@
|
||||||
|
import { connection } from '../../db/connection'
|
||||||
|
import { passwordEncryption } from '../types/passwordEncryption'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The result of the getPasswordByName query
|
||||||
|
*/
|
||||||
|
export interface PasswordByEmailResult {
|
||||||
|
password: string
|
||||||
|
passwordEncryption: passwordEncryption
|
||||||
|
id: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the password, passwordEncryption and id of an account from it's email
|
||||||
|
*
|
||||||
|
* @param email The email of the account
|
||||||
|
*/
|
||||||
|
export const getPasswordByEmail = (email: string): Promise<PasswordByEmailResult> => {
|
||||||
|
return connection
|
||||||
|
.from('account')
|
||||||
|
.select('password', 'passwordEncryption', 'id')
|
||||||
|
.where({
|
||||||
|
email
|
||||||
|
})
|
||||||
|
.first()
|
||||||
|
}
|
|
@ -0,0 +1,112 @@
|
||||||
|
import supertest from 'supertest'
|
||||||
|
import { app } from '../../../server'
|
||||||
|
import { loggedInAgent } from '../../../../test/utils/loggedInAgent'
|
||||||
|
import { mockAccounts } from '../../../../test/seeds/01_create-account'
|
||||||
|
import { random, internet } from 'faker'
|
||||||
|
import { defaultEncryptionMethod } from '../constants'
|
||||||
|
|
||||||
|
describe('The /auth route', () => {
|
||||||
|
// used to make requests
|
||||||
|
const request = supertest(app.callback())
|
||||||
|
|
||||||
|
describe(`The GET method on the / subroute`, () => {
|
||||||
|
test('should return undefined if the user was not logged in', async () => {
|
||||||
|
// act
|
||||||
|
const res = await request.get('/auth')
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(res.body.uid).toBe(undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should return the uid form the session while logged in', async () => {
|
||||||
|
// arrange
|
||||||
|
const [agent, cookie] = await loggedInAgent(supertest.agent(app.callback()), {
|
||||||
|
email: mockAccounts[0].email,
|
||||||
|
password: mockAccounts[0].password
|
||||||
|
})
|
||||||
|
|
||||||
|
// act
|
||||||
|
const response = await agent.get('/auth').set('cookie', cookie)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(response.body.uid).not.toBe(undefined)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe(`The POST method on the /login subroute`, () => {
|
||||||
|
test('should throw an error if the user is already logged in', async () => {
|
||||||
|
// arrange
|
||||||
|
const [agent, cookie] = await loggedInAgent(supertest.agent(app.callback()), {
|
||||||
|
email: mockAccounts[0].email,
|
||||||
|
password: mockAccounts[0].password
|
||||||
|
})
|
||||||
|
|
||||||
|
// act
|
||||||
|
const reponse = await agent.post('/auth/login').set('cookie', cookie)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(reponse.status).toBe(401)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should throw an error if the password is wrong', async () => {
|
||||||
|
// act
|
||||||
|
const response = await request.post('/auth/login').send({
|
||||||
|
email: mockAccounts[0].email,
|
||||||
|
password: mockAccounts[0].password + 'something'
|
||||||
|
})
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(response.status).toBe(422)
|
||||||
|
expect((response.body.message as string).startsWith('child')).toBe(false) // Not JOI
|
||||||
|
})
|
||||||
|
|
||||||
|
test("should throw an error if the user doesn't exist", async () => {
|
||||||
|
// act
|
||||||
|
const reponse = await request.post('/auth/login').send({
|
||||||
|
email: 'idk' + mockAccounts[0].email,
|
||||||
|
password: mockAccounts[0].password
|
||||||
|
})
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(reponse.status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should work when the password is correct', async () => {
|
||||||
|
for (const account of mockAccounts) {
|
||||||
|
// act
|
||||||
|
const response = await request.post('/auth/login').send({
|
||||||
|
email: account.email,
|
||||||
|
password: account.password
|
||||||
|
})
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(response.body.uid).not.toBe(undefined)
|
||||||
|
expect(response.body.encryption).toBe(account.passwordEncryption)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('The POST method on the /signup subroute', () => {
|
||||||
|
test('should work if all fields are correct', async () => {
|
||||||
|
// arrange
|
||||||
|
const name = internet.userName()
|
||||||
|
const password = random.alphaNumeric(5)
|
||||||
|
const email = internet.email()
|
||||||
|
|
||||||
|
const user = {
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
password
|
||||||
|
}
|
||||||
|
|
||||||
|
// act
|
||||||
|
const response = await request.post('/auth/signup').send(user)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(response.body.uid).not.toBe(undefined)
|
||||||
|
expect(response.body.encryption).toBe(defaultEncryptionMethod)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,82 @@
|
||||||
|
import Router from 'koa-router'
|
||||||
|
import { validate } from '../../../common/validation/middleware/validate'
|
||||||
|
import { getPasswordByEmail } from '../queries/getPasswordByEmail'
|
||||||
|
import { HttpError } from '../../network/classes/HttpError'
|
||||||
|
import { checkPassword } from '../helpers/checkPassword'
|
||||||
|
import { SignupBodySchema } from '../schemas/SignupBody'
|
||||||
|
import { encryptPassword } from '../helpers/encryptPassword'
|
||||||
|
import { createAccount } from '../queries/createAccount'
|
||||||
|
import { defaultEncryptionMethod } from '../constants'
|
||||||
|
import { LoginBodySchema } from '../schemas/LoginBody'
|
||||||
|
import { requireAnonymous } from '../middleware/requireAnonymous'
|
||||||
|
|
||||||
|
const router = new Router()
|
||||||
|
|
||||||
|
router.get('/', (context, next) => {
|
||||||
|
context.body = {
|
||||||
|
uid: context.session.uid
|
||||||
|
}
|
||||||
|
|
||||||
|
return next()
|
||||||
|
})
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/login',
|
||||||
|
requireAnonymous(),
|
||||||
|
validate(LoginBodySchema, 'body'),
|
||||||
|
async (context, next) => {
|
||||||
|
const { email, password } = context.request.body
|
||||||
|
const passwordData = await getPasswordByEmail(email)
|
||||||
|
|
||||||
|
// in case the user doesnt exist
|
||||||
|
if (!passwordData) {
|
||||||
|
throw new HttpError(404)
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = await checkPassword(
|
||||||
|
passwordData.password,
|
||||||
|
password,
|
||||||
|
passwordData.passwordEncryption
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new HttpError(422, 'wrong password')
|
||||||
|
}
|
||||||
|
|
||||||
|
context.session.uid = passwordData.id
|
||||||
|
context.body = {
|
||||||
|
encryption: passwordData.passwordEncryption,
|
||||||
|
uid: passwordData.id
|
||||||
|
}
|
||||||
|
|
||||||
|
return next()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/signup',
|
||||||
|
requireAnonymous(),
|
||||||
|
validate(SignupBodySchema, 'body'),
|
||||||
|
async (context, next) => {
|
||||||
|
const { email, name, password } = context.request.body
|
||||||
|
|
||||||
|
// encript the password (bcrypt by default)
|
||||||
|
const encryptedPassword = await encryptPassword(password, defaultEncryptionMethod, 10)
|
||||||
|
|
||||||
|
const uid = await createAccount({
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
password: encryptedPassword,
|
||||||
|
passwordEncryption: defaultEncryptionMethod
|
||||||
|
})
|
||||||
|
|
||||||
|
context.body = {
|
||||||
|
uid,
|
||||||
|
encryption: defaultEncryptionMethod
|
||||||
|
}
|
||||||
|
|
||||||
|
return next()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
export default router
|
|
@ -0,0 +1,9 @@
|
||||||
|
import Joi from '@hapi/joi'
|
||||||
|
import { email, password } from './authFields'
|
||||||
|
|
||||||
|
export const LoginBodySchema = Joi.object({
|
||||||
|
email,
|
||||||
|
password
|
||||||
|
}).required()
|
||||||
|
|
||||||
|
export type LoginBody = Joi.extractType<typeof LoginBodySchema>
|
|
@ -0,0 +1,10 @@
|
||||||
|
import Joi from '@hapi/joi'
|
||||||
|
import { email, name, password } from './authFields'
|
||||||
|
|
||||||
|
export const SignupBodySchema = Joi.object({
|
||||||
|
name,
|
||||||
|
password,
|
||||||
|
email
|
||||||
|
}).required()
|
||||||
|
|
||||||
|
export type SignupBody = Joi.extractType<typeof SignupBodySchema>
|
|
@ -0,0 +1,18 @@
|
||||||
|
import Joi from 'joi'
|
||||||
|
|
||||||
|
export const name = Joi.string()
|
||||||
|
.min(3)
|
||||||
|
.max(30)
|
||||||
|
.required()
|
||||||
|
|
||||||
|
export const email = Joi.string()
|
||||||
|
.email()
|
||||||
|
.min(3)
|
||||||
|
.max(30)
|
||||||
|
.required()
|
||||||
|
|
||||||
|
export const password = Joi.string()
|
||||||
|
.min(3)
|
||||||
|
.max(20)
|
||||||
|
.alphanum()
|
||||||
|
.required()
|
32
typescript/lunargame/api/src/modules/auth/types/Account.ts
Normal file
32
typescript/lunargame/api/src/modules/auth/types/Account.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import { passwordEncryption } from './passwordEncryption'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data about an account wich needs to be inserted into the db
|
||||||
|
*/
|
||||||
|
export interface DbAccount {
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
password: string
|
||||||
|
passwordEncryption: passwordEncryption
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data about an account wich actually gets stored into the db
|
||||||
|
*/
|
||||||
|
export interface FullDbAccount extends DbAccount {
|
||||||
|
id: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data everyone can get about an account
|
||||||
|
*/
|
||||||
|
export interface AccountPublicData {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The data only the owner of the account has acces to
|
||||||
|
*/
|
||||||
|
export interface AccountPrivateData extends AccountPublicData {
|
||||||
|
email: string
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
import { passwordEncryption } from './passwordEncryption'
|
||||||
|
|
||||||
|
export interface LoginReponseBody {
|
||||||
|
uid: number
|
||||||
|
encryption: passwordEncryption
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
/**
|
||||||
|
* All modes a password can be encrypted in
|
||||||
|
*/
|
||||||
|
export type passwordEncryption = 'plain' | 'bcrypt'
|
8
typescript/lunargame/api/src/modules/core/node_env.ts
Normal file
8
typescript/lunargame/api/src/modules/core/node_env.ts
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
// this is the type wich the node_env constant can take
|
||||||
|
export type iNode_env = 'development' | 'production' | 'test'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type safe version of process.env.NODE_ENV
|
||||||
|
*/
|
||||||
|
export const node_env: iNode_env =
|
||||||
|
(process.env.NODE_ENV as iNode_env) || 'development'
|
8
typescript/lunargame/api/src/modules/core/router.ts
Normal file
8
typescript/lunargame/api/src/modules/core/router.ts
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
import Router from 'koa-router'
|
||||||
|
import AuthRouter from '../auth/routes/authRoute'
|
||||||
|
|
||||||
|
const router = new Router()
|
||||||
|
|
||||||
|
router.use('/auth', AuthRouter.middleware())
|
||||||
|
|
||||||
|
export { router }
|
6
typescript/lunargame/api/src/modules/db/connection.ts
Normal file
6
typescript/lunargame/api/src/modules/db/connection.ts
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
import config from '../../../knexfile'
|
||||||
|
import knex, { Config } from 'knex'
|
||||||
|
import { node_env } from '../core/node_env'
|
||||||
|
|
||||||
|
// TODO: remove the as Config after finshnig the knexfile
|
||||||
|
export const connection = knex(config[node_env] as Config)
|
|
@ -0,0 +1,29 @@
|
||||||
|
import { HttpError, HTTP_REASONS, HttpStatus, httpSymbol } from './HttpError'
|
||||||
|
|
||||||
|
describe('The HttpError class', () => {
|
||||||
|
test('should allow passing a custom message', () => {
|
||||||
|
const status = Math.random()
|
||||||
|
const reason = 'testing'
|
||||||
|
|
||||||
|
const error = new HttpError(status, reason)
|
||||||
|
|
||||||
|
expect(error.toString()).toBe(`HttpError: ${status} - ${reason}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should use the default reason for the status when passing no second arg', () => {
|
||||||
|
// ts will always consider it a string
|
||||||
|
for (let untypedStatus in HTTP_REASONS) {
|
||||||
|
// this forces ts to belive its an actual status
|
||||||
|
const status = (untypedStatus as unknown) as HttpStatus
|
||||||
|
const error = new HttpError(status)
|
||||||
|
|
||||||
|
expect(error.reason).toBe(HTTP_REASONS[status])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should always have the http error symbol set to true', () => {
|
||||||
|
const error = new HttpError()
|
||||||
|
|
||||||
|
expect(error[httpSymbol]).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
|
@ -0,0 +1,50 @@
|
||||||
|
/**
|
||||||
|
* Made by Entioni
|
||||||
|
*/
|
||||||
|
|
||||||
|
export enum HttpStatus {
|
||||||
|
BadRequest = 400,
|
||||||
|
Unauthorized = 401,
|
||||||
|
PaymentRequired = 402,
|
||||||
|
Forbidden = 403,
|
||||||
|
NotFound = 404,
|
||||||
|
Conflict = 409,
|
||||||
|
Gone = 410,
|
||||||
|
PayloadTooLarge = 413,
|
||||||
|
UnprocessableEntity = 422,
|
||||||
|
TooManyRequests = 429,
|
||||||
|
InternalServerError = 500
|
||||||
|
}
|
||||||
|
|
||||||
|
export const HTTP_REASONS: Record<HttpStatus, string> = {
|
||||||
|
'400': 'Bad request',
|
||||||
|
'401': 'Unauthorized',
|
||||||
|
'402': 'Payment required',
|
||||||
|
'403': 'Forbidden',
|
||||||
|
'404': 'Not found',
|
||||||
|
'409': 'Conflict',
|
||||||
|
'410': 'Gone',
|
||||||
|
'413': 'Payload too large',
|
||||||
|
'422': 'Validation error',
|
||||||
|
'429': 'Too many requests',
|
||||||
|
'500': 'Internal server error'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const httpSymbol = Symbol('http')
|
||||||
|
|
||||||
|
export class HttpError extends Error {
|
||||||
|
// for some reason instanceof stopped working at some point
|
||||||
|
public [httpSymbol] = true
|
||||||
|
|
||||||
|
public constructor(
|
||||||
|
public status: HttpStatus = HttpStatus.InternalServerError,
|
||||||
|
public reason?: string
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
this.reason = reason || HTTP_REASONS[status]
|
||||||
|
}
|
||||||
|
|
||||||
|
public toString() {
|
||||||
|
return `HttpError: ${this.status} - ${this.reason}`
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { Middleware } from 'koa'
|
||||||
|
import { httpSymbol } from '../../network/classes/HttpError'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Midlware for error handling
|
||||||
|
*
|
||||||
|
* Not testing it because its made by Enitoni
|
||||||
|
*/
|
||||||
|
export const handleError = (): Middleware => async (context, next) => {
|
||||||
|
try {
|
||||||
|
await next()
|
||||||
|
} catch (error) {
|
||||||
|
if (error[httpSymbol]) {
|
||||||
|
context.status = error.status
|
||||||
|
context.body = {
|
||||||
|
message: error.reason
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(error)
|
||||||
|
|
||||||
|
context.status = 500
|
||||||
|
context.body = 'Internal server error'
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
import Koa, { Middleware } from 'koa'
|
||||||
|
import session from 'koa-session'
|
||||||
|
import knexSessionStore from 'koa-session-knex-store'
|
||||||
|
import { connection } from '../../db/connection'
|
||||||
|
|
||||||
|
// The store sessions are saved to
|
||||||
|
export const sessionStore = knexSessionStore(connection, {
|
||||||
|
createtable: true
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middleware factory for handling sessions
|
||||||
|
*
|
||||||
|
* @param app The app to handle sessions for
|
||||||
|
*/
|
||||||
|
export const handleSessions = (app: Koa): Middleware =>
|
||||||
|
session(
|
||||||
|
{
|
||||||
|
maxAge: 1000 * 60 * 60 * (24 * 7),
|
||||||
|
overwrite: true,
|
||||||
|
signed: true,
|
||||||
|
rolling: true,
|
||||||
|
renew: false,
|
||||||
|
store: sessionStore,
|
||||||
|
domain: 'localhost'
|
||||||
|
},
|
||||||
|
app
|
||||||
|
)
|
26
typescript/lunargame/api/src/server.ts
Normal file
26
typescript/lunargame/api/src/server.ts
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
import Koa from 'koa'
|
||||||
|
import cors from '@koa/cors'
|
||||||
|
import parser from 'koa-bodyparser'
|
||||||
|
|
||||||
|
import { config } from 'dotenv'
|
||||||
|
import { handleError } from './modules/network/middleware/errorHandler'
|
||||||
|
import { handleSessions } from './modules/network/middleware/handleSessions'
|
||||||
|
import { router } from './modules/core/router'
|
||||||
|
|
||||||
|
config()
|
||||||
|
|
||||||
|
const app = new Koa()
|
||||||
|
|
||||||
|
app.keys = [process.env.secret || 'secret']
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
cors({
|
||||||
|
credentials: true
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.use(handleError())
|
||||||
|
.use(parser())
|
||||||
|
.use(handleSessions(app))
|
||||||
|
.use(router.middleware())
|
||||||
|
|
||||||
|
export { app }
|
21
typescript/lunargame/api/test/seeds/01_create-account.ts
Normal file
21
typescript/lunargame/api/test/seeds/01_create-account.ts
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
import * as Knex from 'knex'
|
||||||
|
import { DbAccount } from '../../src/modules/auth/types/Account'
|
||||||
|
|
||||||
|
const tableName = 'account'
|
||||||
|
|
||||||
|
export const mockAccounts: DbAccount[] = [
|
||||||
|
{
|
||||||
|
name: 'Adriel',
|
||||||
|
email: 'rafaeladriel11@gmail.com',
|
||||||
|
password: '1234',
|
||||||
|
passwordEncryption: 'plain'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
export async function seed(knex: Knex): Promise<any> {
|
||||||
|
return knex(tableName)
|
||||||
|
.del()
|
||||||
|
.then(() => {
|
||||||
|
return knex(tableName).insert(mockAccounts)
|
||||||
|
})
|
||||||
|
}
|
4
typescript/lunargame/api/test/utils/fakeNext.ts
Normal file
4
typescript/lunargame/api/test/utils/fakeNext.ts
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
/**
|
||||||
|
* Factory for a quick mock of the next function required to test middlewares
|
||||||
|
*/
|
||||||
|
export const fakeNext = () => async () => {}
|
27
typescript/lunargame/api/test/utils/loggedInAgent.ts
Normal file
27
typescript/lunargame/api/test/utils/loggedInAgent.ts
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
import supertest from 'supertest'
|
||||||
|
import 'joi-extract-type'
|
||||||
|
import { LoginBody } from '../../src/modules/auth/schemas/LoginBody'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to get a supertest agent wich is logged in
|
||||||
|
*
|
||||||
|
* @param agent The agent to make the request with
|
||||||
|
* @param uid The uid to use to login
|
||||||
|
*/
|
||||||
|
export const loggedInAgent = async (
|
||||||
|
agent: supertest.SuperTest<supertest.Test>,
|
||||||
|
{ email, password }: LoginBody
|
||||||
|
) => {
|
||||||
|
const response = await agent.post('/auth/login').send({
|
||||||
|
email,
|
||||||
|
password
|
||||||
|
})
|
||||||
|
|
||||||
|
// the cookie to send back
|
||||||
|
// needs to be set manually due to a bug with jest
|
||||||
|
const cookie = response.header['set-cookie']
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
return [agent, cookie]
|
||||||
|
}
|
13
typescript/lunargame/api/tsconfig.json
Normal file
13
typescript/lunargame/api/tsconfig.json
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"noImplicitAny": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"lib": ["es2015", "dom", "dom.iterable", "esnext"],
|
||||||
|
"target": "esnext"
|
||||||
|
},
|
||||||
|
"include": ["src", "test"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
Loading…
Reference in a new issue