mirror of https://github.com/sveltejs/svelte
parent
f22c22c6b3
commit
fdf79639d2
@ -1,10 +1,8 @@
|
|||||||
import send from '@polka/send';
|
import send from '@polka/send';
|
||||||
|
import { isUser, toUser } from '../../backend/auth';
|
||||||
|
|
||||||
export function get(req, res) {
|
export async function get(req, res) {
|
||||||
if (!req.session || !req.session.passport || !req.session.passport.user) {
|
const user = await isUser(req, res);
|
||||||
return send(res, 200, 'null');
|
res.setHeader('Cache-Control', 'private, no-cache, no-store');
|
||||||
}
|
return send(res, 200, user ? toUser(user) : null);
|
||||||
|
|
||||||
const { id, username, displayName, photo } = req.session.passport.user;
|
|
||||||
send(res, 200, { id, username, displayName, photo });
|
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,33 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
|
|
||||||
export const user = writable(null);
|
export const user = writable(null);
|
||||||
|
|
||||||
if (process.browser) {
|
if (process.browser) {
|
||||||
// TODO this is a workaround for the fact that there's currently
|
const storageKey = 'svelte-dev:token';
|
||||||
// no way to pass session data from server to client
|
|
||||||
// TODO there is now! replace this with the session mechanism
|
// On load, get the last-known user token (if any)
|
||||||
fetch('/auth/me.json', { credentials: 'include' })
|
// Note: We can skip this all by writing User data?
|
||||||
.then(r => r.json())
|
const token = localStorage.getItem(storageKey);
|
||||||
|
|
||||||
|
// Write changes to localStorage
|
||||||
|
user.subscribe(obj => {
|
||||||
|
if (obj) {
|
||||||
|
localStorage.setItem(storageKey, obj.token);
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem(storageKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
// If token, refresh the User data from API
|
||||||
|
const headers = { Authorization: `Bearer ${token}` };
|
||||||
|
fetch('/auth/me.json', { headers })
|
||||||
|
.then(r => r.ok ? r.json() : null)
|
||||||
.then(user.set);
|
.then(user.set);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function logout() {
|
export function logout() {
|
||||||
const r = await fetch(`/auth/logout`, { method: 'POST' });
|
user.set(null);
|
||||||
if (r.ok) user.set(null);
|
|
||||||
}
|
}
|
Loading…
Reference in new issue