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