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
+270 -38

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <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" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head% %sveltekit.head%
</head> </head>
+39 -7
View File
@@ -1,19 +1,27 @@
import { error } from '@sveltejs/kit' 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 }) { export async function handle({ event, resolve }) {
// annoying hack to fix lemmy's CORS // annoying hack to fix lemmy's CORS
if (event.url.pathname.startsWith('/cors')) { if (event.url.pathname.startsWith('/cors')) {
const instance = `${event.url.pathname.split('/')[2]}` // cut off the 1st slash (empty), and remove the /cors
const url = `${event.url.pathname
.split('/')
.slice(3)
.join('/')}?${event.url.searchParams.toString()}`
event.request.headers.delete('origin') event.request.headers.delete('origin')
event.request.headers.delete('host') event.request.headers.delete('host')
try { try {
const data = await fetch(`https://${instance}/${url.toString()}`, { const url = buildUrl(event.url)
const data = await fetch(url, {
method: event.request.method, method: event.request.method,
body: event.request.body, body: event.request.body,
headers: event.request.headers, headers: event.request.headers,
@@ -22,9 +30,33 @@ export async function handle({ event, resolve }) {
signal: AbortSignal.timeout(20 * 1000), signal: AbortSignal.timeout(20 * 1000),
}) })
if (!data.ok) {
return new Response(
JSON.stringify({
message: await data.text(),
}),
{
status: data.status,
}
)
}
try {
const json = await data.json() const json = await data.json()
return new Response(JSON.stringify(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) { } catch (error) {
console.error(error) console.error(error)
return new Response( return new Response(
@@ -7,13 +7,13 @@
function linkFromCommunity(community: Community) { function linkFromCommunity(community: Community) {
const local = community.local const local = community.local
if (local) { // if (local) {
return `/c/${community.name}` // return `/c/${community.name}`
} else { // } else {
const domain = new URL(community.actor_id).hostname const domain = new URL(community.actor_id).hostname
return `/c/${community.name}@${domain}` return `/c/${community.name}@${domain}`
} // }
} }
</script> </script>
@@ -26,6 +26,7 @@
width={24} width={24}
height={24} height={24}
class="rounded-full aspect-square object-cover" class="rounded-full aspect-square object-cover"
loading="lazy"
/> />
{/if} {/if}
{community.title} {community.title}
@@ -5,4 +5,10 @@
export let width: number export let width: number
</script> </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"
/>
+27 -5
View File
@@ -1,9 +1,16 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'
import Link from '$lib/components/input/Link.svelte' import Link from '$lib/components/input/Link.svelte'
import Logo from '$lib/components/ui/Logo.svelte' import Logo from '$lib/components/ui/Logo.svelte'
import Menu from '$lib/components/ui/menu/Menu.svelte' import Menu from '$lib/components/ui/menu/Menu.svelte'
import MenuButton from '$lib/components/ui/menu/MenuButton.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 { import {
ArrowLeftOnRectangle, ArrowLeftOnRectangle,
ArrowRightOnRectangle, ArrowRightOnRectangle,
@@ -21,14 +28,16 @@
<Logo width={40} /> <Logo width={40} />
<div class="flex flex-col"> <div class="flex flex-col">
<span class="font-bold">Xylemmy</span> <span class="font-bold">Xylemmy</span>
{#if $instance_url}
<span <span
class="text-xs opacity-50 class="text-xs opacity-50
transition-opacity" transition-opacity"
> >
{new URL(`https://${$instance_url}`).hostname} {#if $authData?.instance}
</span> {$authData.instance}
{:else}
{DEFAULT_INSTANCE_URL}
{/if} {/if}
</span>
</div> </div>
</a> </a>
</div> </div>
@@ -50,9 +59,22 @@
{/if} {/if}
</button> </button>
<span class="text-xs opacity-80 text-left mx-4 my-2">Profile</span> <span class="text-xs opacity-80 text-left mx-4 my-2">Profile</span>
{#if !$user}
<MenuButton link href="/login"> <MenuButton link href="/login">
<Icon src={ArrowLeftOnRectangle} mini width={16} /> Log in <Icon src={ArrowLeftOnRectangle} mini width={16} /> Log in
</MenuButton> </MenuButton>
<MenuButton><Icon src={Cog6Tooth} mini width={16} /> Settings</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> </Menu>
</nav> </nav>
+57
View File
@@ -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>
+39
View File
@@ -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)
}
+12 -6
View File
@@ -3,13 +3,17 @@ import {
LemmyHttp, LemmyHttp,
type LoginResponse, type LoginResponse,
} from 'lemmy-js-client' } from 'lemmy-js-client'
import { writable } from 'svelte/store' import { get, writable } from 'svelte/store'
import { PUBLIC_PROXY_URL } from '$env/static/public' import { PUBLIC_PROXY_URL } from '$env/static/public'
export const DEFAULT_INSTANCE_URL = 'programming.dev' export const DEFAULT_INSTANCE_URL = 'programming.dev'
export let instance_url = writable(DEFAULT_INSTANCE_URL) 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}`) return new LemmyHttp(`${PUBLIC_PROXY_URL}/cors/${instance}`)
} }
@@ -19,18 +23,20 @@ export interface AuthData {
instance: string instance: string
} }
export const authData = writable<AuthData | undefined>() export const authData = writable<AuthData | undefined>(
export const user = writable<GetPersonDetailsResponse>() await (() => {
if (typeof localStorage != 'undefined') { if (typeof localStorage != 'undefined') {
if (localStorage.getItem('user')) { if (localStorage.getItem('user')) {
try { try {
authData.set(JSON.parse(localStorage.getItem('user') ?? '')) return JSON.parse(localStorage.getItem('user') ?? '')
} catch (error) { } catch (error) {
localStorage.removeItem('user') localStorage.removeItem('user')
} }
} }
} }
})()
)
export const user = writable<GetPersonDetailsResponse>()
authData.subscribe(async (data) => { authData.subscribe(async (data) => {
if (!data) return if (!data) return
+2
View File
@@ -4,6 +4,7 @@
import { navigating, page } from '$app/stores' import { navigating, page } from '$app/stores'
import nProgress from 'nprogress' import nProgress from 'nprogress'
import 'nprogress/nprogress.css' import 'nprogress/nprogress.css'
import ToastContainer from '$lib/components/ui/toasts/ToastContainer.svelte'
nProgress.configure({ nProgress.configure({
minimum: 0.4, minimum: 0.4,
@@ -22,6 +23,7 @@
</script> </script>
<Navbar /> <Navbar />
<ToastContainer />
<div class="mx-auto max-w-5xl p-4"> <div class="mx-auto max-w-5xl p-4">
<slot /> <slot />
</div> </div>
+1 -1
View File
@@ -14,7 +14,7 @@
PencilSquare, PencilSquare,
UserGroup, UserGroup,
} from 'svelte-hero-icons' } 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 Post from './post/[id]/Post.svelte'
import FormattedNumber from '$lib/components/util/FormattedNumber.svelte' import FormattedNumber from '$lib/components/util/FormattedNumber.svelte'
import Markdown from '$lib/components/markdown/Markdown.svelte' import Markdown from '$lib/components/markdown/Markdown.svelte'
+1 -1
View File
@@ -3,7 +3,7 @@
import Link from '$lib/components/input/Link.svelte' import Link from '$lib/components/input/Link.svelte'
import MultiSelect from '$lib/components/input/MultiSelect.svelte' import MultiSelect from '$lib/components/input/MultiSelect.svelte'
import SvelteMarkdown from 'svelte-markdown' 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 Post from '../../post/[id]/Post.svelte'
import { goto } from '$app/navigation' import { goto } from '$app/navigation'
import RelativeDate from '$lib/components/util/RelativeDate.svelte' import RelativeDate from '$lib/components/util/RelativeDate.svelte'
+3 -1
View File
@@ -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 type { ListingType, SortType } from 'lemmy-js-client'
import { get } from 'svelte/store'
export function load(req: any) { export function load(req: any) {
const page = Number(req.url.searchParams.get('page') || 1) || 1 const page = Number(req.url.searchParams.get('page') || 1) || 1
@@ -13,6 +14,7 @@ export function load(req: any) {
community_name: req.params.name, community_name: req.params.name,
page: page, page: page,
sort: sort, sort: sort,
auth: get(authData)?.token,
}), }),
streamed: { streamed: {
community: getClient().getCommunity({ community: getClient().getCommunity({
+2 -1
View File
@@ -12,6 +12,7 @@
import CommunityLink from '$lib/components/community/CommunityLink.svelte' import CommunityLink from '$lib/components/community/CommunityLink.svelte'
import Link from '$lib/components/input/Link.svelte' import Link from '$lib/components/input/Link.svelte'
import { Color } from '$lib/ui/colors.js' import { Color } from '$lib/ui/colors.js'
import TextInput from '$lib/components/input/TextInput.svelte'
export let data export let data
@@ -32,7 +33,7 @@
}} }}
/> />
<div class="flex flex-col sm:flex-row gap-2 sm:ml-auto"> <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 class="bg-slate-100 border border-slate-200 dark:border-zinc-800
dark:bg-zinc-900 rounded-md" dark:bg-zinc-900 rounded-md"
bind:value={search} bind:value={search}
+39 -4
View File
@@ -1,33 +1,63 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'
import Button from '$lib/components/input/Button.svelte' import Button from '$lib/components/input/Button.svelte'
import TextInput from '$lib/components/input/TextInput.svelte' import TextInput from '$lib/components/input/TextInput.svelte'
import Card from '$lib/components/ui/Card.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 { DEFAULT_INSTANCE_URL, authData, getClient } from '$lib/lemmy.js'
import { Color } from '$lib/ui/colors.js' import { Color } from '$lib/ui/colors.js'
let data = { let data = {
instance: DEFAULT_INSTANCE_URL,
username: '', username: '',
password: '', password: '',
loading: false, 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() { async function logIn() {
data.loading = true data.loading = true
try { 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, username_or_email: data.username,
password: data.password, password: data.password,
}) })
if (response.jwt) { if (response?.jwt) {
authData.set({ authData.set({
instance: DEFAULT_INSTANCE_URL, instance: data.instance,
token: response.jwt, token: response.jwt,
username: data.username, username: data.username,
}) })
addToast('Success', 'Successfully logged in.', ToastType.success)
goto('/')
} else {
throw new Error('Invalid credentials')
} }
} catch (error) { } catch (error) {
alert('failed') addToast('Error', error as any, ToastType.error)
} }
data.loading = false data.loading = false
} }
@@ -36,6 +66,11 @@
<Card class="mx-auto p-6"> <Card class="mx-auto p-6">
<form on:submit|preventDefault={logIn} class="flex flex-col gap-4"> <form on:submit|preventDefault={logIn} class="flex flex-col gap-4">
<h1 class="font-bold text-lg">Log in</h1> <h1 class="font-bold text-lg">Log in</h1>
<TextInput
bind:value={data.instance}
label="Instance URL"
placeholder="lemmy.world"
/>
<TextInput <TextInput
bind:value={data.username} bind:value={data.username}
label="Username" label="Username"
+5 -5
View File
@@ -7,7 +7,7 @@
Minus, Minus,
Plus, Plus,
} from 'svelte-hero-icons' } from 'svelte-hero-icons'
import Avatar from '../Avatar.svelte' import Avatar from '../../../../lib/components/ui/Avatar.svelte'
import type { CommentNodeI } from '../comments.js' import type { CommentNodeI } from '../comments.js'
import SvelteMarkdown from 'svelte-markdown' import SvelteMarkdown from 'svelte-markdown'
import RelativeDate from '$lib/components/util/RelativeDate.svelte' import RelativeDate from '$lib/components/util/RelativeDate.svelte'
@@ -27,6 +27,8 @@
const upvoted = node.comment_view.my_vote == 1 const upvoted = node.comment_view.my_vote == 1
node.comment_view.my_vote = Number(!upvoted)
await getClient() await getClient()
.likeComment({ .likeComment({
score: upvoted ? 0 : 1, score: upvoted ? 0 : 1,
@@ -34,8 +36,6 @@
comment_id: node.comment_view.comment.id, comment_id: node.comment_view.comment.id,
}) })
.catch((_) => undefined) .catch((_) => undefined)
node.comment_view.my_vote = Number(!upvoted)
} }
async function downvote() { async function downvote() {
@@ -43,6 +43,8 @@
const upvoted = node.comment_view.my_vote == -1 const upvoted = node.comment_view.my_vote == -1
node.comment_view.my_vote = -Number(!upvoted)
await getClient() await getClient()
.likeComment({ .likeComment({
score: upvoted ? 0 : -1, score: upvoted ? 0 : -1,
@@ -50,8 +52,6 @@
comment_id: node.comment_view.comment.id, comment_id: node.comment_view.comment.id,
}) })
.catch((_) => undefined) .catch((_) => undefined)
node.comment_view.my_vote = -Number(!upvoted)
} }
</script> </script>
@@ -4,6 +4,7 @@
import type { Comment, Post } from 'lemmy-js-client' import type { Comment, Post } from 'lemmy-js-client'
import { authData, getClient, user } from '$lib/lemmy.js' import { authData, getClient, user } from '$lib/lemmy.js'
import { createEventDispatcher } from 'svelte' import { createEventDispatcher } from 'svelte'
import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js'
export let postId: number export let postId: number
export let parentId: number | undefined = undefined export let parentId: number | undefined = undefined
@@ -28,8 +29,13 @@
dispatch('comment', response) dispatch('comment', response)
newComment = '' newComment = ''
addToast(
'Success',
'Your comment was added. You may need to refresh to see it.',
ToastType.success
)
} catch (err) { } catch (err) {
alert('Failed to comment') addToast('Error', 'Failed to comment.', ToastType.error)
} }
loading = false loading = false
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" fill="none">
<circle cx="50" cy="50" fill="white" r="50" />
<path d="M45 20.8868C48.094 19.1004 51.906 19.1004 55 20.8868L72.7128 31.1132C75.8068 32.8996 77.7128 36.2008 77.7128 39.7735V60.2265C77.7128 63.7992 75.8068 67.1004 72.7128 68.8868L55 79.1132C51.906 80.8996 48.094 80.8996 45 79.1132L27.2872 68.8868C24.1932 67.1004 22.2872 63.7992 22.2872 60.2265V39.7735C22.2872 36.2008 24.1932 32.8996 27.2872 31.1132L45 20.8868Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 535 B