feat: Add login stuff
This commit is contained in:
1 parent
f71ad4be8e
commit
f0523b0c3f
18 files changed
+288
-56
No files matched your search
+1
-1
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<link rel="icon" href="%sveltekit.assets%/img/logo-background.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
|
||||
+40
-8
@@ -1,19 +1,27 @@
|
||||
import { error } from '@sveltejs/kit'
|
||||
|
||||
function buildUrl(inputUrl: URL): URL {
|
||||
let withoutCors = inputUrl.pathname.replace('/cors/', '')
|
||||
|
||||
if (!withoutCors.startsWith('https://')) {
|
||||
withoutCors = 'https://' + withoutCors
|
||||
}
|
||||
|
||||
return new URL(`${withoutCors}?${inputUrl.searchParams.toString()}`)
|
||||
}
|
||||
|
||||
export async function handle({ event, resolve }) {
|
||||
// annoying hack to fix lemmy's CORS
|
||||
if (event.url.pathname.startsWith('/cors')) {
|
||||
const instance = `${event.url.pathname.split('/')[2]}`
|
||||
const url = `${event.url.pathname
|
||||
.split('/')
|
||||
.slice(3)
|
||||
.join('/')}?${event.url.searchParams.toString()}`
|
||||
// cut off the 1st slash (empty), and remove the /cors
|
||||
|
||||
event.request.headers.delete('origin')
|
||||
event.request.headers.delete('host')
|
||||
|
||||
try {
|
||||
const data = await fetch(`https://${instance}/${url.toString()}`, {
|
||||
const url = buildUrl(event.url)
|
||||
|
||||
const data = await fetch(url, {
|
||||
method: event.request.method,
|
||||
body: event.request.body,
|
||||
headers: event.request.headers,
|
||||
@@ -22,9 +30,33 @@ export async function handle({ event, resolve }) {
|
||||
signal: AbortSignal.timeout(20 * 1000),
|
||||
})
|
||||
|
||||
const json = await data.json()
|
||||
if (!data.ok) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
message: await data.text(),
|
||||
}),
|
||||
{
|
||||
status: data.status,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(json))
|
||||
try {
|
||||
const json = await data.json()
|
||||
|
||||
return new Response(JSON.stringify(json), {
|
||||
status: data.status,
|
||||
})
|
||||
} catch (err) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
message: 'Failed to fetch',
|
||||
}),
|
||||
{
|
||||
status: data.status,
|
||||
}
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return new Response(
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
function linkFromCommunity(community: Community) {
|
||||
const local = community.local
|
||||
|
||||
if (local) {
|
||||
return `/c/${community.name}`
|
||||
} else {
|
||||
const domain = new URL(community.actor_id).hostname
|
||||
// if (local) {
|
||||
// return `/c/${community.name}`
|
||||
// } else {
|
||||
const domain = new URL(community.actor_id).hostname
|
||||
|
||||
return `/c/${community.name}@${domain}`
|
||||
}
|
||||
return `/c/${community.name}@${domain}`
|
||||
// }
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
width={24}
|
||||
height={24}
|
||||
class="rounded-full aspect-square object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
{/if}
|
||||
{community.title}
|
||||
|
||||
@@ -5,4 +5,10 @@
|
||||
export let width: number
|
||||
</script>
|
||||
|
||||
<img src={url} {alt} {width} class="rounded-full aspect-square object-cover" />
|
||||
<img
|
||||
src={url}
|
||||
{alt}
|
||||
{width}
|
||||
loading="lazy"
|
||||
class="rounded-full aspect-square object-cover"
|
||||
/>
|
||||
@@ -1,9 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation'
|
||||
import Link from '$lib/components/input/Link.svelte'
|
||||
import Logo from '$lib/components/ui/Logo.svelte'
|
||||
import Menu from '$lib/components/ui/menu/Menu.svelte'
|
||||
import MenuButton from '$lib/components/ui/menu/MenuButton.svelte'
|
||||
import { instance_url, user } from '$lib/lemmy.js'
|
||||
import {
|
||||
DEFAULT_INSTANCE_URL,
|
||||
authData,
|
||||
instance_url,
|
||||
user,
|
||||
} from '$lib/lemmy.js'
|
||||
import { Color } from '$lib/ui/colors.js'
|
||||
import {
|
||||
ArrowLeftOnRectangle,
|
||||
ArrowRightOnRectangle,
|
||||
@@ -21,14 +28,16 @@
|
||||
<Logo width={40} />
|
||||
<div class="flex flex-col">
|
||||
<span class="font-bold">Xylemmy</span>
|
||||
{#if $instance_url}
|
||||
<span
|
||||
class="text-xs opacity-50
|
||||
transition-opacity"
|
||||
>
|
||||
{new URL(`https://${$instance_url}`).hostname}
|
||||
</span>
|
||||
{/if}
|
||||
<span
|
||||
class="text-xs opacity-50
|
||||
transition-opacity"
|
||||
>
|
||||
{#if $authData?.instance}
|
||||
{$authData.instance}
|
||||
{:else}
|
||||
{DEFAULT_INSTANCE_URL}
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
@@ -50,9 +59,22 @@
|
||||
{/if}
|
||||
</button>
|
||||
<span class="text-xs opacity-80 text-left mx-4 my-2">Profile</span>
|
||||
<MenuButton link href="/login">
|
||||
<Icon src={ArrowLeftOnRectangle} mini width={16} /> Log in
|
||||
</MenuButton>
|
||||
<MenuButton><Icon src={Cog6Tooth} mini width={16} /> Settings</MenuButton>
|
||||
{#if !$user}
|
||||
<MenuButton link href="/login">
|
||||
<Icon src={ArrowLeftOnRectangle} mini width={16} /> Log in
|
||||
</MenuButton>
|
||||
{:else}
|
||||
<MenuButton
|
||||
on:click={() => {
|
||||
localStorage.removeItem('user')
|
||||
goto('/', {
|
||||
invalidateAll: true,
|
||||
})
|
||||
}}
|
||||
color={Color.dangerSecondary}
|
||||
>
|
||||
<Icon src={ArrowRightOnRectangle} mini width={16} />Log out
|
||||
</MenuButton>
|
||||
{/if}
|
||||
</Menu>
|
||||
</nav>
|
||||
@@ -0,0 +1,57 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
ToastType,
|
||||
type Toast,
|
||||
toasts,
|
||||
} from '$lib/components/ui/toasts/toasts'
|
||||
import {
|
||||
InformationCircle,
|
||||
ExclamationTriangle,
|
||||
ExclamationCircle,
|
||||
CheckCircle,
|
||||
Icon,
|
||||
XMark,
|
||||
} from 'svelte-hero-icons'
|
||||
import { expoInOut } from 'svelte/easing'
|
||||
import { scale } from 'svelte/transition'
|
||||
export let toast: Toast
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="relative w-80 min-h-[4rem] dark:bg-zinc-900 bg-white shadow-lg rounded-md overflow-hidden flex flex-row items-center"
|
||||
transition:scale={{
|
||||
duration: 500,
|
||||
start: 0.8,
|
||||
easing: expoInOut,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class="h-full w-[2px] absolute left-0 top-0 bg-gradient-to-b {toast.type}"
|
||||
/>
|
||||
<Icon
|
||||
size="20"
|
||||
solid
|
||||
class="relative m-2 ml-4 flex-shrink-0 {toast.type}"
|
||||
src={toast.type == ToastType.info
|
||||
? InformationCircle
|
||||
: toast.type == ToastType.success
|
||||
? CheckCircle
|
||||
: toast.type == ToastType.warning
|
||||
? ExclamationTriangle
|
||||
: toast.type == ToastType.error
|
||||
? ExclamationCircle
|
||||
: ExclamationCircle}
|
||||
/>
|
||||
<div class="flex flex-col p-4 pl-0">
|
||||
<h1 class="text-base font-bold">{toast.title}</h1>
|
||||
<p class="text-sm">{toast.content}</p>
|
||||
</div>
|
||||
<button
|
||||
on:click={() => {
|
||||
toasts.update((toasts) => toasts.filter((t) => t.id != toast.id))
|
||||
}}
|
||||
class="absolute top-0 right-0 p-2 m-2 rounded-lg transition-colors hover:bg-slate-100 hover:dark:bg-zinc-700"
|
||||
>
|
||||
<Icon src={XMark} size="20" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -0,0 +1,19 @@
|
||||
<script lang="ts">
|
||||
import Toast from '$lib/components/ui/toasts/Toast.svelte'
|
||||
import { flip } from 'svelte/animate'
|
||||
import { expoInOut } from 'svelte/easing'
|
||||
import { toasts } from '$lib/components/ui/toasts/toasts'
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="fixed right-0 top-0 flex flex-col gap-4 z-50 p-4 overflow-hidden h-screen min-w-[24rem] items-end pointer-events-none"
|
||||
>
|
||||
{#each $toasts as toast (toast.id)}
|
||||
<div
|
||||
animate:flip={{ duration: 500, easing: expoInOut }}
|
||||
class="pointer-events-auto"
|
||||
>
|
||||
<Toast {toast} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -0,0 +1,39 @@
|
||||
import { writable } from 'svelte/store'
|
||||
|
||||
export enum ToastType {
|
||||
'error' = 'from-red-400 to-red-400 text-red-400',
|
||||
'warning' = 'from-yellow-300 to-yellow-300 text-yellow-300',
|
||||
'success' = 'from-green-400 to-green-400 text-green-400',
|
||||
'info' = '',
|
||||
}
|
||||
|
||||
export interface Toast {
|
||||
id: number
|
||||
title: string
|
||||
content: string
|
||||
type: ToastType
|
||||
}
|
||||
|
||||
export const toasts = writable<Toast[]>([])
|
||||
|
||||
export function addToast(title: string, content: string, type: ToastType) {
|
||||
let id = 0
|
||||
|
||||
toasts.update((toasts) => {
|
||||
id = Math.floor(Math.random() * 10000)
|
||||
|
||||
return [
|
||||
{
|
||||
id: id,
|
||||
content: content,
|
||||
title: title,
|
||||
type: type,
|
||||
},
|
||||
...toasts,
|
||||
]
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
toasts.update((toasts) => toasts.filter((toast) => toast.id != id))
|
||||
}, 5000)
|
||||
}
|
||||
+19
-13
@@ -3,13 +3,17 @@ import {
|
||||
LemmyHttp,
|
||||
type LoginResponse,
|
||||
} from 'lemmy-js-client'
|
||||
import { writable } from 'svelte/store'
|
||||
import { get, writable } from 'svelte/store'
|
||||
import { PUBLIC_PROXY_URL } from '$env/static/public'
|
||||
|
||||
export const DEFAULT_INSTANCE_URL = 'programming.dev'
|
||||
export let instance_url = writable(DEFAULT_INSTANCE_URL)
|
||||
|
||||
export function getClient(instance: string = `programming.dev`): LemmyHttp {
|
||||
export function getClient(instance?: string): LemmyHttp {
|
||||
if (!instance) {
|
||||
instance = get(authData)?.instance ?? DEFAULT_INSTANCE_URL
|
||||
}
|
||||
|
||||
return new LemmyHttp(`${PUBLIC_PROXY_URL}/cors/${instance}`)
|
||||
}
|
||||
|
||||
@@ -19,18 +23,20 @@ export interface AuthData {
|
||||
instance: string
|
||||
}
|
||||
|
||||
export const authData = writable<AuthData | undefined>()
|
||||
export const user = writable<GetPersonDetailsResponse>()
|
||||
|
||||
if (typeof localStorage != 'undefined') {
|
||||
if (localStorage.getItem('user')) {
|
||||
try {
|
||||
authData.set(JSON.parse(localStorage.getItem('user') ?? ''))
|
||||
} catch (error) {
|
||||
localStorage.removeItem('user')
|
||||
export const authData = writable<AuthData | undefined>(
|
||||
await (() => {
|
||||
if (typeof localStorage != 'undefined') {
|
||||
if (localStorage.getItem('user')) {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('user') ?? '')
|
||||
} catch (error) {
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
)
|
||||
export const user = writable<GetPersonDetailsResponse>()
|
||||
|
||||
authData.subscribe(async (data) => {
|
||||
if (!data) return
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { navigating, page } from '$app/stores'
|
||||
import nProgress from 'nprogress'
|
||||
import 'nprogress/nprogress.css'
|
||||
import ToastContainer from '$lib/components/ui/toasts/ToastContainer.svelte'
|
||||
|
||||
nProgress.configure({
|
||||
minimum: 0.4,
|
||||
@@ -22,6 +23,7 @@
|
||||
</script>
|
||||
|
||||
<Navbar />
|
||||
<ToastContainer />
|
||||
<div class="mx-auto max-w-5xl p-4">
|
||||
<slot />
|
||||
</div>
|
||||
@@ -14,7 +14,7 @@
|
||||
PencilSquare,
|
||||
UserGroup,
|
||||
} from 'svelte-hero-icons'
|
||||
import Avatar from './post/[id]/Avatar.svelte'
|
||||
import Avatar from '../lib/components/ui/Avatar.svelte'
|
||||
import Post from './post/[id]/Post.svelte'
|
||||
import FormattedNumber from '$lib/components/util/FormattedNumber.svelte'
|
||||
import Markdown from '$lib/components/markdown/Markdown.svelte'
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Link from '$lib/components/input/Link.svelte'
|
||||
import MultiSelect from '$lib/components/input/MultiSelect.svelte'
|
||||
import SvelteMarkdown from 'svelte-markdown'
|
||||
import Avatar from '../../post/[id]/Avatar.svelte'
|
||||
import Avatar from '../../../lib/components/ui/Avatar.svelte'
|
||||
import Post from '../../post/[id]/Post.svelte'
|
||||
import { goto } from '$app/navigation'
|
||||
import RelativeDate from '$lib/components/util/RelativeDate.svelte'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getClient } from '$lib/lemmy.js'
|
||||
import { authData, getClient } from '$lib/lemmy.js'
|
||||
import type { ListingType, SortType } from 'lemmy-js-client'
|
||||
import { get } from 'svelte/store'
|
||||
|
||||
export function load(req: any) {
|
||||
const page = Number(req.url.searchParams.get('page') || 1) || 1
|
||||
@@ -13,6 +14,7 @@ export function load(req: any) {
|
||||
community_name: req.params.name,
|
||||
page: page,
|
||||
sort: sort,
|
||||
auth: get(authData)?.token,
|
||||
}),
|
||||
streamed: {
|
||||
community: getClient().getCommunity({
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import CommunityLink from '$lib/components/community/CommunityLink.svelte'
|
||||
import Link from '$lib/components/input/Link.svelte'
|
||||
import { Color } from '$lib/ui/colors.js'
|
||||
import TextInput from '$lib/components/input/TextInput.svelte'
|
||||
|
||||
export let data
|
||||
|
||||
@@ -32,7 +33,7 @@
|
||||
}}
|
||||
/>
|
||||
<div class="flex flex-col sm:flex-row gap-2 sm:ml-auto">
|
||||
<input
|
||||
<TextInput
|
||||
class="bg-slate-100 border border-slate-200 dark:border-zinc-800
|
||||
dark:bg-zinc-900 rounded-md"
|
||||
bind:value={search}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
Minus,
|
||||
Plus,
|
||||
} from 'svelte-hero-icons'
|
||||
import Avatar from '../Avatar.svelte'
|
||||
import Avatar from '../../../../lib/components/ui/Avatar.svelte'
|
||||
import type { CommentNodeI } from '../comments.js'
|
||||
import SvelteMarkdown from 'svelte-markdown'
|
||||
import RelativeDate from '$lib/components/util/RelativeDate.svelte'
|
||||
@@ -27,6 +27,8 @@
|
||||
|
||||
const upvoted = node.comment_view.my_vote == 1
|
||||
|
||||
node.comment_view.my_vote = Number(!upvoted)
|
||||
|
||||
await getClient()
|
||||
.likeComment({
|
||||
score: upvoted ? 0 : 1,
|
||||
@@ -34,8 +36,6 @@
|
||||
comment_id: node.comment_view.comment.id,
|
||||
})
|
||||
.catch((_) => undefined)
|
||||
|
||||
node.comment_view.my_vote = Number(!upvoted)
|
||||
}
|
||||
|
||||
async function downvote() {
|
||||
@@ -43,6 +43,8 @@
|
||||
|
||||
const upvoted = node.comment_view.my_vote == -1
|
||||
|
||||
node.comment_view.my_vote = -Number(!upvoted)
|
||||
|
||||
await getClient()
|
||||
.likeComment({
|
||||
score: upvoted ? 0 : -1,
|
||||
@@ -50,8 +52,6 @@
|
||||
comment_id: node.comment_view.comment.id,
|
||||
})
|
||||
.catch((_) => undefined)
|
||||
|
||||
node.comment_view.my_vote = -Number(!upvoted)
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { Comment, Post } from 'lemmy-js-client'
|
||||
import { authData, getClient, user } from '$lib/lemmy.js'
|
||||
import { createEventDispatcher } from 'svelte'
|
||||
import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js'
|
||||
|
||||
export let postId: number
|
||||
export let parentId: number | undefined = undefined
|
||||
@@ -28,8 +29,13 @@
|
||||
dispatch('comment', response)
|
||||
|
||||
newComment = ''
|
||||
addToast(
|
||||
'Success',
|
||||
'Your comment was added. You may need to refresh to see it.',
|
||||
ToastType.success
|
||||
)
|
||||
} catch (err) {
|
||||
alert('Failed to comment')
|
||||
addToast('Error', 'Failed to comment.', ToastType.error)
|
||||
}
|
||||
|
||||
loading = false
|
||||
|
||||
Reference in new issue
Block a user