Skip to content

Commit

Permalink
fix: fixed type errors and refactored serverless functions, added str…
Browse files Browse the repository at this point in the history
…ipe as a dependency
  • Loading branch information
ErikBjare committed Nov 30, 2023
1 parent cbc3449 commit dec4ec3
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 558 deletions.
610 changes: 83 additions & 527 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"prettier": "^3.0.3",
"pug": "^3.0.2",
"sass": "^1.69.5",
"stripe": "^14.5.0",
"tailwindcss": "^3.3.5",
"typescript": "~5.2.0",
"vite": "^4.4.11",
Expand Down
4 changes: 2 additions & 2 deletions src/components/SignIn.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useAuthStore } from '../stores/auth.ts'
import { useAuthStore } from '../stores/auth'
const auth = useAuthStore()
const email = ref('')
Expand All @@ -11,7 +11,7 @@ const signIn = async () => {
try {
await auth.signIn(email.value, password.value)
console.log('User signed in:', auth.user)
} catch (error) {
} catch (error: any) {
console.error('Error signing in:', error)
errorMessage.value = error.message
}
Expand Down
6 changes: 3 additions & 3 deletions src/components/SignUp.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useAuthStore } from '../stores/auth.ts'
import router from '../router/index.ts'
import { useAuthStore } from '../stores/auth'
import router from '../router/index'
const auth = useAuthStore()
const email = ref('')
Expand All @@ -14,7 +14,7 @@ const signUp = async () => {
console.log('User signed up:', auth.user)
// Redirect to home page after successful sign up
router.push({ path: '/' })
} catch (error) {
} catch (error: any) {
console.error('Error signing up:', error)
errorMessage.value = error.message
}
Expand Down
11 changes: 8 additions & 3 deletions src/stores/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { defineStore } from 'pinia'
import { supabase } from '../supabase/init.ts'
import { supabase } from '../supabase/init'
import type { User } from '@supabase/supabase-js'

interface State {
user: User | null
}

export const useAuthStore = defineStore('auth', {
state: () => ({
state: (): State => ({
user: null
}),
actions: {
Expand Down Expand Up @@ -35,7 +40,7 @@ export const useAuthStore = defineStore('auth', {
}
},
getters: {
isLoggedIn() {
isLoggedIn(this: State) {
return !!this.user
}
}
Expand Down
28 changes: 18 additions & 10 deletions src/supabase/functions/checkSubscription/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
const { createClient } = require('@supabase/supabase-js')
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
const stripe = require('stripe')(STRIPE_SECRET_KEY)
import type { Stripe } from 'stripe'
import { supabase, stripe } from '../../init'

module.exports = async (req, res) => {
const userId = req.query.userId || req.body.userId
export default async (req: Request): Promise<Response> => {
const query = await req.json()
const userId = query.userId

if (!userId) {
return res.status(400).send('User ID is required')
return new Response('User ID is required', {
status: 400
})
}

// Fetch subscription info from Supabase
Expand All @@ -16,17 +18,23 @@ module.exports = async (req, res) => {
.eq('user_id', userId)

if (error || !data || !data.length) {
return res.status(404).send('Subscription not found')
return new Response('Subscription not found', {
status: 404
})
}

const subscriptionId = data[0].subscription_id

// Validate subscription with Stripe
const subscription = await stripe.subscriptions.retrieve(subscriptionId)
const subscription = (await stripe.subscriptions.retrieve(subscriptionId)) as Stripe.Subscription

if (!subscription || subscription.status !== 'active') {
return res.status(403).send('Subscription is not active')
return new Response('Subscription is not active', {
status: 403
})
}

return res.status(200).json({ status: 'active' })
return new Response(JSON.stringify(subscription), {
status: 200
})
}
27 changes: 15 additions & 12 deletions src/supabase/functions/stripeWebhook/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
export default async (req, res) => {
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const { createClient } = require('@supabase/supabase-js')
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY)
import { supabase, stripe } from '../../init'

const sig = req.headers['stripe-signature']
let event
const STRIPE_WEBHOOK_SECRET = import.meta.env.VITE_STRIPE_WEBHOOK_SECRET

export default async (req: Request): Promise<Response> => {
const body = await req.text()
const sig = req.headers.get('stripe-signature')!!

let event
try {
event = stripe.webhooks.constructEvent(req.rawBody, sig, process.env.STRIPE_WEBHOOK_SECRET)
} catch (err) {
event = await stripe.webhooks.constructEventAsync(body, sig, STRIPE_WEBHOOK_SECRET)
} catch (err: any) {
// Invalid signature, return error response
return res.status(400).send(`Webhook Error: ${err.message}`)
return new Response(`Webhook Error: ${err.message}`, { status: 400 })
}

// Handle the event
Expand All @@ -24,13 +25,15 @@ export default async (req, res) => {

if (error) {
console.error('Error updating subscription:', error)
return res.status(500).send('Internal Server Error')
return new Response('Internal Server Error', { status: 500 })
}

// Successful response
return res.status(200).send('Webhook received and processed successfully')
return new Response('Webhook received and processed successfully', {
status: 200
})
} else {
// Unexpected event type
return res.status(400).send(`Unhandled event type ${event.type}`)
return new Response(`Unhandled event type ${event.type}`, { status: 400 })
}
}
4 changes: 4 additions & 0 deletions src/supabase/init.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// initialize Supabase client
import { createClient } from '@supabase/supabase-js'
import Stripe from 'stripe'

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY

const stripeKey = import.meta.env.VITE_STRIPE_SECRET_KEY

export const supabase = createClient(supabaseUrl, supabaseAnonKey)
export const stripe = new Stripe(stripeKey)
2 changes: 1 addition & 1 deletion src/views/AccountView.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
import SignIn from '../components/SignIn.vue'
import SignUp from '../components/SignUp.vue'
import { useAuthStore } from '../stores/auth.ts'
import { useAuthStore } from '../stores/auth'
const auth = useAuthStore()
</script>
Expand Down

0 comments on commit dec4ec3

Please sign in to comment.