feat: Add login stuff

This commit is contained in:
Xyphyn committed 2023-07-04 13:08:58 -07:00
1 parent f71ad4be8e
commit f0523b0c3f
18 files changed
+288 -56

No files matched your search

+39 -4
View File
@@ -1,33 +1,63 @@
<script lang="ts">
import { goto } from '$app/navigation'
import Button from '$lib/components/input/Button.svelte'
import TextInput from '$lib/components/input/TextInput.svelte'
import Card from '$lib/components/ui/Card.svelte'
import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js'
import { DEFAULT_INSTANCE_URL, authData, getClient } from '$lib/lemmy.js'
import { Color } from '$lib/ui/colors.js'
let data = {
instance: DEFAULT_INSTANCE_URL,
username: '',
password: '',
loading: false,
}
async function validateURL(instance: string): Promise<boolean> {
if (instance == '') return false
if (!instance.startsWith('https://')) {
instance = 'https://' + instance
}
const url = new URL(instance)
try {
await getClient(url.toString()).getSite({})
} catch (err) {
throw new Error('Invalid instance URL')
}
return true
}
async function logIn() {
data.loading = true
try {
const response = await getClient().login({
if (!(await validateURL(data.instance))) {
throw new Error('Invalid instance URL')
}
const response = await getClient(data.instance).login({
username_or_email: data.username,
password: data.password,
})
if (response.jwt) {
if (response?.jwt) {
authData.set({
instance: DEFAULT_INSTANCE_URL,
instance: data.instance,
token: response.jwt,
username: data.username,
})
addToast('Success', 'Successfully logged in.', ToastType.success)
goto('/')
} else {
throw new Error('Invalid credentials')
}
} catch (error) {
alert('failed')
addToast('Error', error as any, ToastType.error)
}
data.loading = false
}
@@ -36,6 +66,11 @@
<Card class="mx-auto p-6">
<form on:submit|preventDefault={logIn} class="flex flex-col gap-4">
<h1 class="font-bold text-lg">Log in</h1>
<TextInput
bind:value={data.instance}
label="Instance URL"
placeholder="lemmy.world"
/>
<TextInput
bind:value={data.username}
label="Username"