Created
May 6, 2019 10:41
-
-
Save renso3x/9524b311bbe88f6abf1d3e69cd74e802 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
'use strict'; | |
import { v1 as neo4j } from 'neo4j-driver'; | |
import crypto from 'crypto'; | |
import uuidv4 from 'uuid/v4'; | |
import middleware from 'lambda-utilities/lib/middleware'; | |
import { filterWarmUpEvent } from 'lambda-utilities/lib/middleware/filterWarmUpEvent'; | |
import { ErrorUnauthorized } from 'lambda-utilities/lib/error'; | |
import { jsonResponse } from '../utils/util'; | |
import errorResponse from '../utils/errorResponse'; | |
import auth from '../../config/auth'; | |
import neo4jconfig from '../../config/neo4jconfig'; | |
const { | |
auth: { basic } | |
} = neo4j; | |
const { uri, user, password } = neo4jconfig; | |
export const handler = async (event, context, callback) => { | |
context.callbackWaitsForEmptyEventLoop = false; | |
try { | |
// event.pathParameters.custId | |
const { Authorization } = event.headers; | |
const driver = neo4j.driver(uri, basic(user, password)); | |
const session = driver.session(); | |
// temporary check for authorization | |
if (Authorization !== auth.apiKey) { | |
throw new ErrorUnauthorized(); | |
} | |
const email = decodeURIComponent(event.pathParameters.email); | |
const hashedEmail = crypto | |
.createHash('sha256') | |
.update(email) | |
.digest('base64'); | |
const userEmail = await session.run( | |
`MATCH (c:customer{ email: "${hashedEmail}" }) RETURN c.user_id` | |
); | |
let userId; | |
const isExist = userEmail.records.length > 0; | |
if (!isExist) { | |
// create user | |
const result = await session.run( | |
`CREATE (c:customer{ user_id: "${uuidv4()}", email: "${hashedEmail}" }) RETURN c.user_id` | |
); | |
userId = result.records[0].get('c.user_id'); | |
} else { | |
userId = userEmail.records[0].get('c.user_id'); | |
} | |
driver.close(); | |
session.close(); | |
const response = { | |
statusCode: 200, | |
userId | |
}; | |
return callback(null, jsonResponse(response)); | |
} catch (e) { | |
return callback(null, errorResponse(e)); | |
} | |
}; | |
export default middleware(filterWarmUpEvent())(handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment