Skip to content

Instantly share code, notes, and snippets.

@duartefdias
Last active March 20, 2024 23:09
Show Gist options
  • Save duartefdias/0a1467e7f788a1ca261d2b1e02596783 to your computer and use it in GitHub Desktop.
Save duartefdias/0a1467e7f788a1ca261d2b1e02596783 to your computer and use it in GitHub Desktop.
var express = require('express');
var router = express.Router();
// Used to perfrom signature authentication
var ethUtil = require('ethereumjs-util');
// JWT generation and verification
const jwt = require('jsonwebtoken');
import passport from 'passport'
import User from '../models/users';
// Check if user exists
router.get('/:wallet_address', (req, res) => {
// Check if user exists
// ... check if user's address is already in the database and return true or false
});
// Register user
router.post('/register', (req, res) => {
const user = new User();
user.address = req.body.address;
// .. add any additional fields depending on your schema
user.save((err) => {
if (err) {
res.send(err);
}
res.json({ message: 'User successfully registered!' });
});
});
// Get user nonce
router.get('/:wallet_address/nonce', (req, res) => {
// Check if user exists
// ... search in database for user and returns its current nonce
});
// Process signed message
router.post('/:user/signature', (req, res) => {
// Get user from db
User.findOne({wallet_address: req.params.user}, (err, user) => {
if (err) {
res.send(err);
}
if (user) {
const msg = `Nonce: ${user.nonce}`;
// Convert msg to hex string
const msgHex = ethUtil.bufferToHex(Buffer.from(msg));
// Check if signature is valid
const msgBuffer = ethUtil.toBuffer(msgHex);
const msgHash = ethUtil.hashPersonalMessage(msgBuffer);
const signatureBuffer = ethUtil.toBuffer(req.body.signature);
const signatureParams = ethUtil.fromRpcSig(signatureBuffer);
const publicKey = ethUtil.ecrecover(
msgHash,
signatureParams.v,
signatureParams.r,
signatureParams.s
);
const addresBuffer = ethUtil.publicToAddress(publicKey);
const address = ethUtil.bufferToHex(addresBuffer);
// Check if address matches
if (address.toLowerCase() === req.params.user.toLowerCase()) {
// Change user nonce
user.nonce = Math.floor(Math.random() * 1000000);
user.save((err) => {
if (err) {
res.send(err);
}
});
// Set jwt token
const token = jwt.sign({
_id: user._id,
address: user.address
}, process.env.JWT_SECRET, {expiresIn: '6h'});
res.status(200).json({
success: true,
token: `Bearer ${token}`,
user: user,
msg: "You are now logged in."
});
} else {
// User is not authenticated
res.status(401).send('Invalid credentials');
}
} else {
res.send('User does not exist');
}
});
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment