From 9479a4b1271b903ed4677669ef71acac8a4c31f9 Mon Sep 17 00:00:00 2001 From: swve Date: Thu, 22 Sep 2022 23:48:51 +0200 Subject: [PATCH] feat: init auth cookies --- app.py | 11 ++++++++--- front/pages/login.tsx | 2 +- front/pages/signup.tsx | 2 +- front/services/{ => auth}/auth.ts | 13 ++++++++----- src/routers/auth.py | 14 +++++++++----- 5 files changed, 27 insertions(+), 15 deletions(-) rename front/services/{ => auth}/auth.ts (82%) diff --git a/app.py b/app.py index 63093868..94b2a63a 100644 --- a/app.py +++ b/app.py @@ -2,6 +2,11 @@ from fastapi import FastAPI from src.main import global_router from fastapi.middleware.cors import CORSMiddleware +######################## +# Pre-Alpha Version 0.1.0 +# Author: @swve +# (c) LearnHouse 2022 +######################## # Init app = FastAPI( @@ -10,18 +15,18 @@ app = FastAPI( version="0.1.0", root_path="/" ) + app.add_middleware( CORSMiddleware, - allow_origins=["*"], + allow_origins=["http://localhost:3000"], allow_methods=["*"], allow_credentials=True, - allow_headers=["*"], + allow_headers=["*"] ) app.include_router(global_router) - @app.get("/") async def root(): return {"Message": "Welcome to LearnHouse ✨"} diff --git a/front/pages/login.tsx b/front/pages/login.tsx index 8f36941c..21709e25 100644 --- a/front/pages/login.tsx +++ b/front/pages/login.tsx @@ -1,7 +1,7 @@ import React from "react"; import Layout from "../components/ui/layout"; import { Title } from "../components/ui/styles/title"; -import { loginAndGetToken } from "../services/auth"; +import { loginAndGetToken } from "../services/auth/auth"; const Login = () => { const [email, setEmail] = React.useState(""); diff --git a/front/pages/signup.tsx b/front/pages/signup.tsx index 5d45a404..c0839da6 100644 --- a/front/pages/signup.tsx +++ b/front/pages/signup.tsx @@ -1,7 +1,7 @@ import React from "react"; import Layout from "../components/ui/layout"; import { Title } from "../components/ui/styles/title"; -import { signup } from "../services/auth"; +import { signup } from "../services/auth/auth"; const SignUp = () => { const [email, setEmail] = React.useState(""); diff --git a/front/services/auth.ts b/front/services/auth/auth.ts similarity index 82% rename from front/services/auth.ts rename to front/services/auth/auth.ts index 244ec5f9..f2153575 100644 --- a/front/services/auth.ts +++ b/front/services/auth/auth.ts @@ -1,4 +1,4 @@ -import { getAPIUrl } from "./config"; +import { getAPIUrl } from "../config"; interface LoginAndGetTokenResponse { access_token: "string"; @@ -9,7 +9,7 @@ interface LoginAndGetTokenResponse { export async function loginAndGetToken(username: string, password: string): Promise { // Request Config - const HeadersConfig = new Headers({ "Content-Type": "application/x-www-form-urlencoded", Origin: "http://localhost:3000" }); + const HeadersConfig = new Headers({ "Content-Type": "application/x-www-form-urlencoded" , Origin: "http://localhost:3000" }); const urlencoded = new URLSearchParams({ username: username, password: password }); const requestOptions: any = { @@ -17,11 +17,13 @@ export async function loginAndGetToken(username: string, password: string): Prom headers: HeadersConfig, body: urlencoded, redirect: "follow", + credentials: "include", }; - return fetch(`${getAPIUrl()}auth/token`, requestOptions) - .then((result) => result.json()) - .catch((error) => console.log("error", error)); + // fetch using await and async + const response = await fetch(`${getAPIUrl()}auth/token`, requestOptions); + const data = await response.json(); + return data; } export async function getUserInfo(token: string): Promise { @@ -30,6 +32,7 @@ export async function getUserInfo(token: string): Promise { method: "GET", headers: HeadersConfig, redirect: "follow", + credentials: "include" }; return fetch(`${getAPIUrl()}auth/users/me`, requestOptions) diff --git a/src/routers/auth.py b/src/routers/auth.py index da46b4b5..2e6748b2 100644 --- a/src/routers/auth.py +++ b/src/routers/auth.py @@ -1,9 +1,9 @@ -from fastapi import Depends, FastAPI, APIRouter, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from pydantic import BaseModel +from fastapi import Depends, APIRouter, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm from src.services.auth import * from src.services.users import * -from datetime import datetime, timedelta +from datetime import timedelta +from fastapi.responses import JSONResponse router = APIRouter() @@ -24,4 +24,8 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + + response = JSONResponse(content={"access_token" : access_token ,"token_type": "bearer"}) + response.set_cookie(key="user_token", value=access_token, httponly=True, expires="3600",secure=True) + + return response