Skip to content

Commit

Permalink
fix(better-auth): add some docs, fix some starter missing deps, fix p…
Browse files Browse the repository at this point in the history
…assing jwt to zero
  • Loading branch information
natew committed Dec 22, 2024
1 parent 078778e commit 117bb33
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 24 deletions.
2 changes: 1 addition & 1 deletion apps/chat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"@dnd-kit/sortable": "^10.0.0",
"@docsearch/react": "^3.6.1",
"@floating-ui/react": "^0.27.0",
"@rocicorp/zero": "^0.9.2024121900",
"@rocicorp/zero": "0.9.2024121900",
"@tamagui/helpers-icon": "^1.120.2",
"@tamagui/linear-gradient": "^1.120.2",
"@tamagui/lucide-icons": "^1.120.2",
Expand Down
19 changes: 19 additions & 0 deletions apps/chat/src/helpers/pluralize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
let pluralRules = new Intl.PluralRules('en-US')

export function pluralize(count: number, singular: string, plural: string) {
const grammaticalNumber = pluralRules.select(count)
switch (grammaticalNumber) {
case 'one':
return `${count} ${singular}`
case 'other':
return `${count} ${plural}`
default:
throw new Error(
`Can't pluralize: ${grammaticalNumber} for ${count} / ${singular} / ${plural}`
)
}
}

export function setPluralizeLocale(locale: Intl.LocalesArgument) {
pluralRules = new Intl.PluralRules(locale)
}
9 changes: 6 additions & 3 deletions apps/chat/src/interface/settings/ServerSettingsPane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { DevTools } from '~/dev/DevTools'
import { randomID } from '~/helpers/randomID'
import { hiddenPanelWidth } from '~/interface/settings/constants'
import { useCurrentServer, useCurrentServerRoles } from '~/state/server'
import type { Role, Server } from '~/zero/schema'
import type { Role, RoleWithRelations, Server, User } from '~/zero/schema'
import { mutate } from '~/zero/zero'
import { Avatar } from '../Avatar'
import { ButtonSimple } from '../ButtonSimple'
Expand Down Expand Up @@ -165,11 +165,14 @@ const SettingsServerPermissions = ({ server }: { server: Server }) => {
)
}

const RoleListItem = ({ role, ...rest }: Omit<EditableListItemProps, 'role'> & { role?: Role }) => {
const RoleListItem = ({
role,
...rest
}: Omit<EditableListItemProps, 'role'> & { role?: RoleWithRelations }) => {
return (
<EditableListItem
icon={<Circle size={24} bg={role?.color || 'gray'} />}
after={<SizableText>3 members</SizableText>}
after={<SizableText>{role?.members?.length} members</SizableText>}
{...rest}
>
{role?.name || ''}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ type ServerChannelSort = string[]
export const SidebarServerChannelsList = () => {
const { user } = useAuth()
const server = useCurrentServer()
console.log('server', server)
const channels = useServerChannels()
const channelSort: ServerChannelSort =
Array.isArray(server?.channelSort) && server.channelSort.length
Expand Down
7 changes: 5 additions & 2 deletions apps/chat/src/state/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ export const useCurrentServer = () => {

export const useCurrentServerRoles = () => {
const [userState] = useUserState()
return useQuery((q) => q.server.where('id', userState?.activeServer || '').related('roles'))[0][0]
?.roles
return useQuery((q) =>
q.server
.where('id', userState?.activeServer || '')
.related('roles', (r) => r.related('members'))
)[0][0]?.roles
}

export const useCurrentServerMembership = () => {
Expand Down
2 changes: 2 additions & 0 deletions apps/chat/src/zero/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,8 @@ export type Role = Row<typeof roleSchema>
export type UserRole = Row<typeof userRoleSchema>
export type ChannelRole = Row<typeof channelRoleSchema>

export type RoleWithRelations = Role & { members: readonly User[] }

export type MessageWithRelations = Message & {
reactions: readonly Reaction[]
thread?: readonly Thread[]
Expand Down
4 changes: 4 additions & 0 deletions examples/one-zero/app/_layout.css
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ body > div {
}

a {
text-decoration: none;
}

p a {
color: inherit;
text-decoration: underline;
text-decoration-thickness: 2px;
Expand Down
2 changes: 2 additions & 0 deletions examples/one-zero/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export default function HomePage() {
<Avatar image={user.image || ''} />
<SizableText>{user.name}</SizableText>

<Button onPress={() => authClient.signOut()}>Logout</Button>

{isWeb && !isTauri && jwtToken && (
<a href={`one-chat://finish-auth?token=${session?.token}`}>
<Button>Login in Tauri</Button>
Expand Down
4 changes: 3 additions & 1 deletion examples/one-zero/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"zero:build-schema": "cd ./src/zero && zero-build-schema -p './schema.ts'"
},
"dependencies": {
"@rocicorp/zero": "^0.9.2024121900",
"@rocicorp/zero": "0.9.2024121900",
"@tamagui/config": "^1.120.2",
"@tamagui/linear-gradient": "^1.120.2",
"@tamagui/lucide-icons": "^1.120.2",
Expand All @@ -48,6 +48,8 @@
"tamagui": "^1.120.2"
},
"devDependencies": {
"@types/node": "^22.1.0",
"vite": "^6.0.5",
"@tamagui/vite-plugin": "^1.120.2",
"@tauri-apps/cli": "^2",
"tsx": "^4.19.0"
Expand Down
19 changes: 13 additions & 6 deletions examples/one-zero/src/better-auth/AuthEffects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ export const AuthEffects = () => {
}

const useAuthPassJWTSecretToZeroEffect = () => {
const { jwtToken } = useAuth()
const { jwtToken, user } = useAuth()

useEffect(() => {
if (jwtToken) {
setZeroAuth(jwtToken)
if (user && jwtToken) {
setZeroAuth({
jwtToken,
userID: user.id,
})
}
}, [jwtToken])
}, [user, jwtToken])
}

const useAuthPassTokenToTauriEffect = () => {
Expand All @@ -32,9 +35,13 @@ const useAuthPassTokenToTauriEffect = () => {
switch (url.host) {
case 'finish-auth': {
const token = url.searchParams.get('token')
const session = url.searchParams.get('session')

if (token) {
setAuthClientToken(token)
if (token && session) {
setAuthClientToken({
token,
session,
})
}

break
Expand Down
31 changes: 24 additions & 7 deletions packages/better-auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,35 @@ interface StorageKeys {
session: string
}

interface AuthClientConfig {
options?: ClientOptions
interface ExtraConfig {
storageKeys?: StorageKeys
}

export function createBetterAuthClient(config: AuthClientConfig = {}) {
/**
*
* This is a very early package to lightly abstract better-auth/client to work well with:
* - React and React Native
* - jwt tokens
*
* 1. Stores the session and jwt configuration locally and restores from it if existing
* 2. Provides a useAuth hook that automatically fetches jwt token for you
*
* @param options better-auth/client createAuthClient optinos
* @param extraConfig for setting localStorage keys
* @returns
*/
export function createBetterAuthClient(
options: ClientOptions = {},
{ storageKeys }: ExtraConfig = {}
) {
const keys = {
token: config.storageKeys?.token ?? 'TOKEN_KEY',
session: config.storageKeys?.session ?? 'SESSION_KEY',
token: storageKeys?.token ?? 'TOKEN_KEY',
session: storageKeys?.session ?? 'SESSION_KEY',
}

const createAuthClientWithSession = (session: string) => {
return createAuthClient({
...config.options,
...options,
fetchOptions: {
headers: {
Authorization: `Bearer ${session}`,
Expand All @@ -33,7 +48,9 @@ export function createBetterAuthClient(config: AuthClientConfig = {}) {
let authClient = (() => {
const existingSession =
typeof localStorage !== 'undefined' ? localStorage.getItem(keys.session) : ''
return existingSession ? createAuthClientWithSession(existingSession) : createAuthClient()
return existingSession
? createAuthClientWithSession(existingSession)
: createAuthClient(options)
})()

const authClientVersion = createEmitter<number>()
Expand Down
3 changes: 3 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
{
"path": "examples/one-fullstack"
},
{
"path": "examples/one-zero"
},
{
"path": "examples/bare"
}
Expand Down
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7525,7 +7525,7 @@ __metadata:
languageName: node
linkType: hard

"@rocicorp/zero@npm:^0.9.2024121900":
"@rocicorp/zero@npm:0.9.2024121900":
version: 0.9.2024121900
resolution: "@rocicorp/zero@npm:0.9.2024121900"
dependencies:
Expand Down Expand Up @@ -22014,7 +22014,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "one-zero@workspace:examples/one-zero"
dependencies:
"@rocicorp/zero": "npm:^0.9.2024121900"
"@rocicorp/zero": "npm:0.9.2024121900"
"@tamagui/config": "npm:^1.120.2"
"@tamagui/linear-gradient": "npm:^1.120.2"
"@tamagui/lucide-icons": "npm:^1.120.2"
Expand Down Expand Up @@ -22125,7 +22125,7 @@ __metadata:
"@dnd-kit/sortable": "npm:^10.0.0"
"@docsearch/react": "npm:^3.6.1"
"@floating-ui/react": "npm:^0.27.0"
"@rocicorp/zero": "npm:^0.9.2024121900"
"@rocicorp/zero": "npm:0.9.2024121900"
"@tamagui/helpers-icon": "npm:^1.120.2"
"@tamagui/linear-gradient": "npm:^1.120.2"
"@tamagui/lucide-icons": "npm:^1.120.2"
Expand Down

0 comments on commit 117bb33

Please sign in to comment.