Skip to content

Commit

Permalink
Merge pull request #156 from consensusnetworks/feature/auth-lambda-setup
Browse files Browse the repository at this point in the history
Feature/auth lambda setup
  • Loading branch information
shanejearley committed Oct 14, 2022
2 parents 0044c54 + a76923c commit 6cba763
Show file tree
Hide file tree
Showing 34 changed files with 7,401 additions and 1,961 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ jobs:
env:
PUBLIC_STAGE: ${{ env.STAGE }}

- name: Build users service
run: npm run build --workspace @casimir/users
- name: Build auth service
run: npm run build --workspace @casimir/auth

- name: Test cdk stacks
run: npm run test --workspace @casimir/cdk
4 changes: 2 additions & 2 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ jobs:
env:
PUBLIC_STAGE: ${{ env.STAGE }}

- name: Build users service
run: npm run build --workspace @casimir/users
- name: Build auth service
run: npm run build --workspace @casimir/auth

- name: Deploy cdk infrastructure
run: npm run deploy
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ jobs:
- name: Build landing app
run: npm run build --workspace @casimir/landing

- name: Build users service
run: npm run build --workspace @casimir/users
- name: Build auth service
run: npm run build --workspace @casimir/auth

- name: Deploy cdk infrastructure
run: npm run deploy
Expand Down
22 changes: 8 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,37 +100,31 @@ Ethereum contract development is serviced through [Hardhat](https://hardhat.io/)
1. Compile the contracts in [contracts/ethereum](contracts/ethereum).

```zsh
npm run task:compile
npm run task:compile --workspace @casimir/ethereum
```

2. Deploy a contract, specifically [contracts/ethereum/src/Sample.sol](contracts/ethereum/src/Sample.sol) with [contracts/ethereum/deploy/sample.ts](contracts/ethereum/deploy/sample.ts).
2. Deploy a contract, specifically [contracts/ethereum/src/SSVManager.sol](contracts/ethereum/src/Sample.sol) with [contracts/ethereum/deploy/ssv.deploy.ts](contracts/ethereum/deploy/ssv.deploy.ts).

```zsh
npm run deploy:sample
npm run deploy:ssv --workspace @casimir/ethereum
```

3. Test the Sample with the tests in [contracts/ethereum/test/sample.ts](contracts/ethereum/test/sample.ts).

```zsh
npm run test:contracts
npm run test --workspace @casimir/ethereum
```

4. Print all local accounts.

```zsh
npm run task:accounts
```

6. Use a contract in a Casimir app.
4. Use a contract in the Casimir web app.

```typescript
// Todo add Casimir Typescript usage
```

7. Clean [contracts/ethereum/build/artifacts](contracts/ethereum/build/artifacts) and [contracts/ethereum/build/cache](contracts/ethereum/build/cache)).
5. Clean [contracts/ethereum/build/artifacts](contracts/ethereum/build/artifacts) and [contracts/ethereum/build/cache](contracts/ethereum/build/cache)).

```zsh
npm run task:clean
npm run task:clean --workspace @casimir/ethereum
```

> 🚩 Note, this is required if you change the Hardhat configuration.
Expand Down Expand Up @@ -226,7 +220,7 @@ Code is organized into work directories (apps, services, infrastructure – and
├── scripts/ (devops and build scripts)
| └── local/ (mock and serve tasks)
├── services/ (backend services)
| └── users/ (users lambda api)
| └── auth/ (auth lambda api)
└── package.json (project-wide npm dependencies and scripts)
```

Expand Down
38 changes: 0 additions & 38 deletions apps/landing/src/composables/users.ts

This file was deleted.

5 changes: 1 addition & 4 deletions apps/landing/src/pages/index/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { ArrowRightIcon } from '@heroicons/vue/solid'
import { ref, Ref } from 'vue'
import Puddles from '@/components/Puddles.vue'
import useSlideshow from '@/composables/slideshow'
import useUsers from '@/composables/users'
const { slideshowProgress, currentSlide } = useSlideshow()
const { signupUser } = useUsers()
const successMessage: Ref = ref<HTMLDivElement>()
const invalidMessage: Ref = ref<HTMLDivElement>()
Expand All @@ -27,8 +25,7 @@ async function onSubmit() {
const newEmail = email.value
email.value = ''
successMessage.value.style.display = 'block'
const res = await signupUser(newEmail)
console.log('Signup result', await res.json())
console.log('Email signup API removed. You sent', newEmail)
} catch (err) {
console.log('Signup error', err)
}
Expand Down
39 changes: 39 additions & 0 deletions apps/web/src/composables/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { LoginCredentials } from '@casimir/types'

export default function useAuth() {

/**
* Logs a user in with an address, message and signed message
*
* @param {LoginCredentials} loginCredentials - The user's address, message and signed message
* @returns {Promise<Response>} - The response from the login request
*/
async function login(loginCredentials: LoginCredentials): Promise<Response> {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(loginCredentials)
}
const authBaseUrl = _getAuthBaseUrl()
return await fetch(`${authBaseUrl}/login`, requestOptions)
}

/**
* Get the auth base url for the current environment
*
* @returns {string} The base URL for the auth API
*/
function _getAuthBaseUrl(): string {
if (import.meta.env.PUBLIC_MOCK) {
return `http://localhost:${import.meta.env.PUBLIC_AUTH_PORT}`
} else {
return `https://auth.${import.meta.env.PUBLIC_STAGE || 'dev'}.casimir.co`
}
}

return {
login
}
}
7 changes: 7 additions & 0 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { TransactionInit } from '@/interfaces/TransactionInit'
import { MessageInit } from '@/interfaces/MessageInit'
import { TransactionRequest } from '@ethersproject/abstract-provider'
import { Deferrable } from '@ethersproject/properties'
import useAuth from '@/composables/auth'

const defaultProviders = {
MetaMask: undefined,
Expand Down Expand Up @@ -62,6 +63,12 @@ export default function useEthers() {
new ethers.providers.Web3Provider(browserProvider as EthersProvider)
const signer = web3Provider.getSigner()
const signature = await signer.signMessage(hashedMessage)

// Todo move this sample code
const { login } = useAuth()
const response = await login({ address: signer._address, message: hashedMessage, signedMessage: signature })
console.log('Response', await response.json()) // Currently the response is always false

return signature
}

Expand Down
5 changes: 5 additions & 0 deletions common/types/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "@casimir/types",
"private": true,
"main": "src/index.ts"
}
2 changes: 2 additions & 0 deletions common/types/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { LoginCredentials } from './interfaces/LoginCredentials'
export type { LoginCredentials }
5 changes: 5 additions & 0 deletions common/types/src/interfaces/LoginCredentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface LoginCredentials {
address: string;
message: string;
signedMessage: string;
}
3 changes: 1 addition & 2 deletions contracts/ethereum/deploy/ssv.deploy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import hre from 'hardhat'
import { ethers } from 'hardhat'
import { SSVManager } from '@casimir/ethereum/build/artifacts/types'
const { ethers } = hre

async function main() {
const factory = await ethers.getContractFactory('SSVManager')
Expand Down
6 changes: 3 additions & 3 deletions contracts/ethereum/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"scripts": {
"dev:node": "npx hardhat node",
"deploy:ssv": "npx hardhat run deploy/ssv.deploy.ts",
"test:contracts": "npx hardhat test",
"test": "mocha --require hardhat/register --recursive --exit --extension ts --timeout 15000",
"task:clean": "npx hardhat clean",
"task:compile": "npm run task:clean && npx hardhat compile",
"postinstall": "npm run task:compile"
Expand All @@ -19,9 +19,9 @@
"@types/mocha": "^9.1.1",
"@types/node": "^17.0.45",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"hardhat": "^2.9.9",
"hardhat": "^2.12.0",
"localtunnel": "^2.0.2",
"mocha": "^10.0.0",
"ts-node": "^10.8.2",
"typechain": "^8.1.0"
}
Expand Down
5 changes: 2 additions & 3 deletions contracts/ethereum/test/ssv.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import hre from 'hardhat'
import { ethers } from 'hardhat'
import { loadFixture } from '@nomicfoundation/hardhat-network-helpers'
import { expect } from 'chai'
import { SSVManager } from '@casimir/ethereum/build/artifacts/types'
const { ethers } = hre

/** Fixture to deploy SSV manager contract */
async function deploymentFixture() {
Expand Down Expand Up @@ -43,7 +42,7 @@ async function thirdUserDepositFixture() {
return { contract, firstUser, owner, secondUser, thirdUser }
}

describe('SSV Manager', async function () {
describe('SSV manager', async function () {

it('First user\'s deposit of 16 ETH should open the first pool', async function () {
const { contract } = await loadFixture(firstUserDepositFixture)
Expand Down
4 changes: 2 additions & 2 deletions infrastructure/cdk/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'source-map-support/register'
import * as cdk from 'aws-cdk-lib'
import { pascalCase } from '@casimir/helpers'
import { LandingStack } from '../lib/landing/landing-stack'
import { UsersStack } from '../lib/users/users-stack'
import { AuthStack } from '../lib/auth/auth-stack'
import { DnsStack } from '../lib/dns/dns-stack'
import { EtlStack } from '../lib/etl/etl-stack'

Expand All @@ -19,6 +19,6 @@ if (!process.env.PROJECT || !process.env.STAGE) {
const dnsStack = new DnsStack(app, `${project}DnsStack${stage}`, { env: defaultEnv, project, stage })
const { domain, dnsRecords, hostedZone } = dnsStack
new EtlStack(app, `${project}EtlStack${stage}`, { env: defaultEnv, project, stage })
new UsersStack(app, `${project}UsersStack${stage}`, { env: defaultEnv, project, stage, domain, dnsRecords, hostedZone })
new AuthStack(app, `${project}AuthStack${stage}`, { env: defaultEnv, project, stage, domain, dnsRecords, hostedZone })
new LandingStack(app, `${project}LandingStack${stage}`, { env: defaultEnv, project, stage, domain, dnsRecords, hostedZone })
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as route53targets from 'aws-cdk-lib/aws-route53-targets'
import * as route53 from 'aws-cdk-lib/aws-route53'
import * as certmgr from 'aws-cdk-lib/aws-certificatemanager'

export interface UsersStackProps extends StackProps {
export interface AuthStackProps extends StackProps {
project: string;
stage: string;
domain: string;
Expand All @@ -16,29 +16,29 @@ export interface UsersStackProps extends StackProps {
}

/**
* Class representing the users stack.
* Class representing the auth stack.
*
* Shortest name: {@link UsersStack}
* Full name: {@link (UsersStack:class)}
* Shortest name: {@link AuthStack}
* Full name: {@link (AuthStack:class)}
*/
export class UsersStack extends Stack {
export class AuthStack extends Stack {

public readonly service: string = 'Users'
public readonly assetPath: string = '../../services/users/dist'
public readonly service: string = 'Auth'
public readonly assetPath: string = '../../services/auth/dist'

/**
* UsersStack class constructor.
* AuthStack class constructor.
*
* Shortest name: {@link (UsersStack:constructor)}
* Full name: {@link (UsersStack:constructor)}
* Shortest name: {@link (AuthStack:constructor)}
* Full name: {@link (AuthStack:constructor)}
*/
constructor(scope: Construct, id: string, props: UsersStackProps) {
constructor(scope: Construct, id: string, props: AuthStackProps) {

/**
* UsersStack class constructor super method.
* AuthStack class constructor super method.
*
* Shortest name: {@link (UsersStack:constructor:super)}
* Full name: {@link (UsersStack:constructor:super)}
* Shortest name: {@link (AuthStack:constructor:super)}
* Full name: {@link (AuthStack:constructor:super)}
*/
super(scope, id, props)

Expand All @@ -50,7 +50,7 @@ export class UsersStack extends Stack {
const certificate = new certmgr.DnsValidatedCertificate(this, `${project}${this.service}Cert${stage}`, {
domainName: serviceDomain,
subjectAlternativeNames: [
[dnsRecords.users, serviceDomain].join('.')
[dnsRecords.auth, serviceDomain].join('.')
],
hostedZone,
region: 'us-east-2'
Expand All @@ -67,24 +67,13 @@ export class UsersStack extends Stack {
timeout: Duration.seconds(25)
})

const pinpointPolicy = new iam.PolicyStatement({
actions: ['mobiletargeting:*', 'mobileanalytics:*'],
resources: ['*'],
})

lambdaHandler.role?.attachInlinePolicy(
new iam.Policy(this, `${project}${this.service}PinpointPolicy${stage}`, {
statements: [pinpointPolicy]
})
)

// Todo update to use new api gateway version when stable
// https://docs.aws.amazon.com/cdk/api/v2/docs/aws-apigateway-readme.html#apigateway-v2
const apiGateway = new apigateway.LambdaRestApi(this, `${project}${this.service}ApiGateway${stage}`, {
restApiName: `${project}${this.service}Gateway${stage}`,
handler: lambdaHandler,
domainName: {
domainName: [dnsRecords.users, serviceDomain].join('.'),
domainName: [dnsRecords.auth, serviceDomain].join('.'),
certificate
},
defaultCorsPreflightOptions: {
Expand All @@ -95,7 +84,7 @@ export class UsersStack extends Stack {
})

new route53.ARecord(this, `${project}${this.service}DnsARecordApi${stage}`, {
recordName: [dnsRecords.users, serviceDomain].join('.'),
recordName: [dnsRecords.auth, serviceDomain].join('.'),
zone: hostedZone as route53.IHostedZone,
target: route53.RecordTarget.fromAlias(new route53targets.ApiGateway(apiGateway)),
ttl: Duration.minutes(1),
Expand Down
2 changes: 1 addition & 1 deletion infrastructure/cdk/lib/dns/dns-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class DnsStack extends Stack {
const dnsRecords = {
wildcard: '*',
landing: 'www',
users: 'users'
auth: 'auth'
}

const hostedZone = route53.HostedZone.fromLookup(this, `${project}${this.service}HostedZone${stage}`, {
Expand Down
Loading

0 comments on commit 6cba763

Please sign in to comment.