UsersModule moved to old repos

This commit is contained in:
Luis Fernando Molina committed 2020-11-20 18:53:33 +01:00
1 parent b291894227
commit 121af47510
65 files changed

No files matched your search

@@ -0,0 +1,14 @@
# Ignore files to be uploaded to the image
.env
.env.dev
.env.prod
.git
.gitignore
Dockerfile
Dockerfile.prod
README.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
/coverage
/.nyc_output
+13
View File
@@ -0,0 +1,13 @@
NODE_ENV=production
PORT=4000
MONGO_URL=mongodb://mongo/users
GATEWAY_ENDPOINT=http://master-app-api:4100/graphql
USERS_API_PRESHARED=users_key
GENERATE_SOURCEMAP=true
ERROR_LOG=true
INFO_LOG=true
@@ -0,0 +1,6 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
.env
.env.dev
/node_modules
/coverage
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at feedback at advancedalgos dot org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,45 @@
# Contributing
We are thrilled you are interested in contributing to this repository. Your help may be essential to the project's success and we want you in!
Advanced Algos LTD is a startup, currently at a very early stage. Although this repository is not open source software yet, we do welcome contributions from the community.
Contributions are deemed _voluntary work_. There might be incentives in place for certain kinds of contributions. Contact us for more information in this regards.
In any case, contributors agree to provide an express grant of patent rights for their contributions. Submitting Pull Requests to this repository represents an express agreement with the terms of our Balanced Contributor Intellectual Property Agreement. This agreement is a direct implementation of GitHub's [Balanced Employee Intellectual Property Agreement 1.0.1](https://github.com/github/balanced-employee-ip-agreement/blob/master/Balanced_Employee_IP_Agreement.md).
# Balanced Contributor Intellectual Property Agreement 1.0.1
This BALANCED CONTRIBUTOR INTELLECTUAL PROPERTY AGREEMENT is between person or team submitting Pull Requests to this repository and Advanced Algos LTD ("Company").
**What is this?** This is the Company's Intellectual Property Agreement ("Agreement"). If you've worked in the technology space before, there's a good chance that you've run across one or more of these in the past. This document is the official, entire and exclusive agreement on what intellectual property ("IP") is yours, and what belongs to the Company.
**Why is this?** The Company needs to be clear on what IP it owns and has rights to. Its customers, contributors, and investors depend on the Company having the legal rights to the products and services it is providing so that the Company can continue operating and doing business.
The Company also believes that it's important to be clear on what it doesn't own. The Company doesn't want you looking over your shoulder every time you work on something personal or worrying that the Company will someday seize your open source non-lethal mousetrap simulation software. In other words, the Company isn't interested in appropriating your personal projects.
**Read this.** Please read this document and be sure you understand it before you submit any Pull Requests. Due to legal risk and corporate obligations, the Company cannot, by and large, negotiate its terms. If you feel you have a particular circumstance that keeps you from signing, please let the Company's legal department ("Legal") know. And, of course, you're always free and encouraged to get your own legal counsel to explain anything you're not clear on.
Cool? Then, by submitting your first Pull Request, and as a condition of your contribution, you agree to the following:
1. **What the Company owns.** The Company owns any IP ("Company IP") that you create, or help create _as its contributor_, but only if it meets one or more of these additional conditions: The IP was (i) related to an existing or prospective Company product or service at the time you developed, invented, or created it, (ii) developed for use by the Company, or (iii) developed or promoted with existing Company IP or with the Company's endorsement. You hereby grant and assign, and will grant and assign, to the Company all rights and interests in all Company IP.
"Company IP" includes concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, and works of authorship.
2. **What the Company doesn't own.** If you create IP that doesn't fit into one of the categories listed above, the Company doesn't own it. In other words, the Company doesn't own concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, or works of authorship that you develop, invent, or create that do not meet any of the conditions in Section 1.
3. **Contribution of your IP to Company projects.** If you include your own IP – such as IP you created prior to working for the Company – into a Company product or service, it's still yours, of course, but you grant the Company a non-exclusive, irrevocable, fully paid-up, royalty-free, perpetual, sublicensable, transferable, worldwide license to use it without restriction in any way or implementation, in modified form, or as is, by itself, or incorporated into another product or service ("License"). If you include your name in any project over which the Company would have rights under this Agreement, such as in a copyright notice or a comment in code or documentation, then the License covers the rights associated with that use of your name as well.
4. **Your contributions to non-Company projects.** The Company recognizes that you may be engaged in work that requires you to submit IP to entities other than the Company, such as open source projects used by the Company. Please make sure that Legal is aware of what you're working on so that Legal can help with any licensing issues. If any project asks you to sign a contribution agreement, you should check with Legal before doing so. These agreements may be legally binding on the Company and so should be run through Legal first.
5. **Voluntary Works** All Company IP that you are involved with or create as part of your work for the Company is voluntary work which does not require compensation. There might be incentives in place for certain kinds of contributions. Feel free to contact the Company to learn more.
6. **No conflicts.** You agree that you don't have any outstanding agreements or obligations that conflict with those in this Agreement, and that you won't enter into conflicting agreements in the future.
7. **IP protection.** The Company might someday need to show the work that went into the development of IP that it uses or has used, or to make government filings to establish that it owns the IP or has rights over it. To help in those situations, you agree not to destroy any records you maintain relating to the development of any Company IP or IP under License (together, "All IP"), and, if the Company asks, to provide those records to the Company. You agree to help the Company secure and defend its rights in All IP. For your help the Company will compensate you at a reasonable rate. If the Company is unable to secure your help, you authorize the Company to act on your behalf (as your agent and attorney-in-fact) in securing all rights related to All IP.
8. **Confidentiality.** As an contributor or contractor of the Company, you will have access to sensitive confidential information that is important to the Company's business. You are responsible for keeping this information confidential, including after you end your work for the Company.
"Confidential Information" includes non-public technical details about our products or services, financial information, business strategies and forecasts, customer data, or any other information, data or know-how that is valuable to the Company because it is not publicly known.
The Company's Confidential Information is sensitive and we expect that you'll treat it as such. You agree to only use the Company's Confidential Information for the purpose of performing your contribution and for the benefit of the Company. You will do your best to keep Confidential Information secret. If you are not sure if something is Confidential Information, you should assume that it is, until you can confirm otherwise.
+19
View File
@@ -0,0 +1,19 @@
FROM mhart/alpine-node:12
# Directory where the service will be installed
ARG API_DIR=/usr/src/users-api
# Prepare required directories
RUN mkdir -p ${API_DIR}
# Use app directory as current workdir
WORKDIR ${API_DIR}
# Copy package.json to workdir
COPY . ${API_DIR}/
# Install dependencies
RUN npm install --production
# Expose Port
EXPOSE $PORT
@@ -0,0 +1,21 @@
FROM mhart/alpine-node:8
ENV PORT=4000
RUN mkdir -p /var/www/app && \
mkdir -p /var/www/app/node_modules
# Use app directory as current workdir
WORKDIR /var/www/app
ENV PATH /var/www/app/node_modules/.bin:$PATH
# Copy package.json to workdir
COPY package.json /var/www/app/package.json
# Install dependencies
RUN npm install
# Copy application code
COPY . /var/www/app
# Expose Port
EXPOSE $PORT
+201
View 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.
@@ -0,0 +1,24 @@
version: '3'
services:
node:
image: aausersapi-dev:v1
build:
context: .
dockerfile: ./Dockerfile.prod
env_file: ./.env
container_name: aausersapi
tty: true
stdin_open: true
volumes:
- ./:/var/www/app
- /var/www/app/node_modules
working_dir: /var/www/app
restart: always
command: npm start
expose:
- 4000
network_mode: webproxy
networks:
default:
external:
name: webproxy
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
{
"name": "@superalgos/users-api",
"version": "0.1.0",
"description": "Superalgos Users backend API",
"author": "Superalgos, ltd.",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/Superalgos/UsersModule.git"
},
"main": "src/index.js",
"scripts": {
"start": "nodemon --exec babel-node --presets env,stage-2 src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.18.10"
},
"dependencies": {
"cors": "^2.8.4",
"dotenv": "^6.0.0",
"express": "^4.16.3",
"express-graphql": "^0.6.12",
"express-jwt": "^5.3.1",
"graphql": "^14.0.0",
"jsonwebtoken": "^8.3.0",
"jwks-rsa": "^1.3.0",
"lodash": "^4.17.10",
"mongoose": "^5.2.12",
"winston": "^3.1.0"
}
}
@@ -0,0 +1,16 @@
/*
Global in-memory Sessions
Here, we are going to store some information associated to the logged in user, after it was
succesfully authenticated. This will prevent cheating, since we will use the in-Session
user-id for any transaction belonging to the user instead of whatever user id it provides
from the client app.
The key to access the in-Session information will allways be the authenticatioin token received
at the authentication transaction. This token should always come at the header of each
transactional functionality supported by this server module.
*/
global.Sessions = new Map();
@@ -0,0 +1,26 @@
const jwt = require('express-jwt')
const jwksRsa = require('jwks-rsa')
// Authentication middleware. When used, the
// if the access token exists, it be verified against
// the Auth0 JSON Web Key Set
const checkJwt = jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the signing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
}),
// Validate the audience and the issuer.
credentialsRequired: false,
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: [`RS256`]
})
module.exports = checkJwt
@@ -0,0 +1,81 @@
const MODULE_NAME = 'token-decoder'
/*
JSON Web Token (JWT) is a compact, URL-safe means of representing
claims to be transferred between two parties. The claims in a JWT
are encoded as a JSON object that is used as the payload of a JSON
Web Signature (JWS) structure or as the plaintext of a JSON Web
Encryption (JWE) structure, enabling the claims to be digitally
signed or integrity protected with a Message Authentication Code
(MAC) and/or encrypted.
*/
const JSONWebToken = require('jsonwebtoken') // A library to deal with JSON Web Tokens.
const webTokenLibrary = require('jwks-rsa') // A library to retrieve RSA signing keys from a JWKS (JSON Web Key Set) endpoint.
const decoder = webTokenLibrary({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
})
function decodeToken (token, callBackFunction) {
try {
if (process.env.INFO_LOG === true) { console.log('[INFO] ' + MODULE_NAME + ' -> decodeToken -> Entering function.') }
const decoded = JSONWebToken.decode(token, { complete: true })
const header = decoded.header
const payload = decoded.payload
if (
header === null ||
header.kid === null ||
payload === null
) {
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> Invalid Token. ') }
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> token = ' + token) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE)
return
}
decoder.getSigningKey(header.kid, onKeyReady)
function onKeyReady (err, key) {
if (process.env.INFO_LOG === true) { console.log('[INFO] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> Entering function.') }
if (err) {
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> Error getting the key. ') }
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> key = ' + key) }
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> err = ' + err) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE)
return
}
JSONWebToken.verify(
token,
key.publicKey,
{ algorithms: ['RS256'] },
onVerified)
function onVerified (err, decoded) {
if (process.env.INFO_LOG === true) { console.log('[INFO] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> onVerified -> Entering function.') }
if (err) {
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> onVerified -> Error verifying. ') }
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> onVerified -> decoded = ' + decoded) }
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> onKeyReady -> onVerified -> err = ' + err) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE)
return
}
callBackFunction(global.DEFAULT_OK_RESPONSE, decoded)
}
}
} catch (err) {
if (process.env.ERROR_LOG === true) { console.log('[ERROR] ' + MODULE_NAME + ' -> decodeToken -> err = ' + err) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE)
}
}
module.exports = decodeToken
@@ -0,0 +1,8 @@
{
"errors": [
{
"code": 401,
"message": "Wait, you're not supposed to be here, go through the gate as everyone else"
}
]
}
@@ -0,0 +1,27 @@
/* Callbacks default responses. */
global.DEFAULT_OK_RESPONSE = {
result: 'Ok',
message: 'Operation Succeeded'
}
global.DEFAULT_FAIL_RESPONSE = {
result: 'Fail',
message: 'Operation Failed'
}
global.DEFAULT_RETRY_RESPONSE = {
result: 'Retry',
message: 'Retry Later'
}
global.CUSTOM_OK_RESPONSE = {
result: 'Ok, but check Message',
message: 'Custom Message'
}
global.CUSTOM_FAIL_RESPONSE = {
result: 'Fail Because',
message: 'Custom Message'
}
@@ -0,0 +1,65 @@
/* This module imports */
import 'dotenv/config'
import './globals'
import logger from './logger'
import express from 'express'
import graphqlHTTP from 'express-graphql'
import schema from './schema/schema'
import mongoose from 'mongoose'
import checkJwt from './auth/jwt'
import wrongPreshared from './errors/notAllowed.json'
import cors from 'cors'
require('dotenv').config()
const app = express()
// Checking preshared key
app.post('/graphql', (req, res, next) => {
if (req.headers.preshared === process.env.USERS_API_PRESHARED) {
next()
} else {
logger.error('Wrong Pre-Shared Received', req.headers.preshared)
res.send(wrongPreshared)
}
})
// Allow crosss-origin requests
app.use(cors())
// Database Connection
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true })
mongoose.connection.once('open', () => {
logger.info('Connected to the DB.')
})
/* Here we bind all requests to this endpoint to be procecced by the GraphQL Library. */
app.get('/graphql', graphqlHTTP({
schema,
graphiql: true
}))
app.post('/graphql', graphqlHTTP(req => {
return {
schema,
graphiql: false,
context: {
user: req.user,
userId: req.headers.userid
}
}
}))
app.post('/graphql', checkJwt, (err, req, res, next) => {
if (err) return res.status(401).send(`[Authenticate Token Error] ${err.message}`)
next()
})
app.listen(4000, () => {
logger.info('Now listening for requests on port 4000')
})
@@ -0,0 +1,41 @@
import { createLogger, format, transports } from 'winston'
const { combine, timestamp, simple } = format
import { inspect } from 'util'
const options = {
file: {
level: 'info',
filename: '../logs/app.log',
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
timestamp: true
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
timestamp: true
}
}
const logger = createLogger({
level: 'info',
format: format.combine(
format.colorize(),
format.timestamp({ format: 'YY/MM/DD HH:mm' }),
format.printf(
info => `${info.timestamp} - ${info.level}: ${JSON.parse(JSON.stringify(inspect(info.message)))}`
)
),
transports: [
new transports.File(options.file),
new transports.Console(options.console)
],
exitOnError: false // do not exit on handled exceptions
})
export default logger
@@ -0,0 +1,28 @@
/* This is the database schema definition for the User Collection in Mongo DB */
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
authId: String,
referrerId: String,
creationDate: Number,
alias: String,
firstName: String,
middleName: String,
lastName: String,
email: String,
emailVerified: Boolean,
bio: String,
isDeveloper: Boolean,
isTrader: Boolean,
isDataAnalyst: Boolean,
roleId: String,
avatarHandle: String,
avatarChangeDate: String,
sessionToken: String
})
global.UserSchema = global.UserSchema || mongoose.model('User', userSchema)
module.exports = global.UserSchema
@@ -0,0 +1,468 @@
const MODULE_NAME = 'schema'
import logger from '../logger'
import _ from 'lodash'
import User from '../models/user'
import tokenDecoder from '../auth/token-decoder'
const graphql = require('graphql')
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull
} = graphql // Destructuring this variables from inside the package.
let roles = [
{id: '1', name: 'Not Defined'},
{id: '2', name: 'Developer'},
{id: '3', name: 'Trader'},
{id: '4', name: 'Data Analyst'}
]
// Types
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLID},
authId: { type: GraphQLString},
referrerId: {type: GraphQLString},
alias: {type: GraphQLString},
firstName: {type: GraphQLString},
middleName: {type: GraphQLString},
lastName: {type: GraphQLString},
bio: {type: GraphQLString},
email: {type: GraphQLString},
emailVerified: {type: GraphQLInt},
isDeveloper: {type: GraphQLInt},
isTrader: {type: GraphQLInt},
isDataAnalyst: {type: GraphQLInt},
avatarHandle: {type: GraphQLString},
avatarChangeDate: {type: GraphQLString},
sessionToken: {type: GraphQLString},
role: {
type: RoleType,
resolve (parent, args) {
return _.find(roles, {id: parent.roleId})
}
}
})
})
const DescendentType = new GraphQLObjectType({
name: 'Descendent',
fields: () => ({
id: { type: GraphQLID},
referrerId: {type: GraphQLString},
alias: {type: GraphQLString},
firstName: {type: GraphQLString},
middleName: {type: GraphQLString},
lastName: {type: GraphQLString},
descendents: {
type: new GraphQLList(DescendentType),
resolve (parent, args) {
return User.find({referrerId: parent.id})
}
}
})
})
const RoleType = new GraphQLObjectType({
name: 'Role',
fields: () => ({
id: { type: GraphQLID},
name: {type: GraphQLString},
users: {
type: new GraphQLList(UserType),
resolve (parent, args) {
return User.find({roleId: parent.id})
}
}
})
})
// RootQueries
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: {id: {type: GraphQLID}},
resolve (parent, args) {
// Code to get data from data source.
return User.findById(args.id)
}
},
userByAuthId: {
type: UserType,
args: {authId: {type: GraphQLString}},
resolve (parent, args) {
// Code to get data from data source.
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Entering function.') }
/* In order to be able to wait for asyc calls to the database, we need to return a promise to GraphQL. */
const promiseToGraphQL = new Promise((resolve, reject) => {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Promise -> Entering function.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Promise -> args.authId = ' + args.authId) }
findUserByAuthId(args.authId, onUserFound)
function onUserFound (err, responseToGraphQL) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Promise -> onUserFound -> Entering function.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Promise -> onUserFound -> responseToGraphQL = ' + JSON.stringify(responseToGraphQL)) }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> RootQuery -> userByAuthId -> resolve -> Promise -> onUserFound -> err.message = ' + err.message) }
reject(responseToGraphQL)
} else {
resolve(responseToGraphQL)
}
}
})
return promiseToGraphQL
}
},
role: {
type: RoleType,
args: {id: {type: GraphQLID}},
resolve (parent, args) {
// Code to get data from data source.
return _.find(roles, {id: args.id})
}
},
users: {
type: new GraphQLList(UserType),
resolve (parent, args) {
return User.find({})
}
},
roles: {
type: new GraphQLList(RoleType),
resolve (parent, args) {
return roles
}
},
usersSearch: {
type: new GraphQLList(UserType),
args: {alias: {type: GraphQLString}, firstName: {type: GraphQLString}, middleName: {type: GraphQLString}, lastName: {type: GraphQLString}},
resolve (parent, args) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> usersSearch -> resolve -> Entering function.') }
let mongoQuery = { $or: [] }
if (args.alias !== null && args.alias !== '') { mongoQuery.$or.push({alias: args.alias}) }
if (args.firstName !== null && args.firstName !== '') { mongoQuery.$or.push({firstName: args.firstName}) }
if (args.middleName !== null && args.middleName !== '') { mongoQuery.$or.push({middleName: args.middleName}) }
if (args.lastName !== null && args.lastName !== '') { mongoQuery.$or.push({lastName: args.lastName}) }
if (mongoQuery.$or.length === 0) { mongoQuery = {} }
return User.find(mongoQuery)
}
},
descendents: {
type: new GraphQLList(DescendentType),
args: {id: {type: GraphQLString}},
resolve (parent, args) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> RootQuery -> descendents -> resolve -> Entering function.') }
return User.find({referrerId: args.id})
}
}
}
})
// Mutations
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
authenticate: {
type: UserType,
args: {
idToken: {type: new GraphQLNonNull(GraphQLString)}
},
resolve (parent, args) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> Mutation -> authenticate -> resolve -> Entering function.') }
/* In order to be able to wait for asyc calls to the database, and authorization authority, we need to return a promise to GraphQL. */
const promiseToGraphQL = new Promise((resolve, reject) => {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> Mutation -> authenticate -> resolve -> Promise -> Entering function.') }
authenticate(args.idToken, onAuthenticated)
function onAuthenticated (err, responseToGraphQL) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> Mutation -> authenticate -> resolve -> Promise -> onAuthenticated -> Entering function.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> Mutation -> authenticate -> resolve -> Promise -> onAuthenticated -> responseToGraphQL = ' + JSON.stringify(responseToGraphQL)) }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> Mutation -> authenticate -> resolve -> Promise -> onAuthenticated -> err.message = ' + err.message) }
reject(responseToGraphQL)
} else {
resolve(responseToGraphQL)
}
}
})
return promiseToGraphQL
}
},
updateUser: {
type: UserType,
args: {
firstName: {type: GraphQLString},
middleName: {type: GraphQLString},
lastName: {type: GraphQLString},
bio: {type: GraphQLString},
isDeveloper: {type: GraphQLInt},
isTrader: {type: GraphQLInt},
isDataAnalyst: {type: GraphQLInt},
roleId: {type: new GraphQLNonNull(GraphQLString)}
},
resolve (parent, args, context) {
let key = {
_id: context.userId
}
let updatedUser = {
firstName: args.firstName,
middleName: args.middleName,
lastName: args.lastName,
bio: args.bio,
isDeveloper: args.isDeveloper,
isTrader: args.isTrader,
isDataAnalyst: args.isDataAnalyst,
roleId: args.roleId
}
return User.update(key, updatedUser)
}
},
updateUserReferrer: {
type: UserType,
args: {
referrerId: {type: GraphQLString}
},
resolve (parent, args, context) {
let key = {
_id: context.userId,
referrerId: null
}
let updatedUser = {
referrerId: args.referrerId
}
return User.update(key, updatedUser)
}
},
updateSessionToken: {
type: UserType,
args: {
userId: {type: GraphQLString},
sessionToken: {type: GraphQLString}
},
resolve (parent, args) {
let key = {
_id: decodeURI(args.userId)
}
let updatedUser = {
sessionToken: args.sessionToken
}
return User.update(key, updatedUser)
}
}
}
})
function findUserByAuthId (authId, callBackFunction) {
try {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> Entering function.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> authId = ' + authId) }
if (authId === null || authId === undefined) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> User requested not specified.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> args.authId = ' + authId) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: 'Bad Request' })
return
}
User.findOne({authId: authId}, onUserReceived)
function onUserReceived (err, user) {
if (err) {
if (ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> Database Error.') }
if (ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> err = ' + err) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
} else {
if (user === null) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> User not found at Database.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> args.authId = ' + authId) }
let customResponse = {
result: global.CUSTOM_OK_RESPONSE.result,
message: 'User Not Found'
}
callBackFunction(customResponse, { error: customResponse.message })
return
}
if (user.authId === authId && user.authId !== undefined) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> User found at Database.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> args.authId = ' + authId) }
callBackFunction(global.DEFAULT_OK_RESPONSE, user)
return
} else {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> User found at Database is not the user requested.') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> args.authId = ' + authId) }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> findUserByAuthId -> onUserReceived -> user.authId = ' + user.authId) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
return
}
}
}
} catch (err) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> findUserByAuthId -> err.message = ' + err.message) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
}
}
function authenticate (encodedToken, callBackFunction) {
try {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> Entering function.') }
let authId = ''
let alias = ''
let email = ''
let emailVerified = false
tokenDecoder(encodedToken, onValidated)
function onValidated (err, decodedToken) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> Entering function.') }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> onValidated -> err.message = ' + err.message) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
return
}
/*
Ok, the user was correctly authenticated. Next we need to know if this logged in user
has already been added to this module's database or not yet.
*/
authId = decodedToken.sub
alias = decodedToken.nickname
email = decodedToken.email
emailVerified = decodedToken.email_verified
findUserByAuthId(authId, onUserFound)
function onUserFound (err, user) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> Entering function.') }
if (err.result === global.DEFAULT_FAIL_RESPONSE.result) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> err.message = ' + err.message) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
return
}
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> User already exists at database') }
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> Existing User: ' + JSON.stringify(user)) }
callBackFunction(global.DEFAULT_OK_RESPONSE, { authId: authId, alias: user.alias })
return
}
if (
err.result === global.CUSTOM_OK_RESPONSE.result &&
err.message === 'User Not Found'
) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> User does not exist at database') }
/*
The authenticated user is NOT at our module database. We need to add him.
We will take from the authentication provider the basic information it knows about the logged in users
and save it as an initial set of data, which can later be modified.
*/
/* The user can sign up with many different possible social accounts. Currently this module only supports Github only. */
let authArray = authId.split('|')
let socialAccountProvider = authArray[0]
if (
socialAccountProvider !== 'github' &&
socialAccountProvider !== 'auth0'
) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> Social Account Provider not Supoorted. ') }
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> socialAccountProvider = ' + socialAccountProvider) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
return
}
let localDate = new Date()
let creationDate = localDate.valueOf()
let newUser = new User({
alias: alias,
authId: authId,
creationDate: creationDate,
email: email,
emailVerified: emailVerified,
roleId: '1'
})
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> ' + alias + ' being added to the database') }
newUser.save(onSaved)
function onSaved (err, savedUser) {
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> onSaved -> Entering function.') }
if (err) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> onSaved -> err = ' + err) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
return
}
if (process.env.INFO_LOG === true) { logger.debug('[INFO] ' + MODULE_NAME + ' -> authenticate -> onValidated -> onUserFound -> onSaved -> Saved User: ' + JSON.stringify(savedUser)) }
callBackFunction(global.DEFAULT_OK_RESPONSE, { authId, alias })
}
}
}
}
} catch (err) {
if (process.env.ERROR_LOG === true) { logger.error('[ERROR] ' + MODULE_NAME + ' -> authenticate -> err.message = ' + err.message) }
callBackFunction(global.DEFAULT_FAIL_RESPONSE, { error: err })
}
}
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
})
@@ -0,0 +1,9 @@
const getItem = async name => window.localStorage.getItem(name)
const setItem = async (name, value) => window.localStorage.setItem(name, value)
const removeItem = async name => window.localStorage.removeItem(name)
export {
getItem,
setItem,
removeItem
}