Created
October 16, 2017 20:00
-
-
Save oshalygin/1c3cce71eb3fbcaef8f6c0e823b1a76d 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
import GoogleAuth from 'google-auth-library'; | |
import { googleAuthClientId } from '../../src/constants/config'; | |
import { User } from '../utilities/database'; | |
import { path } from 'ramda'; | |
const checkUserToken = token => { | |
return new Promise((resolve, reject) => { | |
const auth = new GoogleAuth(); | |
const client = new auth.OAuth2(googleAuthClientId, '', ''); | |
client.verifyIdToken(token, googleAuthClientId, (error, login) => { | |
if (error) { | |
reject(error); | |
} | |
resolve(login); | |
}); | |
}); | |
}; | |
const authenticateUser = async ({ body }, response) => { | |
const { id_token } = body; | |
try { | |
const { _payload } = await checkUserToken(id_token); | |
const { name, email, picture } = _payload; | |
const user = await User.find({ | |
where: { | |
email, | |
}, | |
}); | |
if (!user) { | |
await User.create({ name, email, picture }); | |
return response.status(401).json({ status: 'Not Authorized' }); | |
} | |
if (path('permissions', user)) { | |
return response.status(200).json(user); | |
} | |
} catch (error) { | |
// Handle your error and display a nice message or just bomb out and return the bottom 401 | |
return response.status(401).json({ status: 'Not Authorized' }); | |
} | |
}; | |
const authController = { | |
post: authenticateUser, | |
}; | |
export default authController; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment