Full stack serverless template
This commit is contained in:
81
api/app.js
Normal file
81
api/app.js
Normal file
@@ -0,0 +1,81 @@
|
||||
const express = require('express')
|
||||
const app = express()
|
||||
const passport = require('passport')
|
||||
const {
|
||||
users
|
||||
} = require('./controllers')
|
||||
|
||||
/**
|
||||
* Configure Passport
|
||||
*/
|
||||
|
||||
try { require('./config/passport')(passport) }
|
||||
catch (error) { console.log(error) }
|
||||
|
||||
/**
|
||||
* Configure Express.js Middleware
|
||||
*/
|
||||
|
||||
// Enable CORS
|
||||
app.use(function (req, res, next) {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
res.header('Access-Control-Allow-Headers', '*')
|
||||
res.header('x-powered-by', 'serverless-express')
|
||||
next()
|
||||
})
|
||||
|
||||
// Initialize Passport and restore authentication state, if any, from the session
|
||||
app.use(passport.initialize())
|
||||
app.use(passport.session())
|
||||
|
||||
// Enable JSON use
|
||||
app.use(express.json())
|
||||
|
||||
// Since Express doesn't support error handling of promises out of the box,
|
||||
// this handler enables that
|
||||
const asyncHandler = fn => (req, res, next) => {
|
||||
return Promise
|
||||
.resolve(fn(req, res, next))
|
||||
.catch(next);
|
||||
};
|
||||
|
||||
/**
|
||||
* Routes - Public
|
||||
*/
|
||||
|
||||
app.options(`*`, (req, res) => {
|
||||
res.status(200).send()
|
||||
})
|
||||
|
||||
app.post(`/users/register`, asyncHandler(users.register))
|
||||
|
||||
app.post(`/users/login`, asyncHandler(users.login))
|
||||
|
||||
app.get(`/test/`, (req, res) => {
|
||||
res.status(200).send('Request received')
|
||||
})
|
||||
|
||||
/**
|
||||
* Routes - Protected
|
||||
*/
|
||||
|
||||
app.post(`/user`, passport.authenticate('jwt', { session: false }), asyncHandler(users.get))
|
||||
|
||||
/**
|
||||
* Routes - Catch-All
|
||||
*/
|
||||
|
||||
app.get(`/*`, (req, res) => {
|
||||
res.status(404).send('Route not found')
|
||||
})
|
||||
|
||||
/**
|
||||
* Error Handler
|
||||
*/
|
||||
app.use(function (err, req, res, next) {
|
||||
console.error(err)
|
||||
res.status(500).json({ error: `Internal Serverless Error - "${err.message}"` })
|
||||
})
|
||||
|
||||
module.exports = app
|
||||
27
api/config/passport.js
Normal file
27
api/config/passport.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Config: Passport.js
|
||||
*/
|
||||
|
||||
const StrategyJWT = require('passport-jwt').Strategy
|
||||
const ExtractJWT = require('passport-jwt').ExtractJwt
|
||||
const { users } = require('../models')
|
||||
const { comparePassword } = require('../utils')
|
||||
|
||||
module.exports = (passport) => {
|
||||
|
||||
const options = {}
|
||||
options.jwtFromRequest = ExtractJWT.fromAuthHeaderAsBearerToken()
|
||||
options.secretOrKey = process.env.tokenSecret || 'secret_j91jasf0j1asfkl' // Change this to only use your own secret token
|
||||
|
||||
passport.use(new StrategyJWT(options, async (jwtPayload, done) => {
|
||||
let user
|
||||
try { user = await users.getById(jwtPayload.id) }
|
||||
catch (error) {
|
||||
console.log(error)
|
||||
return done(error, null)
|
||||
}
|
||||
|
||||
if (!user) { return done(null, false) }
|
||||
return done(null, user)
|
||||
}))
|
||||
}
|
||||
5
api/controllers/index.js
Normal file
5
api/controllers/index.js
Normal file
@@ -0,0 +1,5 @@
|
||||
const users = require('./users')
|
||||
|
||||
module.exports = {
|
||||
users,
|
||||
}
|
||||
81
api/controllers/users.js
Normal file
81
api/controllers/users.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Controllers: Users
|
||||
*/
|
||||
|
||||
const jwt = require('jsonwebtoken')
|
||||
const { users } = require('../models')
|
||||
const { comparePassword } = require('../utils')
|
||||
|
||||
/**
|
||||
* Save
|
||||
* @param {*} req
|
||||
* @param {*} res
|
||||
* @param {*} next
|
||||
*/
|
||||
const register = async (req, res, next) => {
|
||||
|
||||
try {
|
||||
await users.register(req.body)
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: error.message })
|
||||
}
|
||||
|
||||
let user
|
||||
try {
|
||||
user = await users.getByEmail(req.body.email)
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
return next(error, null)
|
||||
}
|
||||
|
||||
const token = jwt.sign(user, process.env.tokenSecret, {
|
||||
expiresIn: 604800 // 1 week
|
||||
})
|
||||
|
||||
res.json({ message: 'Authentication successful', token })
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a user in
|
||||
* @param {*} req
|
||||
* @param {*} res
|
||||
* @param {*} next
|
||||
*/
|
||||
const login = async (req, res, next) => {
|
||||
|
||||
let user
|
||||
try { user = await users.getByEmail(req.body.email) }
|
||||
catch (error) { return done(error, null) }
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).send({ error: 'Authentication failed. User not found.' })
|
||||
}
|
||||
|
||||
const isCorrect = comparePassword(req.body.password, user.password)
|
||||
if (!isCorrect) {
|
||||
return res.status(401).send({ error: 'Authentication failed. Wrong password.' })
|
||||
}
|
||||
|
||||
const token = jwt.sign(user, process.env.tokenSecret, {
|
||||
expiresIn: 604800 // 1 week
|
||||
})
|
||||
|
||||
res.json({ message: 'Authentication successful', token })
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user
|
||||
* @param {*} req
|
||||
* @param {*} res
|
||||
* @param {*} next
|
||||
*/
|
||||
const get = async (req, res, next) => {
|
||||
const user = users.convertToPublicFormat(req.user)
|
||||
res.json({ user })
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
register,
|
||||
login,
|
||||
get,
|
||||
}
|
||||
5
api/models/index.js
Normal file
5
api/models/index.js
Normal file
@@ -0,0 +1,5 @@
|
||||
const users = require('./users')
|
||||
|
||||
module.exports = {
|
||||
users,
|
||||
}
|
||||
136
api/models/users.js
Normal file
136
api/models/users.js
Normal file
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Model: Users
|
||||
*/
|
||||
|
||||
const AWS = require('aws-sdk')
|
||||
const shortid = require('shortid')
|
||||
const utils = require('../utils')
|
||||
|
||||
const dynamodb = new AWS.DynamoDB.DocumentClient({
|
||||
region: process.env.AWS_REGION
|
||||
})
|
||||
|
||||
/**
|
||||
* Register user
|
||||
* @param {string} user.email User email
|
||||
* @param {string} user.password User password
|
||||
*/
|
||||
const register = async(user = {}) => {
|
||||
|
||||
// Validate
|
||||
if (!user.email) {
|
||||
throw new Error(`"email" is required`)
|
||||
}
|
||||
if (!user.password) {
|
||||
throw new Error(`"password" is required`)
|
||||
}
|
||||
if (!utils.validateEmailAddress(user.email)) {
|
||||
throw new Error(`"${user.email}" is not a valid email address`)
|
||||
}
|
||||
|
||||
// Check if user is already registered
|
||||
const existingUser = await getByEmail(user.email)
|
||||
if (existingUser) {
|
||||
throw new Error(`A user with email "${user.email}" is already registered`)
|
||||
}
|
||||
|
||||
user.password = utils.hashPassword(user.password)
|
||||
|
||||
// Save
|
||||
const params = {
|
||||
TableName: process.env.db,
|
||||
Item: {
|
||||
hk: user.email,
|
||||
sk: 'user',
|
||||
sk2: shortid.generate(),
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
password: user.password,
|
||||
}
|
||||
}
|
||||
|
||||
await dynamodb.put(params).promise()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by email address
|
||||
* @param {string} email
|
||||
*/
|
||||
|
||||
const getByEmail = async(email) => {
|
||||
|
||||
// Validate
|
||||
if (!email) {
|
||||
throw new Error(`"email" is required`)
|
||||
}
|
||||
if (!utils.validateEmailAddress(email)) {
|
||||
throw new Error(`"${email}" is not a valid email address`)
|
||||
}
|
||||
|
||||
// Query
|
||||
const params = {
|
||||
TableName: process.env.db,
|
||||
KeyConditionExpression: 'hk = :hk',
|
||||
ExpressionAttributeValues: { ':hk': email }
|
||||
}
|
||||
|
||||
let user = await dynamodb.query(params).promise()
|
||||
|
||||
user = user.Items && user.Items[0] ? user.Items[0] : null
|
||||
if (user) {
|
||||
user.id = user.sk2
|
||||
user.email = user.hk
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by id
|
||||
* @param {string} id
|
||||
*/
|
||||
|
||||
const getById = async(id) => {
|
||||
|
||||
// Validate
|
||||
if (!id) {
|
||||
throw new Error(`"id" is required`)
|
||||
}
|
||||
|
||||
// Query
|
||||
const params = {
|
||||
TableName: process.env.db,
|
||||
IndexName: process.env.dbIndex1,
|
||||
KeyConditionExpression: 'sk2 = :sk2 and sk = :sk',
|
||||
ExpressionAttributeValues: { ':sk2': id, ':sk': 'user' }
|
||||
}
|
||||
let user = await dynamodb.query(params).promise()
|
||||
|
||||
user = user.Items && user.Items[0] ? user.Items[0] : null
|
||||
if (user) {
|
||||
user.id = user.sk2
|
||||
user.email = user.hk
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert user record to public format
|
||||
* This hides the keys used for the dynamodb's single table design and returns human-readable properties.
|
||||
* @param {*} user
|
||||
*/
|
||||
const convertToPublicFormat = (user = {}) => {
|
||||
user.email = user.hk || null
|
||||
user.id = user.sk2 || null
|
||||
if (user.hk) delete user.hk
|
||||
if (user.sk) delete user.sk
|
||||
if (user.sk2) delete user.sk2
|
||||
if (user.password) delete user.password
|
||||
return user
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
register,
|
||||
getByEmail,
|
||||
getById,
|
||||
convertToPublicFormat,
|
||||
}
|
||||
20
api/package.json
Normal file
20
api/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "serverless-fullstack-app-api",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "app.js",
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"express": "^4.17.1",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"passport": "^0.4.1",
|
||||
"passport-jwt": "^4.0.0",
|
||||
"shortid": "^2.2.15"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC"
|
||||
}
|
||||
18
api/serverless.yml
Normal file
18
api/serverless.yml
Normal file
@@ -0,0 +1,18 @@
|
||||
component: express
|
||||
name: api
|
||||
|
||||
inputs:
|
||||
# Express application source code.
|
||||
src: ./
|
||||
# Permissions required for the AWS Lambda function to interact with other resources
|
||||
roleName: ${output:permissions.name}
|
||||
# Enable this when you want to set a custom domain.
|
||||
# domain: api.${env:domain}
|
||||
# Environment variables
|
||||
env:
|
||||
# AWS DynamoDB Table name. Needed for the code to access it.
|
||||
db: ${output:database.name}
|
||||
# AWS DynamoDB Table Index name. Needed for the code to access it.
|
||||
dbIndex1: ${output:database.indexes.gsi1.name}
|
||||
# A secret token to sign the JWT tokens with.
|
||||
tokenSecret: secret_1234 # Change to secret via environment variable: ${env:tokenSecret}
|
||||
35
api/utils/index.js
Normal file
35
api/utils/index.js
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Utils
|
||||
*/
|
||||
|
||||
const bcrypt = require('bcryptjs')
|
||||
|
||||
/**
|
||||
* Validate email address
|
||||
*/
|
||||
const validateEmailAddress = (email) => {
|
||||
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
|
||||
return re.test(String(email).toLowerCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash password
|
||||
* @param {*} user
|
||||
*/
|
||||
const hashPassword = (password) => {
|
||||
const salt = bcrypt.genSaltSync(10)
|
||||
return bcrypt.hashSync(password, salt)
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare password
|
||||
*/
|
||||
const comparePassword = (candidatePassword, trustedPassword) => {
|
||||
return bcrypt.compareSync(candidatePassword, trustedPassword)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
hashPassword,
|
||||
comparePassword,
|
||||
validateEmailAddress
|
||||
}
|
||||
Reference in New Issue
Block a user