Skip to content

Instantly share code, notes, and snippets.

@lttn1204
Last active April 26, 2022 05:33
Show Gist options
  • Save lttn1204/8659c561587a8120353f56107f09f2c2 to your computer and use it in GitHub Desktop.
Save lttn1204/8659c561587a8120353f56107f09f2c2 to your computer and use it in GitHub Desktop.
const [loginState,setLoginState]=useState();
const checkUser = async()=>{
const {data}= await supabase.from("users").select("*")
console.log(`data`,data)
}
const login = async() => {
setLoginState("Connecting to your wallet...");
if(!window.ethereum){
setLoginState("No MetaMask wallet ... Please install it");
return;
}
const provider = new ethers.provider.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts",[]);
const signer = provider.getSigner();
const walletAddr=await signer.getAddress();
setLoginState("Generating nonce...");
console.log(`walletAddr`, walletAddr)
let response =await fetch("/api/auth/nonce",{
method:"POST",
body: JSON.stringify({
walletAddr,
}),
headers:{
"Content-Type":"application/json"
}
})
const {nonce}=await response.json();
setLoginState("Please sign the nonce...");
const signature=await signer.signMessage(nonce);
console.log(`signature`,signature)
response = await fetch("/api/auth/wallet",{
method:"POST",
body:JSON.stringify({
walletAddr,
nonce,
signature,
}),
headers:{
"Content-Type":"application/json"
}
})
setLoginState("Login completed");
const data=await response.json();
console.log(`data`,data)
}
const walletApi = async(req,res)=>{
try{
const { walletAddr,signature,nonce} = req.body;
const signerAddr=ethers.utils.verifyMessage(nonce, signature);
if ( signerAddr!==walletAddr){
throw new Error ("wrong_signature");
}
let {data:user,error}= await supabase
.from('user')
.select('*')
.eq('walletAddr',walletAddr)
.eq('nonce',nonce)
.single()
const token = jwt.sign({
"aud": "authenticated",
"exp":Math.floor((Date.now() /1000) + (60*60)),
"sub" : user.id,
"user_metadata":{
id:user.id,
},
"role":"authenticated"
}, process.env.SUPABASE_JWT_SECRET);
res.status(200).json({user,token});
} catch(err){
res.status(400).json({error: err.message});
}
}
const nonceApi=async(req,res)=>{
const {walletAddr} = req.body;
const nonce = uuidv4();
let {data,error}=await supabase
.from('users')
.select('nonce')
.eq('walletAddr',walletAddr)
if(data.length>0){
let {data,error}=await supabase.from('users').update({nonce}).match({walletAddr})
} else{
let{data,error}=await supabase.from('users').insert({nonce,walletAddr})
}
console.log(`error`,error);
console.log(`data`,data);
if(error){
res.status(400).json({error:error.message})
}else{
res.status(200).json({nonce})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment