|
1 | 1 | from datetime import timedelta
|
2 | 2 | from typing import Annotated, Any
|
3 | 3 |
|
4 |
| -from fastapi import APIRouter, Depends, HTTPException |
5 |
| -from fastapi.responses import HTMLResponse |
| 4 | +import requests |
| 5 | +from fastapi import APIRouter, Depends, HTTPException, Response |
| 6 | +from fastapi.responses import HTMLResponse, RedirectResponse |
6 | 7 | from fastapi.security import OAuth2PasswordRequestForm
|
7 | 8 |
|
8 | 9 | from app import crud
|
9 | 10 | from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
|
10 | 11 | from app.core import security
|
11 | 12 | from app.core.config import settings
|
12 | 13 | from app.core.security import get_password_hash
|
13 |
| -from app.models import Message, NewPassword, Token, UserPublic |
| 14 | +from app.models import Message, NewPassword, Token, UserCreateOauth, UserPublic |
14 | 15 | from app.utils import (
|
15 | 16 | generate_password_reset_token,
|
16 | 17 | generate_reset_password_email,
|
@@ -123,3 +124,155 @@ def recover_password_html_content(email: str, session: SessionDep) -> Any:
|
123 | 124 | return HTMLResponse(
|
124 | 125 | content=email_data.html_content, headers={"subject:": email_data.subject}
|
125 | 126 | )
|
| 127 | + |
| 128 | + |
| 129 | +# Redirect user to Google's OAuth2 login page |
| 130 | +@router.get("/login/google") |
| 131 | +def login_google(): |
| 132 | + google_auth_url = ( |
| 133 | + "https://accounts.google.com/o/oauth2/v2/auth?" |
| 134 | + f"client_id={settings.GOOGLE_CLIENT_ID}&" |
| 135 | + "redirect_uri={settings.GOOGLE_REDIRECT_URI}&" |
| 136 | + "response_type=code&" |
| 137 | + "scope=email profile" |
| 138 | + ) |
| 139 | + return RedirectResponse(google_auth_url) |
| 140 | + |
| 141 | + |
| 142 | +# Handle Google OAuth callback |
| 143 | +@router.get("/auth/google") |
| 144 | +def google_oauth(session: SessionDep, code: str, response: Response): |
| 145 | + token_url = "https://oauth2.googleapis.com/token" |
| 146 | + token_data = { |
| 147 | + "code": code, |
| 148 | + "client_id": settings.GOOGLE_CLIENT_ID, |
| 149 | + "client_secret": settings.GOOGLE_CLIENT_SECRET, |
| 150 | + "redirect_uri": settings.GOOGLE_REDIRECT_URI, |
| 151 | + "grant_type": "authorization_code", |
| 152 | + } |
| 153 | + |
| 154 | + token_r = requests.post(token_url, data=token_data) |
| 155 | + token_json = token_r.json() |
| 156 | + |
| 157 | + if "error" in token_json: |
| 158 | + raise HTTPException( |
| 159 | + status_code=400, detail="Failed to retrieve token from Google" |
| 160 | + ) |
| 161 | + |
| 162 | + access_token = token_json["access_token"] |
| 163 | + |
| 164 | + # Get user info from Google |
| 165 | + user_info = requests.get( |
| 166 | + "https://www.googleapis.com/oauth2/v2/userinfo", |
| 167 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 168 | + ).json() |
| 169 | + |
| 170 | + # Check if the user already exists |
| 171 | + user = crud.get_user_by_email(session=session, email=user_info["email"]) |
| 172 | + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) |
| 173 | + if user: |
| 174 | + response = RedirectResponse("http://localhost:3000/dashboard") |
| 175 | + response.set_cookie( |
| 176 | + key="access_token", |
| 177 | + value=security.create_access_token( |
| 178 | + user.id, expires_delta=access_token_expires |
| 179 | + ), |
| 180 | + httponly=True, |
| 181 | + ) |
| 182 | + return response |
| 183 | + |
| 184 | + # Check if the app is open for new user registration |
| 185 | + if not settings.USERS_OPEN_REGISTRATION: |
| 186 | + raise HTTPException( |
| 187 | + status_code=403, |
| 188 | + detail="Open user registration is forbidden on this server", |
| 189 | + ) |
| 190 | + # Create a new user |
| 191 | + user_create = UserCreateOauth.model_validate( |
| 192 | + { |
| 193 | + "email": user_info["email"], |
| 194 | + "is_active": True, |
| 195 | + "is_superuser": False, |
| 196 | + "full_name": user_info["name"], |
| 197 | + "provider": "google", |
| 198 | + } |
| 199 | + ) |
| 200 | + user = crud.create_user_oauth(session=session, user_create=user_create) |
| 201 | + |
| 202 | + response = RedirectResponse("http://localhost:3000/dashboard") |
| 203 | + response.set_cookie( |
| 204 | + key="access_token", |
| 205 | + value=security.create_access_token(user.id, expires_delta=access_token_expires), |
| 206 | + httponly=True, |
| 207 | + ) |
| 208 | + return response |
| 209 | + |
| 210 | + |
| 211 | +# Handle Github OAuth callback |
| 212 | +@router.get("/auth/github") |
| 213 | +def github_oauth(session: SessionDep, code: str, response: Response): |
| 214 | + token_url = "https://github.com/login/oauth/access_token" |
| 215 | + token_data = { |
| 216 | + "code": code, |
| 217 | + "client_id": settings.GITHUB_CLIENT_ID, |
| 218 | + "client_secret": settings.GITHUB_CLIENT_SECRET, |
| 219 | + } |
| 220 | + headers = {"Accept": "application/json"} |
| 221 | + |
| 222 | + token_r = requests.post(token_url, data=token_data, headers=headers) |
| 223 | + token_json = token_r.json() |
| 224 | + if "error" in token_json: |
| 225 | + raise HTTPException( |
| 226 | + status_code=400, detail="Failed to retrieve token from Github" |
| 227 | + ) |
| 228 | + access_token = token_json["access_token"] |
| 229 | + # Get user info from Github |
| 230 | + user_info = requests.get( |
| 231 | + "https://api.github.com/user", |
| 232 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 233 | + ).json() |
| 234 | + |
| 235 | + user_emails = requests.get( |
| 236 | + "https://api.github.com/user/emails", |
| 237 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 238 | + ).json() |
| 239 | + |
| 240 | + # Check if the user already exists |
| 241 | + user = crud.get_user_by_email(session=session, email=user_emails[0]["email"]) |
| 242 | + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) |
| 243 | + if user: |
| 244 | + response = RedirectResponse("http://localhost:3000/dashboard") |
| 245 | + response.set_cookie( |
| 246 | + key="access_token", |
| 247 | + value=security.create_access_token( |
| 248 | + user.id, expires_delta=access_token_expires |
| 249 | + ), |
| 250 | + httponly=True, |
| 251 | + ) |
| 252 | + return response |
| 253 | + |
| 254 | + # Check if the app is open for new user registration |
| 255 | + if not settings.USERS_OPEN_REGISTRATION: |
| 256 | + raise HTTPException( |
| 257 | + status_code=403, |
| 258 | + detail="Open user registration is forbidden on this server", |
| 259 | + ) |
| 260 | + # Create a new user |
| 261 | + user_create = UserCreateOauth.model_validate( |
| 262 | + { |
| 263 | + "email": user_emails[0]["email"], |
| 264 | + "is_active": True, |
| 265 | + "is_superuser": False, |
| 266 | + "full_name": user_info["login"], |
| 267 | + "provider": "github", |
| 268 | + } |
| 269 | + ) |
| 270 | + user = crud.create_user_oauth(session=session, user_create=user_create) |
| 271 | + |
| 272 | + response = RedirectResponse("http://localhost:3000/dashboard") |
| 273 | + response.set_cookie( |
| 274 | + key="access_token", |
| 275 | + value=security.create_access_token(user.id, expires_delta=access_token_expires), |
| 276 | + httponly=True, |
| 277 | + ) |
| 278 | + return response |
0 commit comments