Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update/siwe #326

Merged
merged 2 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 1 addition & 23 deletions apps/web/src/components/Wallet.vue
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
<template>
<div>
<div class="flex">
<button @click="getUserBalance()">
Get User Balance
</button>
</div>
<div class="network-div w-100 mx-8">
Choose Network
<div class="choose-network flex">
Expand Down Expand Up @@ -44,22 +39,6 @@
<button @click="getPools(selectedAddress, 'stake')">
Get staked user pools
</button>
<!-- <ul>
<li
v-for="(account, index) in user?.accounts"
:key="index"
>
<ul v-for="(pool, index) in account"
:key="index"
>
<li>Pool ID: #{{ pool?.id }}</li>
<li>Your Stake: {{ pool?.userStake }} ETH</li>
<li>Your Rewards: {{ pool?.userRewards }} ETH</li>
<li>Total Stake: {{ pool?.stake }} ETH</li>
<li>Total Rewards: {{ pool?.rewards }} ETH</li>
</ul>
</li>
</ul> -->
<input
v-model="amountToStake"
placeholder="Amount to Stake"
Expand Down Expand Up @@ -184,9 +163,9 @@

<script setup lang="ts">
import { ref, watchEffect, onMounted } from 'vue'
import useWallet from '@/composables/wallet'
import useSSV from '@/composables/ssv'
import useUsers from '@/composables/users'
import useWallet from '@/composables/wallet'

const message = ref('')
const signedMessage = ref('')
Expand Down Expand Up @@ -217,7 +196,6 @@ const {
setPrimaryWalletAccount,
sendTransaction,
signMessage,
getUserBalance,
removeConnectedAccount,
switchNetwork
} = useWallet()
Expand Down
56 changes: 44 additions & 12 deletions apps/web/src/composables/auth.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
import useEnvironment from '@/composables/environment'
import { LoginCredentials, ProviderString } from '@casimir/types'
import { LoginCredentials } from '@casimir/types'

const { usersBaseURL } = useEnvironment()
const { domain, origin, usersBaseURL } = useEnvironment()

export default function useAuth() {

/**
* Gets a message from the server to sign
* Creates the message from the server to sign, which includes getting the nonce from auth server
*
* @param {ProviderString} provider - The provider the user is using to sign in
* @param {string} address - The user's address
* @param {ProviderString} address - The address the user is using to sign in
* @param {string} statement - The statement the user is signing
* @returns {Promise<Response>} - The response from the message request
*/
async function getMessage(provider: ProviderString, address: string) {
async function createSiweMessage(address: string, statement: string) {
const requestOptions = {
method: 'GET',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
},
body: JSON.stringify({
address
})
}
return await fetch(`${usersBaseURL}/auth/message/${provider}/${address}`, requestOptions)
const res = await fetch(`${usersBaseURL}/auth/nonce`, requestOptions)
const { nonce } = (await res.json())
const message = {
domain,
address,
statement,
uri: origin,
version: '1',
chainId: 5,
nonce
}
return prepareMessage(message)
}

/**
Expand All @@ -28,7 +43,7 @@ export default function useAuth() {
* @param {LoginCredentials} loginCredentials - The user's address, provider, currency, message, and signed message
* @returns {Promise<Response>} - The response from the login request
*/
async function login(loginCredentials: LoginCredentials) {
async function signInWithEthereum(loginCredentials: LoginCredentials) {
const requestOptions = {
method: 'POST',
headers: {
Expand All @@ -40,7 +55,24 @@ export default function useAuth() {
}

return {
login,
getMessage
createSiweMessage,
signInWithEthereum
}
}

function prepareMessage(obj: any) {
const {
domain,
address,
statement,
uri,
version,
chainId,
nonce,
} = obj

const issuedAt = new Date().toISOString()
const message = `${domain} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}\n\nURI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}\nNonce: ${nonce}\nIssued At: ${issuedAt}`

return message
}
4 changes: 4 additions & 0 deletions apps/web/src/composables/environment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export default function useEnvironment() {
const domain = window.location.host
const origin = window.location.origin
const usersBaseURL = getUsersBaseURL()
const ethereumURL = import.meta.env.PUBLIC_ETHEREUM_URL || 'http://127.0.0.1:8545'
const ledgerType = import.meta.env.PUBLIC_SPECULOS_PORT ? 'speculos' : 'usb'
Expand All @@ -20,6 +22,8 @@ export default function useEnvironment() {
}
}
return {
domain,
origin,
usersBaseURL,
ethereumURL,
ledgerType,
Expand Down
16 changes: 8 additions & 8 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Currency, ProviderString } from '@casimir/types'
import useAuth from '@/composables/auth'
import useEnvironment from '@/composables/environment'

const { getMessage, login } = useAuth()
const { createSiweMessage, signInWithEthereum } = useAuth()
const { ethereumURL } = useEnvironment()

const defaultProviders = {
Expand Down Expand Up @@ -103,15 +103,15 @@ export default function useEthers() {
const browserProvider = availableProviders.value[provider as keyof BrowserProviders]
const web3Provider: ethers.providers.Web3Provider = new ethers.providers.Web3Provider(browserProvider as EthersProvider)
try {
const { message } = await (await getMessage(provider, address)).json()
const message = await createSiweMessage(address, 'Sign in with Ethereum to the app.')
const signer = web3Provider.getSigner()
const signature = await signer.signMessage(message)
const ethersLoginResponse = await login({
const signedMessage = await signer.signMessage(message)
const ethersLoginResponse = await signInWithEthereum({
address,
currency,
message,
provider,
address,
message: message.toString(),
signedMessage: signature,
currency
signedMessage
})
return await ethersLoginResponse.json()
} catch (err) {
Expand Down
10 changes: 4 additions & 6 deletions apps/web/src/composables/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,12 @@ export default function useWallet() {
* @returns
*/
async function connectWallet(provider: ProviderString, currency: Currency = 'ETH') {
console.clear()
try { // Sign Up or Login
if (!user?.value?.address) {
const connectedAddress = await getConnectedAddressFromProvider(provider, currency) as string
const connectedCurrency = await detectCurrencyInProvider(provider) as Currency
await loginWithWallet(provider, connectedAddress, connectedCurrency)
await login(provider, connectedAddress, connectedCurrency)
const userResponse = await getUser()
if (!userResponse?.error) {
setUser(userResponse)
Expand All @@ -92,19 +93,16 @@ export default function useWallet() {
}
loadingUserWallets.value = false
router.push('/')
} else { // Add account
console.log('already logged in')
} else { // Add account if it doesn't already exist
const connectedAddress = await getConnectedAddressFromProvider(provider, currency) as string
const connectedCurrency = await detectCurrencyInProvider(provider, currency) as Currency
const accountExists = user.value?.accounts?.some((account: Account | any) => account?.address === connectedAddress && account?.walletProvider === provider)
console.log('accountExists already exists on user :>> ', accountExists)
if (accountExists) {
alert('Account already exists; setting provider, address, and currency')
setSelectedProvider(provider)
setSelectedAddress(connectedAddress)
setSelectedCurrency(connectedCurrency)
} else {
// If account doesn't exist, add account using users api
console.log('adding sub account')
const account = {
userId: user?.value?.id,
Expand Down Expand Up @@ -227,7 +225,7 @@ export default function useWallet() {
* @param currency
* @returns
*/
async function loginWithWallet(provider: ProviderString, address: string, currency: Currency) {
async function login(provider: ProviderString, address: string, currency: Currency) {
if (ethersProviderList.includes(provider)) {
return await loginWithEthers(provider, address, currency)
} else if (provider === 'Ledger') {
Expand Down
Loading