Last active
September 14, 2022 15:46
-
-
Save georgeben/81b4e9a6838be0b1d5f45ddd639e45be to your computer and use it in GitHub Desktop.
Multi factor authentication using Redis
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
const express = require('express') | |
const redis = require('redis') | |
const app = express() | |
app.use(express.json()) | |
const redisClient = redis.createClient({ | |
legacyMode: true, | |
url: 'your-redis-url-from-redis-cloud' | |
}) | |
redisClient.connect() | |
redisClient.on("ready", () => console.log("Successfully connected to redis")); | |
app.post('/login', async (req, res) => { | |
const { email, password } = req.body; | |
const sampleUser = { | |
name: 'John Dorian', | |
email: '[email protected]', | |
password: 'iloveturk' | |
} | |
if (email !== sampleUser.email || password !== sampleUser.password) { | |
return res.status(401).json({ | |
message: 'Invalid email or password' | |
}) | |
} | |
/** | |
* If email and password is correct, generate an OTP to be | |
* sent to the user's phone number. Save the OTP you generated | |
* in redis, and set it's value the the user's data | |
**/ | |
// | |
try { | |
const otp = Math.floor(100000 + Math.random() * 900000); | |
const FIVE_MINUTES = 60 * 5 | |
await redisClient.json.set(otp.toString(), '$', sampleUser) | |
// Set the OTP expiry to 5 minutes. After 5 minutes, the | |
// OTP would be deleted from REDIS | |
redisClient.expire(otp, FIVE_MINUTES) | |
// Send the OTP to user's phone number | |
return res.status(200).json({ message: 'An OTP has been sent to your number ending with *****72' }) | |
} catch (error) { | |
console.log('Error', error) | |
} | |
}) | |
app.post('/verify-otp', async (req, res) => { | |
const { otp } = req.body | |
// Get the OTP from Redis | |
const user = await redisClient.json.get(otp) | |
if (!user) { | |
return res.status(401).json({ message: 'Invalid OTP. Failed to login.' }) | |
} | |
return res.status(200).json({ | |
message: 'Successfully logged in!' | |
}) | |
}) | |
app.listen(5000, () => console.log('App running')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment