Created
April 27, 2019 13:43
-
-
Save byurhannurula/a55f985c22321f353c140f39e6656d0f to your computer and use it in GitHub Desktop.
index.js - apollo server / user.js - user resolver / user.graphql - graphql schema of user / auth.js = helper functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { User } from './models' | |
export const isAuthenticated = req => { | |
if (!req || !req.session || !req.session.userId) { | |
// user is not logged in | |
throw new Error('Not authenticated!') | |
} | |
} | |
export const signOut = (req, res) => | |
new Promise((resolve, reject) => { | |
req.session.destroy(err => { | |
if (err) reject(err) | |
res.clearCookie(process.env.SESS_NAME) | |
resolve(true) | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cors from 'cors' | |
import dotenv from 'dotenv' | |
import express from 'express' | |
import mongoose from 'mongoose' | |
import session from 'express-session' | |
import connectRedis from 'connect-redis' | |
import { ApolloServer } from 'apollo-server-express' | |
import typeDefs from './schema' | |
import resolvers from './resolvers' | |
dotenv.config({ | |
path: `.env.${process.env.NODE_ENV}`, | |
}) | |
const port = process.env.PORT || 4000 | |
const dev = process.env.NODE_ENV !== 'production' | |
const RedisStore = connectRedis(session) | |
const startServer = async () => { | |
await mongoose | |
.connect(process.env.DB_URL, { useNewUrlParser: true }) | |
.then(() => console.log(`🔗 MongoDB Connected...`)) | |
.catch(err => console.log(`❌ MongoDB Connection error: ${err}`)) | |
const app = express() | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
playground: !dev | |
? false | |
: { | |
settings: { | |
'request.credentials': 'include', | |
}, | |
}, | |
context: ({ req, res }) => ({ req, res }), | |
}) | |
app.disable('x-powered-by') | |
app.set('trust proxy', 1) | |
app.use( | |
cors({ | |
credentials: true, | |
origin: | |
process.env.NODE_ENV === 'production' | |
? process.env.FRONT_END_URL | |
: 'http://localhost:3000', | |
}), | |
) | |
app.use((req, _, next) => { | |
const authorization = req.headers.authorization | |
if (authorization) { | |
try { | |
const cid = authorization.split(' ')[1] | |
req.headers.cookie = `cid=${cid}` | |
} catch (err) { | |
console.log(err) | |
} | |
} | |
return next() | |
}) | |
app.use( | |
session({ | |
store: new RedisStore({ | |
host: process.env.REDIS_HOST, | |
port: process.env.REDIS_PORT, | |
pass: process.env.REDIS_PASS, | |
}), | |
name: process.env.SESS_NAME, | |
secret: process.env.SESS_SECRET, | |
saveUninitialized: false, | |
resave: false, | |
cookie: { | |
httpOnly: true, | |
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days | |
secure: false, | |
}, | |
}), | |
) | |
server.applyMiddleware({ app, cors: false }) | |
app.listen({ port }, () => | |
console.log( | |
`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`, | |
), | |
) | |
} | |
startServer() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql } from 'apollo-server-express' | |
const schema = gql` | |
type Query { | |
me: User | |
user(id: ID!): User | |
users: [User!]! | |
} | |
type Mutation { | |
signUp(name: String!, email: String!, password: String!): User | |
signIn(email: String!, password: String!): User! | |
signOut: Boolean | |
} | |
type User { | |
id: ID! | |
name: String! | |
email: String! | |
password: String! | |
avatar: String | |
createdRooms: [Room!] | |
createdAt: String! | |
updatedAt: String! | |
} | |
` | |
export default schema |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gravatar from 'gravatar' | |
import bcrypt from 'bcrypt' | |
import { User } from '../models' | |
import { isAuthenticated, signOut } from '../auth' | |
import { loginSchema, registerSchema } from '../utils' | |
export default { | |
Query: { | |
user: (parent, { id }, context, info) => { | |
isAuthenticated(req) | |
return User.findById(id) | |
}, | |
me: (parent, args, { req }, info) => { | |
isAuthenticated(req) | |
return User.findById(req.session.userId) | |
}, | |
}, | |
Mutation: { | |
signUp: async (parent, args, { req }, info) => { | |
// isAuthenticated(req) | |
args.email = args.email.toLowerCase() | |
try { | |
await registerSchema.validate(args, { abortEarly: false }) | |
} catch (err) { | |
return err | |
} | |
args.password = await bcrypt.hash(args.password, 12) | |
const user = await User.create(args) | |
req.session.userId = user.id | |
return user | |
}, | |
signIn: async (parent, args, { req }, info) => { | |
// isAuthenticated(req) | |
const { email, password } = args | |
try { | |
await loginSchema.validate(args, { abortEarly: false }) | |
} catch (err) { | |
return err | |
} | |
const user = await User.findOne({ email }) | |
if (!user || !(await bcrypt.compare(password, user.password))) { | |
throw new Error('Incorrect email or password. Please try again.') | |
} | |
req.session.userId = user.id | |
return user | |
}, | |
signOut: (parent, args, { req, res }, info) => { | |
return signOut(req, res) | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment