Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add jest tests #12

Open
wants to merge 32 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
b6cc5ed
Add cors
benawad Jun 17, 2017
a161655
readme
benawad Jun 17, 2017
aea0626
add authentication
benawad Jun 18, 2017
fd02ce4
readme
benawad Jun 18, 2017
5735fea
set up subscriptions on server
benawad Jun 28, 2017
b285469
add permissions
benawad Jul 1, 2017
1651a8c
add refresh tokens implementation
benawad Jul 1, 2017
770f946
Add dataloader
benawad Jul 1, 2017
c356b30
facebook oauth
benawad Jul 4, 2017
dda5162
store user in db
benawad Jul 4, 2017
14c400e
pass token back to client
benawad Jul 4, 2017
b6ab71f
fix register resolver
benawad Jul 6, 2017
11d1c8a
get server ready for login
benawad Jul 7, 2017
eb5fd8e
Update README.md
benawad Jul 7, 2017
fe03592
Update index.js
benawad Jul 16, 2017
445646c
add limit and offset pagination
benawad Jul 27, 2017
0ac3128
cursor pagination for suggestions
benawad Jul 28, 2017
cc68ac0
Update README.md
benawad Jul 28, 2017
4e78fe7
ignore .env
benawad Aug 5, 2017
b07f1ee
Merge branch '17_cursor_pagination' of https://github.com/benawad/gra…
benawad Aug 5, 2017
c6787b1
add n to m relationship and graphql types and resolvers for mutations
benawad Aug 5, 2017
42a1d07
remove price
benawad Aug 5, 2017
d03de96
added join monster
benawad Aug 5, 2017
0acae68
add pagination to allbooks
benawad Aug 5, 2017
e5afa89
split schema up
benawad Aug 30, 2017
6a2e735
removed facebook auth and extra stuff
benawad Sep 5, 2017
475003d
add second secret for refresh token
benawad Sep 5, 2017
8f69e74
new table for champion that has an image
benawad Sep 10, 2017
7c1d6f4
search
benawad Sep 12, 2017
6a6f4e4
merging accounts
benawad Sep 15, 2017
d68eb66
make sure to return user
benawad Sep 15, 2017
629c52a
Update README.md
benawad Sep 15, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"presets": [
"latest"
"latest",
"stage-2"
]
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.env
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# Template for an Express Server with GraphQL

[Watch the video to learn how it was made.](https://youtu.be/hqk30IVeYak
)
[Watch the video to learn how it was made.](https://youtu.be/X6pNLEOs-10)
83 changes: 83 additions & 0 deletions auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import jwt from 'jsonwebtoken';
import _ from 'lodash';
import bcrypt from 'bcrypt';

export const createTokens = async (user, secret, secret2) => {
const createToken = jwt.sign(
{
user: _.pick(user, ['id', 'isAdmin']),
},
secret,
{
expiresIn: '1m',
},
);

const createRefreshToken = jwt.sign(
{
user: _.pick(user, 'id'),
},
secret2,
{
expiresIn: '7d',
},
);

return Promise.all([createToken, createRefreshToken]);
};

export const refreshTokens = async (token, refreshToken, models, SECRET, SECRET_2) => {
let userId = -1;
try {
const { user: { id } } = jwt.decode(refreshToken);
userId = id;
} catch (err) {
return {};
}

if (!userId) {
return {};
}

const user = await models.User.findOne({ where: { id: userId }, raw: true });

if (!user) {
return {};
}

const refreshSecret = SECRET_2 + user.password;

try {
jwt.verify(refreshToken, refreshSecret);
} catch (err) {
return {};
}

const [newToken, newRefreshToken] = await createTokens(user, SECRET, refreshSecret);
return {
token: newToken,
refreshToken: newRefreshToken,
user,
};
};

export const tryLogin = async (email, password, models, SECRET, SECRET_2) => {
const user = await models.User.findOne({ where: { email }, raw: true });
if (!user) {
// user with provided email not found
throw new Error('Invalid login');
}

const valid = await bcrypt.compare(password, user.password);
if (!valid) {
// bad password
throw new Error('Invalid login');
}

const [token, refreshToken] = await createTokens(user, SECRET, SECRET_2 + user.password);

return {
token,
refreshToken,
};
};
9 changes: 9 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"development": {
"username": "test_graphql_admin",
"password": "iamapassword",
"database": "test_graphql_db",
"host": "localhost",
"dialect": "postgres"
}
}
122 changes: 120 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,113 @@
import 'dotenv/config';
import express from 'express';
import bodyParser from 'body-parser';
import { graphiqlExpress, graphqlExpress } from 'graphql-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import cors from 'cors';
import jwt from 'jsonwebtoken';
import { createServer } from 'http';
import { execute, subscribe } from 'graphql';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import joinMonsterAdapt from 'join-monster-graphql-tools-adapter';
import passport from 'passport';
import FacebookStrategy from 'passport-facebook';

import typeDefs from './schema';
import resolvers from './resolvers';
import models from './models';
import { createTokens, refreshTokens } from './auth';
import joinMonsterMetadata from './joinMonsterMetadata';

const schema = makeExecutableSchema({
typeDefs,
resolvers,
});

joinMonsterAdapt(schema, joinMonsterMetadata);

const SECRET = 'aslkdjlkaj10830912039jlkoaiuwerasdjflkasd';
const SECRET_2 = 'ajsdklfjaskljgklasjoiquw01982310nlksas;sdlkfj';

const app = express();

passport.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/facebook/callback',
scope: ['email'],
profileFields: ['id', 'emails'],
},
async (accessToken, refreshToken, profile, cb) => {
// 2 cases
// #1 first time login
// #2 previously logged in with facebook
// #3 previously registered with email
const { id, emails: [{ value }] } = profile;
// []
let fbUser = await models.User.findOne({
where: { $or: [{ fbId: id }, { email: value }] },
});

console.log(fbUser);
console.log(profile);

if (!fbUser) {
// case #1
fbUser = await models.User.create({
fbId: id,
email: value,
});
} else if (!fbUser.fbId) {
// case #3
// add email to user
await fbUser.update({
fbId: id,
});
}

cb(null, fbUser);
},
),
);

app.use(passport.initialize());

app.get('/flogin', passport.authenticate('facebook'));

app.get(
'/auth/facebook/callback',
passport.authenticate('facebook', { session: false }),
async (req, res) => {
const [token, refreshToken] = await createTokens(req.user, SECRET, SECRET_2);
res.redirect(`http://localhost:3001/home?token=${token}&refreshToken=${refreshToken}`);
},
);

const addUser = async (req, res, next) => {
const token = req.headers['x-token'];
if (token) {
try {
const { user } = jwt.verify(token, SECRET);
req.user = user;
} catch (err) {
const refreshToken = req.headers['x-refresh-token'];
const newTokens = await refreshTokens(token, refreshToken, models, SECRET, SECRET_2);
if (newTokens.token && newTokens.refreshToken) {
res.set('Access-Control-Expose-Headers', 'x-token, x-refresh-token');
res.set('x-token', newTokens.token);
res.set('x-refresh-token', newTokens.refreshToken);
}
req.user = newTokens.user;
}
}
next();
};

app.use(cors('*'));
app.use(addUser);

app.use(
'/graphiql',
graphiqlExpress({
Expand All @@ -24,7 +118,31 @@ app.use(
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress({ schema, context: { models } }),
graphqlExpress(req => ({
schema,
context: {
models,
SECRET,
SECRET_2,
user: req.user,
},
})),
);

models.sequelize.sync().then(() => app.listen(3000));
const server = createServer(app);

models.sequelize.sync({ force: true }).then(() =>
server.listen(3000, () => {
new SubscriptionServer(
{
execute,
subscribe,
schema,
},
{
server,
path: '/subscriptions',
},
);
}),
);
54 changes: 54 additions & 0 deletions joinMonsterMetadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
export default {
Query: {
fields: {
getBook: {
where: (table, empty, args) => `${table}.id = ${args.id}`,
},
allBooks: {
limit: (table, { limit }) => limit,
orderBy: 'id',
where: (table, empty, { key }) => `${table}.id > ${key}`,
},
},
},
Author: {
sqlTable: 'authors',
uniqueKey: 'id',
fields: {
books: {
junction: {
sqlTable: '"bookAuthors"',
include: {
primary: {
sqlColumn: 'primary',
},
},
sqlJoins: [
(authorTable, junctionTable) => `${authorTable}.id = ${junctionTable}."authorId"`,
(junctionTable, bookTable) => `${junctionTable}."bookId" = ${bookTable}.id`,
],
},
},
},
},
Book: {
sqlTable: 'books',
uniqueKey: 'id',
fields: {
authors: {
junction: {
sqlTable: '"bookAuthors"',
include: {
primary: {
sqlColumn: 'primary',
},
},
sqlJoins: [
(bookTable, junctionTable) => `${bookTable}.id = ${junctionTable}."bookId"`,
(junctionTable, authorTable) => `${junctionTable}."authorId" = ${authorTable}.id`,
],
},
},
},
},
};
22 changes: 22 additions & 0 deletions models/author.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default (sequelize, DataTypes) => {
const Author = sequelize.define('author', {
firstname: {
type: DataTypes.STRING,
},
lastname: {
type: DataTypes.STRING,
},
});

Author.associate = (models) => {
// many to many with book
Author.belongsToMany(models.Book, {
through: {
model: models.BookAuthor,
},
foreignKey: 'authorId',
});
};

return Author;
};
19 changes: 19 additions & 0 deletions models/book.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default (sequelize, DataTypes) => {
const Book = sequelize.define('book', {
title: {
type: DataTypes.STRING,
},
});

Book.associate = (models) => {
// many to many with book
Book.belongsToMany(models.Author, {
through: {
model: models.BookAuthor,
},
foreignKey: 'bookId',
});
};

return Book;
};
9 changes: 9 additions & 0 deletions models/bookAuthor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default (sequelize, DataTypes) => {
const BookAuthor = sequelize.define('bookAuthor', {
primary: {
type: DataTypes.BOOLEAN,
},
});

return BookAuthor;
};
12 changes: 12 additions & 0 deletions models/champion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default (sequelize, DataTypes) => {
const Champion = sequelize.define('champion', {
name: {
type: DataTypes.STRING,
},
publicId: {
type: DataTypes.STRING,
},
});

return Champion;
};
Loading