mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-18 11:59:26 +00:00
feat: init login & register from frontend
This commit is contained in:
parent
67ce2e7371
commit
8cc727e309
8 changed files with 90 additions and 14 deletions
18
app.py
18
app.py
|
|
@ -1,9 +1,7 @@
|
||||||
from typing import Union
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from src import main
|
|
||||||
from fastapi.staticfiles import StaticFiles
|
|
||||||
from src.main import global_router
|
from src.main import global_router
|
||||||
import pymongo
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
|
||||||
# Init
|
# Init
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
|
|
@ -12,9 +10,19 @@ app = FastAPI(
|
||||||
version="0.1.0",
|
version="0.1.0",
|
||||||
root_path="/"
|
root_path="/"
|
||||||
)
|
)
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
app.include_router(global_router)
|
app.include_router(global_router)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
async def root():
|
async def root():
|
||||||
return {"Message": "Welcome to LearnHouse ✨"}
|
return {"Message": "Welcome to LearnHouse ✨"}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import Layout from "../components/ui/layout";
|
import Layout from "../components/ui/layout";
|
||||||
import { Title } from "../components/ui/styles/title";
|
import { Title } from "../components/ui/styles/title";
|
||||||
|
import { loginAndGetToken } from "../services/auth";
|
||||||
|
|
||||||
const Login = () => {
|
const Login = () => {
|
||||||
const [email, setEmail] = React.useState("");
|
const [email, setEmail] = React.useState("");
|
||||||
|
|
@ -10,6 +11,7 @@ const Login = () => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
console.log({ email, password });
|
console.log({ email, password });
|
||||||
alert(JSON.stringify({ email, password }));
|
alert(JSON.stringify({ email, password }));
|
||||||
|
loginAndGetToken(email, password);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEmailChange = (e: any) => {
|
const handleEmailChange = (e: any) => {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import Layout from "../components/ui/layout";
|
import Layout from "../components/ui/layout";
|
||||||
import { Title } from "../components/ui/styles/title";
|
import { Title } from "../components/ui/styles/title";
|
||||||
|
import { signup } from "../services/auth";
|
||||||
|
|
||||||
const SignUp = () => {
|
const SignUp = () => {
|
||||||
const [email, setEmail] = React.useState("");
|
const [email, setEmail] = React.useState("");
|
||||||
|
|
@ -11,6 +12,7 @@ const SignUp = () => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
console.log({ email, password, username });
|
console.log({ email, password, username });
|
||||||
alert(JSON.stringify({ email, password, username }));
|
alert(JSON.stringify({ email, password, username }));
|
||||||
|
signup({ email, password, username });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleEmailChange = (e: any) => {
|
const handleEmailChange = (e: any) => {
|
||||||
|
|
|
||||||
61
front/services/auth.ts
Normal file
61
front/services/auth.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
import { getAPIUrl } from "./config";
|
||||||
|
|
||||||
|
interface LoginAndGetTokenResponse {
|
||||||
|
access_token: "string";
|
||||||
|
token_type: "string";
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO : everything in this file need to be refactored / mvp phase
|
||||||
|
|
||||||
|
export async function loginAndGetToken(username: string, password: string): Promise<LoginAndGetTokenResponse> {
|
||||||
|
// Request Config
|
||||||
|
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 = {
|
||||||
|
method: "POST",
|
||||||
|
headers: HeadersConfig,
|
||||||
|
body: urlencoded,
|
||||||
|
redirect: "follow",
|
||||||
|
};
|
||||||
|
|
||||||
|
return fetch(`${getAPIUrl()}auth/token`, requestOptions)
|
||||||
|
.then((result) => result.json())
|
||||||
|
.catch((error) => console.log("error", error));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserInfo(token: string): Promise<any> {
|
||||||
|
const HeadersConfig = new Headers({ Authorization: `Bearer ${token}`, Origin: "http://localhost:3000" });
|
||||||
|
const requestOptions: any = {
|
||||||
|
method: "GET",
|
||||||
|
headers: HeadersConfig,
|
||||||
|
redirect: "follow",
|
||||||
|
};
|
||||||
|
|
||||||
|
return fetch(`${getAPIUrl()}auth/users/me`, requestOptions)
|
||||||
|
.then((result) => result.json())
|
||||||
|
.catch((error) => console.log("error", error));
|
||||||
|
}
|
||||||
|
|
||||||
|
// signup
|
||||||
|
|
||||||
|
interface NewAccountBody {
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function signup(body: NewAccountBody): Promise<any> {
|
||||||
|
const HeadersConfig = new Headers({ "Content-Type": "application/json" });
|
||||||
|
|
||||||
|
const requestOptions: any = {
|
||||||
|
method: "POST",
|
||||||
|
headers: HeadersConfig,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
redirect: "follow",
|
||||||
|
};
|
||||||
|
|
||||||
|
return fetch(`${getAPIUrl()}users/`, requestOptions)
|
||||||
|
.then((result) => result.json())
|
||||||
|
.catch((error) => console.log("error", error));
|
||||||
|
}
|
||||||
3
front/services/config.ts
Normal file
3
front/services/config.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
const LEARNHOUSE_API_URL = "http://localhost:1338/api/";
|
||||||
|
|
||||||
|
export const getAPIUrl = () => LEARNHOUSE_API_URL;
|
||||||
|
|
@ -17,7 +17,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Incorrect username or password",
|
detail="Incorrect Email or password",
|
||||||
headers={"WWW-Authenticate": "Bearer"},
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
)
|
)
|
||||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
|
|
||||||
|
|
@ -23,8 +23,8 @@ class TokenData(BaseModel):
|
||||||
#### Classes ####################################################
|
#### Classes ####################################################
|
||||||
|
|
||||||
|
|
||||||
async def authenticate_user(username: str, password: str):
|
async def authenticate_user(email: str, password: str):
|
||||||
user = await security_get_user(username)
|
user = await security_get_user(email)
|
||||||
if not user:
|
if not user:
|
||||||
return False
|
return False
|
||||||
if not await security_verify_password(password, user.password):
|
if not await security_verify_password(password, user.password):
|
||||||
|
|
|
||||||
|
|
@ -12,10 +12,10 @@ class User(BaseModel):
|
||||||
username: str
|
username: str
|
||||||
email: str
|
email: str
|
||||||
full_name: str | None = None
|
full_name: str | None = None
|
||||||
disabled: bool | None = None
|
disabled: bool | None = False
|
||||||
avatar_url: str | None = None
|
avatar_url: str | None = None
|
||||||
verified: bool
|
verified: bool | None = False
|
||||||
user_type: str
|
user_type: str | None = None
|
||||||
bio: str | None = None
|
bio: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -69,15 +69,15 @@ async def get_user_by_userid(user_id: str):
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
async def security_get_user(username: str):
|
async def security_get_user(email: str):
|
||||||
check_database()
|
check_database()
|
||||||
users = learnhouseDB["users"]
|
users = learnhouseDB["users"]
|
||||||
|
|
||||||
user = users.find_one({"username": username})
|
user = users.find_one({"email": email})
|
||||||
|
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_409_CONFLICT, detail="User does not exist")
|
status_code=status.HTTP_409_CONFLICT, detail="User with Email does not exist")
|
||||||
|
|
||||||
return UserInDB(**user)
|
return UserInDB(**user)
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue