misc: add basic auth system

This commit is contained in:
Xyphyn committed 2023-08-01 10:43:36 -07:00
1 parent 1d9bfb44fd
commit 55a047ab73
2 files changed
+131 -6

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import { DEFAULT_INSTANCE_URL, getClient } from '$lib/lemmy.js'
import type { MyUserInfo } from 'lemmy-js-client'
import { get, writable } from 'svelte/store'
function getFromStorage<T>(key: string): T | undefined {
const lc = localStorage.getItem(key)
if (!lc) return undefined
return JSON.parse(lc)
}
function setFromStorage(key: string, item: any) {
return localStorage.setItem(key, JSON.stringify(item))
}
interface Profile {
id: number
instance: string
jwt?: string
user?: PersonData
}
/**
* What gets stored in localstorage.
*/
interface ProfileData {
profiles: Profile[]
profile: number
}
interface PersonData extends MyUserInfo {
unreads: number
reports: number
}
export const profileData = writable<ProfileData>({ profiles: [], profile: -1 })
export const profile = writable<Profile | undefined>({
id: -1,
instance: DEFAULT_INSTANCE_URL,
})
profileData.subscribe((pd) => {
setFromStorage('profileData', pd)
})
profile.subscribe(async (p) => {
if (!p || !p.jwt) {
profileData.update((pd) => ({ ...pd, profile: -1 }))
return
}
if (p.user) return
// fetch the user because p.user is undefined
const user = await userFromJwt(p.jwt, p.instance)
p = {
...p,
user: user,
}
})
export async function setUser(jwt: string, instance: string) {
try {
new URL(`https://${instance}`)
} catch (err) {
return
}
const user = await userFromJwt(jwt, instance)
if (!user) {
toast({
content: 'Failed to fetch your user. Is your instance down?',
type: ToastType.error,
})
}
profileData.update((pd) => {
// too lazy to make a decent system
const id = Math.floor(Math.random() * 100000)
const newProfile: Profile = {
id: id,
instance: instance,
jwt: jwt,
}
profile.set({
...newProfile,
user: user,
})
return {
profile: id,
profiles: [...pd.profiles, newProfile],
}
})
}
async function userFromJwt(
jwt: string,
instance: string
): Promise<PersonData | undefined> {
const myUser = (await getClient(instance).getSite({ auth: jwt })).my_user
if (!myUser) return undefined
return {
unreads: 0,
reports: 0,
...myUser,
}
}
const userToPersonData = (user: MyUserInfo): PersonData => ({
...user,
unreads: 0,
reports: 0,
})
function getProfileData() {
const pd = getFromStorage<ProfileData>('profileData')!
profileData.set(pd)
console.log(get(profileData))
}
getProfileData()
+3 -6
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { profileData, setUser } from '$lib/auth.js'
import Button from '$lib/components/input/Button.svelte'
import TextInput from '$lib/components/input/TextInput.svelte'
import Card from '$lib/components/ui/Card.svelte'
@@ -27,6 +28,7 @@
async function logIn() {
data.loading = true
try {
if (!(await validateInstance(data.instance))) {
throw new Error('Failed to contact that instance. Is it down?')
@@ -39,12 +41,7 @@
})
if (response?.jwt) {
user.set(undefined)
authData.set({
instance: data.instance,
token: response.jwt,
username: data.username,
})
setUser(response.jwt, data.instance)
toast({ content: 'Successfully logged in.', type: ToastType.success })
goto('/')