-
Notifications
You must be signed in to change notification settings - Fork 0
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
feat: invite user, admin setup #132
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# Supabase | ||
|
||
昨年に続いて [Supabase](https://supabase.com/) のお世話になります。 | ||
|
||
## 環境構築 | ||
|
||
ダッシュボードより各種変数を発行、手元の環境でそれらを使えるよう準備します。 | ||
|
||
データベースへの追加、更新する際は URL (SUPABASE_URL) と Anon Key (SUPABASE_KEY) が必要となります。 | ||
|
||
```.env | ||
SUPABASE_URL= | ||
SUPABASE_KEY= | ||
``` | ||
|
||
[`useRuntimeConfig`](https://nuxt.com/docs/api/composables/use-runtime-config) を利用して、各種変数へアクセスできることを確認してください。 | ||
|
||
```ts | ||
export default defineNuxtConfig({ | ||
runtimeConfig: { | ||
public: { | ||
supabaseUrl: process.env.SUPABASE_URL, | ||
supabaseKey: process.env.SUPABASE_KEY, | ||
serviceKey: process.env.SERVICE_KEY, | ||
}, | ||
}, | ||
}) | ||
``` | ||
|
||
なお、ここで supabase.redirect に `false` を設定しないと、強制的にログイン画面へ遷移されるようになっています。 | ||
|
||
```ts | ||
export default defineNuxtConfig({ | ||
supabase: { | ||
redirect: false, | ||
}, | ||
}) | ||
``` | ||
|
||
## メールアドレスを使って招待 | ||
|
||
[`inviteUserByEmail`](https://supabase.com/docs/reference/javascript/auth-admin-inviteuserbyemail) のお世話になります。事前に Supabase の Auth Admin クライアントを作成する必要があり、直接 Web ブラウザからそれを操作することができません。 | ||
|
||
Service Role Key も発行しつつ、合わせてこちらも `useRuntimeConfig` を利用してアクセスできることを確認してください。 | ||
|
||
```ts | ||
import { defineEventHandler, useRuntimeConfig } from '#imports' | ||
import { createClient } from '@supabase/supabase-js' | ||
|
||
export default defineEventHandler(async (event) => { | ||
const config = useRuntimeConfig() | ||
const supabaseUrl = config.public.supabaseUrl | ||
const serviceKey = config.public.serviceKey | ||
|
||
if (!supabaseUrl || !serviceKey) { | ||
return event.node.res.end('No authentication') | ||
} | ||
|
||
const supabase = createClient(supabaseUrl, serviceKey) | ||
const { error } = await supabase.auth.admin.inviteUserByEmail(email) | ||
|
||
if (error) { | ||
return event.node.res.end(error) | ||
} | ||
}) | ||
``` | ||
|
||
raw_user_meta_data に `{ user_role: 'admin' }` を付与しつつ、それが追加された時に限って public.admin_users へデータが insert される設計を取りました。 | ||
|
||
```ts | ||
const { error } = await supabase.auth.admin.inviteUserByEmail( | ||
email, | ||
{ data: { user_role: 'admin' } }, | ||
) | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<script setup lang="ts"> | ||
import type { AdminPage } from '@vuejs-jp/model' | ||
|
||
interface ListProps { | ||
page: AdminPage | ||
} | ||
|
||
const props = defineProps<ListProps>() | ||
|
||
const pageText = props.page.replace(/^[a-z]/g, function (val) { | ||
return val.toUpperCase() | ||
}) | ||
</script> | ||
|
||
<template> | ||
<div class="tab-content"> | ||
<h2>{{ pageText }}</h2> | ||
</div> | ||
</template> | ||
|
||
<style scoped> | ||
.tab-content { | ||
margin: 0 1.5%; | ||
} | ||
</style> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { useSupabaseClient } from '#imports' | ||
import type { AuthProvider, RedirectPath } from '@vuejs-jp/model' | ||
import { REDIRECT_URL } from '~/utils/environment.constants' | ||
|
||
export function useAuth() { | ||
const supabase = useSupabaseClient() | ||
|
||
async function signIn(provider: AuthProvider, path: RedirectPath) { | ||
const { error } = await supabase.auth.signInWithOAuth({ | ||
provider, | ||
options: { | ||
redirectTo: `${REDIRECT_URL}${path}`, | ||
} | ||
}) | ||
if (error) console.log(error) | ||
} | ||
|
||
async function signOut() { | ||
const { error } = await supabase.auth.signOut() | ||
if (error) { | ||
throw new Error('can not signout') | ||
} | ||
} | ||
|
||
return { signIn, signOut } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { createClient, type AuthChangeEvent } from '@supabase/supabase-js' | ||
import { match } from 'ts-pattern' | ||
import { useRuntimeConfig } from '#imports' | ||
import { computed, ref } from 'vue' | ||
|
||
export function useAuthSession() { | ||
const config = useRuntimeConfig() | ||
const supabaseUrl = config.public.supabaseUrl | ||
const supabaseKey = config.public.supabaseKey | ||
|
||
let _onAuthChanged: (e: AuthChangeEvent) => void = () => {} | ||
const onAuthChanged = (callback: (e: AuthChangeEvent) => void) => { | ||
_onAuthChanged = callback | ||
} | ||
|
||
if (!supabaseUrl || !supabaseKey) { | ||
return { signedUserId: null, onAuthChanged } | ||
} | ||
const supabase = createClient(supabaseUrl, supabaseKey) | ||
|
||
const signedUserId = ref<string | null>(null) | ||
const setSignedUserId = (target: string | null) => signedUserId.value = target | ||
|
||
const hasAuth = computed(() => signedUserId.value !== null) | ||
|
||
supabase.auth.onAuthStateChange((e, session) => { | ||
match(e) | ||
.with('INITIAL_SESSION', 'SIGNED_IN', () => { | ||
if (session?.user) setSignedUserId(session.user.id) | ||
_onAuthChanged(e) | ||
}) | ||
.with('SIGNED_OUT', () => { | ||
setSignedUserId(null) | ||
}) | ||
.with( | ||
'MFA_CHALLENGE_VERIFIED', | ||
'PASSWORD_RECOVERY', | ||
'TOKEN_REFRESHED', | ||
'USER_UPDATED', | ||
() => {}, | ||
) | ||
.exhaustive() | ||
}) | ||
|
||
return { hasAuth, onAuthChanged } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { computed, ref } from 'vue' | ||
import { useFormError } from './useFormError' | ||
|
||
export function useInvitation() { | ||
const email = ref('') | ||
const id = ref('') | ||
const { ...rest } = useFormError() | ||
|
||
const isSubmittingId = computed(() => { | ||
if (!id.value) return false | ||
return rest.idError.value === '' | ||
}) | ||
|
||
const isSubmittingEmail = computed(() => { | ||
if (!email.value) return false | ||
return rest.emailError.value === '' | ||
}) | ||
|
||
async function publish(type: 'invite' | 'delete', target: string) { | ||
await $fetch(`/api/${type}-user`, { | ||
method: 'post', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
'Access-Control-Allow-Origin': '*', | ||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', | ||
}, | ||
body: JSON.stringify(type === 'invite' ? { email: target } : { id: target }), | ||
}) | ||
} | ||
|
||
return { publish, isSubmittingId, isSubmittingEmail, email, id, ...rest } | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
最後のreturnにあわせて
にするか、
がよいかと思いました。
今のところ signedUserId を使わないのであれば返却しなくてもよいかもしれないです。
2つのreturnの中身を統一すべきかと思います
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ご確認いただきありがとうございます!
おっしゃるように signedUserId は使用されていませんので、削除しておきました mm