Token login

This commit is contained in:
Philipp Heckel 2022-12-07 20:44:20 -05:00
parent 35657a7bbd
commit 8dcb4be8a8
11 changed files with 94 additions and 26 deletions

View file

@ -7,7 +7,7 @@ import {
topicUrlJsonPoll,
topicUrlJsonPollWithSince,
userAccountUrl,
userAuthUrl,
userTokenUrl,
userStatsUrl
} from "./utils";
import userManager from "./UserManager";
@ -119,8 +119,8 @@ class Api {
throw new Error(`Unexpected server response ${response.status}`);
}
async userAuth(baseUrl, user) {
const url = userAuthUrl(baseUrl);
async login(baseUrl, user) {
const url = userTokenUrl(baseUrl);
console.log(`[Api] Checking auth for ${url}`);
const response = await fetch(url, {
headers: maybeWithBasicAuth({}, user)
@ -135,6 +135,18 @@ class Api {
return json.token;
}
async logout(baseUrl, token) {
const url = userTokenUrl(baseUrl);
console.log(`[Api] Logging out from ${url} using token ${token}`);
const response = await fetch(url, {
method: "DELETE",
headers: maybeWithBearerAuth({}, token)
});
if (response.status !== 200) {
throw new Error(`Unexpected server response ${response.status}`);
}
}
async userStats(baseUrl) {
const url = userStatsUrl(baseUrl);
console.log(`[Api] Fetching user stats ${url}`);

View file

@ -9,6 +9,10 @@ class Session {
localStorage.removeItem("token");
}
exists() {
return this.username() && this.token();
}
username() {
return localStorage.getItem("user");
}

View file

@ -19,7 +19,7 @@ export const topicUrlJsonPollWithSince = (baseUrl, topic, since) => `${topicUrlJ
export const topicUrlAuth = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/auth`;
export const topicShortUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));
export const userStatsUrl = (baseUrl) => `${baseUrl}/user/stats`;
export const userAuthUrl = (baseUrl) => `${baseUrl}/user/auth`;
export const userTokenUrl = (baseUrl) => `${baseUrl}/user/token`;
export const userAccountUrl = (baseUrl) => `${baseUrl}/user/account`;
export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
export const expandUrl = (url) => [`https://${url}`, `http://${url}`];

View file

@ -246,7 +246,7 @@ const ProfileIcon = (props) => {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const anchorRef = useRef(null);
const username = session.username();
const navigate = useNavigate();
const handleToggleOpen = () => {
setOpen((prevOpen) => !prevOpen);
@ -272,7 +272,8 @@ const ProfileIcon = (props) => {
// TODO
};
const handleLogout = () => {
const handleLogout = async () => {
await api.logout("http://localhost:2586"/*window.location.origin*/, session.token());
session.reset();
window.location.href = routes.app;
};
@ -288,15 +289,15 @@ const ProfileIcon = (props) => {
return (
<>
{username &&
{session.exists() &&
<IconButton color="inherit" size="large" edge="end" ref={anchorRef} onClick={handleToggleOpen} sx={{marginRight: 0}} aria-label={t("xxxxxxx")}>
<AccountCircleIcon/>
</IconButton>
}
{!username &&
{!session.exists() &&
<>
<Button>Sign in</Button>
<Button>Sign up</Button>
<Button color="inherit" variant="outlined" onClick={() => navigate(routes.login)}>Sign in</Button>
<Button color="inherit" variant="outlined" onClick={() => navigate(routes.signup)}>Sign up</Button>
</>
}
<Popper

View file

@ -36,7 +36,7 @@ const Login = () => {
username: data.get('email'),
password: data.get('password'),
}
const token = await api.userAuth("http://localhost:2586"/*window.location.origin*/, user);
const token = await api.login("http://localhost:2586"/*window.location.origin*/, user);
console.log(`[Api] User auth for user ${user.username} successful, token is ${token}`);
session.store(user.username, token);
window.location.href = routes.app;

View file

@ -84,7 +84,10 @@ const NotificationList = (props) => {
useEffect(() => {
return () => {
setMaxCount(pageSize);
document.getElementById("main").scrollTo(0, 0);
const main = document.getElementById("main");
if (main) {
main.scrollTo(0, 0);
}
}
}, [props.id]);

View file

@ -441,6 +441,11 @@ const Language = () => {
const title = t("prefs_appearance_language_title") + " " + randomFlags.join(" ");
const lang = i18n.language ?? "en";
const handleChange = async (ev) => {
await i18n.changeLanguage(ev.target.value);
//api.update
};
// Remember: Flags are not languages. Don't put flags next to the language in the list.
// Languages names from: https://www.omniglot.com/language/names.htm
// Better: Sidebar in Wikipedia: https://en.wikipedia.org/wiki/Bokm%C3%A5l
@ -448,7 +453,7 @@ const Language = () => {
return (
<Pref labelId={labelId} title={title}>
<FormControl fullWidth variant="standard" sx={{ m: 1 }}>
<Select value={lang} onChange={(ev) => i18n.changeLanguage(ev.target.value)} aria-labelledby={labelId}>
<Select value={lang} onChange={handleChange} aria-labelledby={labelId}>
<MenuItem value="en">English</MenuItem>
<MenuItem value="id">Bahasa Indonesia</MenuItem>
<MenuItem value="bg">Български</MenuItem>
@ -474,6 +479,10 @@ const Language = () => {
)
};
const AccessControl = () => {
return <></>;
}
/*
const AccessControl = () => {
const { t } = useTranslation();
const [dialogKey, setDialogKey] = useState(0);
@ -632,6 +641,6 @@ const AccessControlDialog = (props) => {
</Dialog>
);
};
*/
export default Preferences;

View file

@ -4,6 +4,7 @@ import {shortUrl} from "../app/utils";
const routes = {
home: "/",
login: "/login",
signup: "/signup",
app: config.appRoot,
settings: "/settings",
subscription: "/:topic",