This commit is contained in:
Julian Lobbes 2023-06-17 19:30:47 +02:00
parent 5c0f557308
commit 2a01ca43b2
6 changed files with 31 additions and 17 deletions

View file

@ -22,7 +22,7 @@ tag_metadata = {
} }
@router.post("/login", response_model=AuthResponseToken) @router.post("/login/", response_model=AuthResponseToken)
def login(credentials: UserLoginSchema, db: Session = Depends(get_db)): def login(credentials: UserLoginSchema, db: Session = Depends(get_db)):
"""Returns a JWT for the user whose credentials were provided. """Returns a JWT for the user whose credentials were provided.

View file

@ -2,7 +2,7 @@
from typing import Annotated from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from todo.database.engine import get_db from todo.database.engine import get_db
@ -13,6 +13,9 @@ from todo.utils.exceptions import create_exception_dict as fmt
from todo.dependencies.users import UserSortablePaginationParams from todo.dependencies.users import UserSortablePaginationParams
import todo.auth.auth as auth import todo.auth.auth as auth
import logging
logger = logging.getLogger()
router = APIRouter( router = APIRouter(
prefix="/users", prefix="/users",
@ -48,9 +51,11 @@ def create_user(
@router.get("/{user_id}", response_model=userschema.User) @router.get("/{user_id}", response_model=userschema.User)
def read_user( def read_user(
user_id: int, user_id: int,
request: Request,
db: Session = Depends(get_db), db: Session = Depends(get_db),
current_user: userschema.User = Depends(auth_handler.get_current_user), current_user: userschema.User = Depends(auth_handler.get_current_user),
): ):
logger.error(request)
try: try:
user = usercrud.read_user(db=db, id=user_id) user = usercrud.read_user(db=db, id=user_id)
except NotFoundException as e: except NotFoundException as e:

View file

@ -2,7 +2,7 @@ import { error } from '@sveltejs/kit';
import type { ItemCount, TodoItem, Token, User } from './types'; import type { ItemCount, TodoItem, Token, User } from './types';
import { Endpoint } from './types'; import { Endpoint } from './types';
import type { StringMapping } from '$lib/utils/types'; import type { StringMapping } from '$lib/utils/types';
import { getTokenFromLocalstorage } from '$lib/auth/session'; import { _getTokenFromLocalstorage } from '$lib/auth/session';
/** /**
* A factory class for creating `Endpoint` instances to interact with the backend API. * A factory class for creating `Endpoint` instances to interact with the backend API.
@ -41,7 +41,7 @@ export class EndpointFactory {
*/ */
constructor(fetchFunction: Function = fetch) { constructor(fetchFunction: Function = fetch) {
this.fetchFunction = fetchFunction; this.fetchFunction = fetchFunction;
this._jwt = getTokenFromLocalstorage(); this._jwt = _getTokenFromLocalstorage();
} }
private _getDefaultHeaders(): StringMapping { private _getDefaultHeaders(): StringMapping {

View file

@ -101,7 +101,6 @@ export class Endpoint<T> {
if ('queryParameters' in options) { if ('queryParameters' in options) {
endpointUrl += `?${new URLSearchParams(options.queryParameters)}`; endpointUrl += `?${new URLSearchParams(options.queryParameters)}`;
} }
console.log(endpointUrl)
const response = await this.fetchFunction(endpointUrl, { const response = await this.fetchFunction(endpointUrl, {
method: this.requestMethod, method: this.requestMethod,

View file

@ -9,10 +9,10 @@ import { writable } from 'svelte/store';
export const storedUser = writable(); export const storedUser = writable();
// Name of the key holding the auth JWT in localstorage // Name of the key holding the auth JWT in localstorage
const jwtKey = 'jwt'; const _jwtKey = 'jwt';
// Name of the key holding the authenticated user in localstorage // Name of the key holding the authenticated user in localstorage
const userKey = 'user'; const _userKey = 'user';
export type StoredUser = { export type StoredUser = {
id: number, id: number,
email: string, email: string,
@ -25,22 +25,22 @@ export type StoredUser = {
* *
* @param {string} token - The token to save in localstorage. * @param {string} token - The token to save in localstorage.
*/ */
function saveTokenToLocalstorage(token: string): void { function _saveTokenToLocalstorage(token: string): void {
localStorage.setItem(jwtKey, token); localStorage.setItem(_jwtKey, token);
} }
/** /**
* Retrieves and returns the token, if present, from localstorage. * Retrieves and returns the token, if present, from localstorage.
*/ */
export function getTokenFromLocalstorage(): string | null { export function _getTokenFromLocalstorage(): string | null {
return localStorage.getItem(jwtKey); return localStorage.getItem(_jwtKey);
} }
/** /**
* Removes the saved token from localstorage. * Removes the saved token from localstorage.
*/ */
function clearTokenInLocalstorage(): void { function clearTokenInLocalstorage(): void {
localStorage.removeItem(jwtKey); localStorage.removeItem(_jwtKey);
} }
/** /**
@ -49,14 +49,14 @@ function clearTokenInLocalstorage(): void {
* @param {StoredUser} user - The user to write to localstorage. * @param {StoredUser} user - The user to write to localstorage.
*/ */
function saveUserToLocalstorage(user: StoredUser): void { function saveUserToLocalstorage(user: StoredUser): void {
localStorage.setItem(userKey, JSON.stringify(user)); localStorage.setItem(_userKey, JSON.stringify(user));
} }
/** /**
* Retrieves and returns the user, if present, from localstorage. * Retrieves and returns the user, if present, from localstorage.
*/ */
export function getUserFromLocalstorage(): StoredUser | null { export function getUserFromLocalstorage(): StoredUser | null {
let item: string | null = localStorage.getItem(userKey); let item: string | null = localStorage.getItem(_userKey);
if (typeof item !== 'string') { if (typeof item !== 'string') {
return null; return null;
} }
@ -67,7 +67,7 @@ export function getUserFromLocalstorage(): StoredUser | null {
* Removes the saved user from localstorage. * Removes the saved user from localstorage.
*/ */
function clearUserInLocalstorage(): void { function clearUserInLocalstorage(): void {
localStorage.removeItem(userKey); localStorage.removeItem(_userKey);
} }
/** /**
@ -112,12 +112,13 @@ export async function login(email: string, password: string): Promise<void> {
const parsedToken = jwt_decode(token.token) as Token; const parsedToken = jwt_decode(token.token) as Token;
const userId = parsedToken.sub; const userId = parsedToken.sub;
saveTokenToLocalstorage(token.token); _saveTokenToLocalstorage(token.token);
// recreate the factory with the jwt now in localstorage // recreate the factory with the jwt now in localstorage
endpointFactory = new EndpointFactory(); endpointFactory = new EndpointFactory();
const readUserEndpoint = endpointFactory.createReadUserEndpoint(userId); const readUserEndpoint = endpointFactory.createReadUserEndpoint(userId);
console.log(readUserEndpoint.call()) console.log(readUserEndpoint)
console.log(await readUserEndpoint.call())
const user = await readUserEndpoint.call(); const user = await readUserEndpoint.call();
saveUserToLocalstorage({ saveUserToLocalstorage({

View file

@ -2,6 +2,8 @@
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { login } from '$lib/auth/session'; import { login } from '$lib/auth/session';
import { EndpointFactory } from '$lib/api/endpoints';
let email: string = ""; let email: string = "";
let password: string = ""; let password: string = "";
@ -37,6 +39,12 @@
formError = true; formError = true;
} }
} }
async function handleDebugButtonClick() {
let epf = new EndpointFactory();
let rue = epf.createReadUserEndpoint(54);
console.log(await rue.call());
}
</script> </script>
<div class="flex flex-col items-center gap-y-4"> <div class="flex flex-col items-center gap-y-4">
@ -58,6 +66,7 @@
{/if} {/if}
</fieldset> </fieldset>
</form> </form>
<button on:click={handleDebugButtonClick}>Click me</button>
</div> </div>
<style> <style>