Skip to content

Commit

Permalink
feat: add rotateKey functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
0xbrayo committed Jul 31, 2024
1 parent 76c2e34 commit cff632f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/components/Apikey.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<h1>API Key</h1>
<p>Your API key is: {{ apiKey }} <ContentCopyIcon @click ="copyApikey"/></p>
<SnackBarVue :message="snackbarMessage" ref="snackbar"/>
<button @click="rotateKey">Rotate Key</button>
</div>
<!--TODO: Add rotate key -->
</template>

<script setup lang="ts">
Expand All @@ -27,6 +27,11 @@ const copyApikey = () => {
snackbarMessage.value = 'ApiKey copied to clipboard'
}
const rotateKey = () => {
store.rotateKey()
snackbarMessage.value = 'ApiKey rotated'
}
</script>

<style scoped></style>
20 changes: 20 additions & 0 deletions src/firebase/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ import {
query,
where
} from 'firebase/firestore/lite'
import { getFunctions, httpsCallable } from "firebase/functions";
import type { ScreenTimeData, ScreenTimeSummary } from '@/types'

const functions = getFunctions();

export function dataToSummary(data: ScreenTimeData): ScreenTimeSummary {
const total = data.events.reduce((acc, event) => acc + event.duration, 0)
const categoryTotals: { [key: string]: number } = {}
Expand Down Expand Up @@ -121,3 +124,20 @@ export async function getApiKey(userId: string): Promise<string | null> {
return null
}
}

interface ApiResponse {
apiKey: string;
}

export async function rotateKey(userId: string): Promise<string | null> {
// invoke a callable function to rotate the user's api key
// this function is defined in functions/src/index.ts
const rotateApiKey = httpsCallable(functions, 'rotateApiKey')
const key = rotateApiKey({ userId: userId }).then((result) => {
return (result.data as ApiResponse)?.apiKey;
}).catch((error) => {
console.error(error)
return null
})
return key
}
13 changes: 11 additions & 2 deletions src/stores/apikey.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineStore } from 'pinia'
import { getApiKey } from '@/firebase/data'
import { getApiKey, rotateKey as rotateKeyCallable } from '@/firebase/data'
import { useAuthStore } from './auth'
import { ref } from 'vue'

Expand All @@ -12,7 +12,16 @@ export const useApiKeyStore = defineStore('apikey', () => {
apikey.value = key
})
}
return { apikey, fetchKey }
function rotateKey() {
const userId = useAuthStore().user!.uid
rotateKeyCallable(userId).then((key) => {
console.log('Key is now', key)
if (key != null) {
apikey.value = key
}
})
}
return { apikey, fetchKey, rotateKey }
},
{
persist: true
Expand Down

0 comments on commit cff632f

Please sign in to comment.