File size: 20,657 Bytes
2476a51
f95433e
2476a51
488c02b
2476a51
59ac5b7
2c0b3d9
 
841d578
2c0b3d9
 
 
 
 
1d62c79
9c6d234
1d62c79
9c6d234
 
2476a51
1d62c79
0052143
9c6d234
2c0b3d9
9c6d234
 
 
 
fce8ee7
2c0b3d9
 
 
9c6d234
 
81a2e90
67638d2
4775141
2c0b3d9
 
 
 
 
 
 
 
 
 
 
 
 
584f738
9c6d234
 
 
6b4e76c
 
9c6d234
 
6b4e76c
9c6d234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5764b08
 
4a003a6
b4e60c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c97e24
b4e60c6
 
14162c4
1bfa413
 
 
f7604d0
1bfa413
 
 
 
 
 
 
 
 
 
 
 
5764b08
1bfa413
 
 
 
 
 
 
 
5764b08
b4e60c6
5129ab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4e60c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab95e7c
3391487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ef3ea6
3391487
 
40e39c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3391487
0872457
 
 
 
 
 
 
 
 
 
 
 
 
 
f0b2666
0872457
 
0ef3ea6
0872457
 
 
51197de
 
 
42868e8
 
89ee564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51197de
 
89ee564
 
98f984a
89ee564
98f984a
 
 
89ee564
b5d2082
47cfbd5
3cbd46c
47cfbd5
 
 
 
 
 
 
ba5569f
89ee564
 
42868e8
7821ebd
 
 
361449c
 
 
 
 
 
 
f442212
 
361449c
 
 
 
7821ebd
2c0b3d9
 
 
 
 
 
 
 
97db5c0
 
 
2c0b3d9
 
eca0026
 
 
 
2c0b3d9
eca0026
97db5c0
 
 
eca0026
 
361449c
 
 
 
 
 
 
 
 
 
 
 
 
2c0b3d9
361449c
 
 
 
b904717
 
361449c
 
 
 
 
 
6c20a60
361449c
 
b904717
 
2c0b3d9
 
 
 
 
 
 
 
 
 
9c6d234
2c0b3d9
 
 
 
 
 
 
 
 
 
 
 
1e17d31
 
 
7236499
1e17d31
7cbd47d
 
1e17d31
7236499
 
 
 
 
 
 
 
 
 
 
1e17d31
7236499
 
 
 
 
 
 
 
 
 
 
97db5c0
063b9b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841d578
 
2c0b3d9
 
 
9c6d234
2c0b3d9
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

from fastapi import FastAPI, Depends, HTTPException, Request, Form, status, Header
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from sqlalchemy.orm import Session
from database import get_db, get_user_by_email
from models import User
from passlib.context import CryptContext
from datetime import datetime, timedelta
import jwt
from emailx import send_verification_email, generate_verification_token

from fastapi.staticfiles import StaticFiles

from typing import Optional
import httpx
import os
from starlette.middleware.sessions import SessionMiddleware
from authlib.integrations.starlette_client import OAuth



# Environment variables
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
SECRET_KEY = os.getenv('SecretKey', 'default_secret')
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

# FastAPI and OAuth setup
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
oauth = OAuth()

# Password context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# OAuth2 scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

class TokenData(BaseModel):
    token: str

class UserCreate(BaseModel):
    username: str
    email: str
    password: str
 #   confirm_password: str
# OAuth Configuration
oauth.register(
    name='google',
    client_id=os.environ['GOOGLE_CLIENT_ID'],
    client_secret=os.environ['GOOGLE_CLIENT_SECRET'],
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    authorize_params=None,
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'}
)

# Static and template configurations
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

# OAuth routes
@app.get("/login/oauth")
async def login_oauth(request: Request):
    redirect_uri = request.url_for('auth_callback')
    return await oauth.google.authorize_redirect(request, redirect_uri)
    
@app.get("/auth/callback")
async def auth_callback(request: Request, db: Session = Depends(get_db)):
    token = await oauth.google.authorize_access_token(request)
    user_info = await oauth.google.parse_id_token(request, token)
    request.session["user_info"] = user_info

    db_user = db.query(User).filter(User.email == user_info['email']).first()
    if not db_user:
        db_user = User(email=user_info['email'], username=user_info['name'], is_verified=True)
        db.add(db_user)
        db.commit()
        db.refresh(db_user)

    access_token = create_access_token(data={"sub": db_user.email}, expires_delta=timedelta(minutes=30))
    response = RedirectResponse(url="/protected")
    response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
    return response
    
@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db), recaptcha_token: str = Form(...)):
    # Perform reCAPTCHA verification first
    
    recaptcha_secret = '6LeSJgwpAAAAAJrLrvlQYhRsOjf2wKXee_Jc4Z-k'  # Replace with your reCAPTCHA secret key
    recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
    recaptcha_data = {
        'secret': recaptcha_secret,
        'response': recaptcha_token
    }
    
    async with httpx.AsyncClient() as client:
        recaptcha_response = await client.post(recaptcha_url, data=recaptcha_data)
    
    recaptcha_result = recaptcha_response.json()
    print(recaptcha_result)  # or use proper logging
    if not recaptcha_result.get('success', False):
        raise HTTPException(status_code=400, detail="reCAPTCHA validation failed.")
    if not form_data.username or not form_data.password:
        raise HTTPException(status_code=400, detail="Invalid email or password")
        
    user = authenticate_user(db, form_data.username, form_data.password)
    if user and user.is_verified:  # Check if user is verified
        access_token = create_access_token(
            data={"sub": user.email},
            expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        )

        # Redirect the user to the protected route with the token in the URL
        url = app.url_path_for("get_protected")  # Ensure you have a name="get_protected" in your app.get("/protected") decorator
        #return RedirectResponse(url=f"/protected?token={access_token}", status_code=status.HTTP_303_SEE_OTHER)
        #return RedirectResponse(f"{url}?token={access_token}")

        response = RedirectResponse(f"{url}?token={access_token}", status_code=status.HTTP_303_SEE_OTHER)
        response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
       # response.set_cookie(key="access_token", value=access_token, httponly=True)
        return response
    elif user and not user.is_verified:  # User is not verified
        raise HTTPException(
            status_code=400,
            detail="You must verify your email before accessing this resource."
        )
    else:
        # If authentication fails, return to the login page with an error message
        return templates.TemplateResponse(
            "login.html", 
            {"request": request, "error_message": "Invalid email or password"}
        )
    
@app.get("/login", response_class=HTMLResponse)
async def login(request: Request, db: Session = Depends(get_db)):
    access_token = request.cookies.get("access_token")

    if access_token:
        try:
            user_email = verify_token(access_token.split("Bearer ")[1])
            if user_email:
                # Retrieve the user from the database
                db_user = db.query(User).filter(User.email == user_email).first()
                if not db_user:
                    raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="User not found")

                # Check if user is verified
                if not db_user.is_verified:
                    raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="User is not verified")

                # Create a new access token for the user
                new_access_token = create_access_token(
                    data={"sub": db_user.email},
                    expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES)
                )

                # Redirect the user to the protected route
                url = app.url_path_for("get_protected")
                response = RedirectResponse(url)
                response.set_cookie(key="access_token", value=f"Bearer {new_access_token}", httponly=True)
                return response
        except ExpiredSignatureError:
            # Token has expired. You could redirect to the login page or inform the user
            raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")
        except InvalidTokenError:
            # Token is invalid, inform the user or redirect
            raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid token")
        except Exception as e:
            # General exception, log this exception for debugging
            # Respond with a generic error message
            raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="An error occurred")

    # If not authenticated, show the login page with Google OAuth option
    google_oauth_url = request.url_for("login_oauth")  # URL to initiate Google OAuth
    return templates.TemplateResponse("login.html", {"request": request, "google_oauth_url": google_oauth_url})

@app.get("/register/google")
async def register_google(request: Request):
    # Redirect to Google OAuth
    redirect_uri = request.url_for('auth_callback')
    return await oauth.google.authorize_redirect(request, redirect_uri)

@app.get("/auth/callback")
async def auth_callback(request: Request, db: Session = Depends(get_db)):
    # Handle the Google OAuth callback and user registration
    token = await oauth.google.authorize_access_token(request)
    user_info = await oauth.google.parse_id_token(request, token)
    
    # Check if user already exists
    existing_user = db.query(User).filter(User.email == user_info['email']).first()
    if existing_user:
        # User already exists, handle accordingly (e.g., log in the user)
        # ...
        pass
    else:
        # Register new user
        new_user = User(
            email=user_info['email'],
            username=user_info.get('name'),
            is_verified=True  # Assuming Google users are verified by default
        )
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
        # Store user info in session or create a token as needed
        request.session["user_info"] = {"username": new_user.username, "email": new_user.email}
        # ...

    # Redirect to a success or dashboard page
    return RedirectResponse(url="/registration_successful")

@app.post("/registration_successful", response_class=HTMLResponse)
async def registration_successful(request: Request, db: Session = Depends(get_db)):
    # Assuming the OAuth process has been completed and user info is stored in the session or a similar mechanism
    user_info = request.session.get("user_info")  # Replace with your method of retrieving user info

    if not user_info:
        raise HTTPException(status_code=401, detail="User not authenticated")

    email = user_info["email"]
    db_user = db.query(User).filter(User.email == email).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    # Create an access token for the user
    access_token = create_access_token(
        data={"sub": db_user.email},
        expires_delta=timedelta(minutes=auth_views.ACCESS_TOKEN_EXPIRE_MINUTES)
    )

    # Redirect the user to the protected route
    response = RedirectResponse(url="/login")
    response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
    return response
    
async def verify_recaptcha(recaptcha_token: str) -> bool:
    recaptcha_secret = '6LeSJgwpAAAAAJrLrvlQYhRsOjf2wKXee_Jc4Z-k'  # Replace with your reCAPTCHA secret key
    recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
    recaptcha_data = {
        'secret': recaptcha_secret,
        'response': recaptcha_token
    }

    async with httpx.AsyncClient() as client:
        recaptcha_response = await client.post(recaptcha_url, data=recaptcha_data)

    recaptcha_result = recaptcha_response.json()
    print(recaptcha_result)  # or use proper logging

    return recaptcha_result.get('success', False)

@app.get("/verify", response_class=HTMLResponse)
async def verify_email(token: str, db: Session = Depends(get_db)):
    user = get_user_by_verification_token(db, token)
    if not user:
        raise HTTPException(status_code=400, detail="Invalid verification token")

    if user.is_verified:
        raise HTTPException(status_code=400, detail="Email already verified")

    user.is_verified = True
    user.email_verification_token = None  # Clear the verification token
    db.commit()

    # Create access token for the user after successful verification
    access_token = create_access_token(data={"sub": user.email}, expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))

    # Redirect to the protected route and set the token in a secure, HTTP-only cookie
    response = RedirectResponse(url="/protected")
    response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True, secure=True, samesite='Lax')
    return response

def is_username_available(db: Session, username: str) -> bool:
    return db.query(User).filter(User.username == username).first() is None
    
@app.get("/register", response_class=HTMLResponse)
async def register_get(request: Request):
    return templates.TemplateResponse("register.html", {"request": request, "google_oauth_url": request.url_for("login_oauth")})

@app.post("/register")
async def register_post(
    request: Request,
    username: str = Form(...),
    email: str = Form(...),
    password: str = Form(...),
    confirm_password: str = Form(...),
    recaptcha_token: str = Form(...),
    db: Session = Depends(get_db)
):
    if not await verify_recaptcha(recaptcha_token):
        return templates.TemplateResponse("register.html", {"request": request, "error_message": "reCAPTCHA validation failed."})

    if password != confirm_password:
        return templates.TemplateResponse("register.html", {"request": request, "error_message": "Passwords do not match."})

    user_data = UserCreate(username=username, email=email, password=password)
    if not is_username_available(db, user_data.username):
        raise HTTPException(status_code=400, detail="Username already taken")
    try:
        registered_user = register_user(user_data, db)

        # Create an access token
        access_token = create_access_token(data={"sub": registered_user.email}, 
        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))

        # Redirect to the protected route
        url = app.url_path_for("get_protected")
        #response = RedirectResponse(url, status_code=status.HTTP_303_SEE_OTHER)
       # response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
        #response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True, secure=True, samesite='Lax')
        #return response
          # Return the access token and redirection URL in the response
        return JSONResponse(content={
        "access_token": access_token,
        "redirect_url": url
    })

    except HTTPException as e:
        return templates.TemplateResponse("register.html", {"request": request, "error_message": e.detail})
    
@app.get("/", response_class=HTMLResponse)
async def landing(request: Request):
    return templates.TemplateResponse("landing.html", {"request": request})

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

def authenticate_user(db: Session, email: str, password: str):
    user = db.query(User).filter(User.email == username).first()
    if not user or not verify_password(password, user.hashed_password):
        return False
    return user

    
def create_access_token(data: dict, expires_delta: timedelta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)):
    to_encode = data.copy()
    expire = datetime.utcnow() + expires_delta
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def verify_token(token: str = Depends(oauth2_scheme)):
    if token.startswith("Bearer "):
        token = token.split(" ")[1]  # Strip the 'Bearer ' prefix if it exists

    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_email = payload.get("sub")
        if user_email is None:
            raise HTTPException(status_code=401, detail="Invalid authentication credentials")
        return user_email
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token has expired")
    except jwt.PyJWTError as e:
        # Log the error for debugging
        print(f"JWT decoding error: {e}")
        raise HTTPException(status_code=401, detail="Could not validate credentials")
        
def validate_token(token: str):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
        return TokenData(username=username)
    except JWTError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")

@app.get("/token/validate")
async def token_validate(token: str = Depends(oauth2_scheme)):
    return validate_token(token)

@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    return await login_for_access_token(form_data.username, form_data.password, db)

async def login_for_access_token(username: str, password: str, db: Session):
    user = authenticate_user(db,form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = create_access_token(data={"sub": user.email})
    return {"access_token": access_token, "token_type": "bearer"}

def authenticate_user(db: Session, username: str, password: str):
    user = get_user_by_email(db, username)
    if not user or not pwd_context.verify(password, user.hashed_password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password")
    return user

def register_user(user_data: UserCreate, db: Session):
    if get_user_by_email(db, user_data.email):
        raise HTTPException(status_code=400, detail="Email already registered")

    hashed_password = pwd_context.hash(user_data.password)
    verification_token = generate_verification_token(user_data.email)
    reset_link = f"http://gregniuki-loginauth.hf.space/verify?token={verification_token}"
    send_verification_email(user_data.email, reset_link)

    new_user = User(
        email=user_data.email,
        username=user_data.username,
        hashed_password=hashed_password,
        email_verification_token=verification_token
    )
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user

@app.get("/protected", response_class=HTMLResponse)
async def get_protected(
    request: Request,
    db: Session = Depends(get_db),
    authorization: Optional[str] = Header(None),# token from Authorization header
    token: Optional[str] = None
):
    # Try to get the token from the Authorization header
    if authorization:
        scheme, _, token = authorization.partition(' ')
        if scheme.lower() != 'bearer':
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication scheme")
    else:
        # Fall back to the cookie
        token = request.cookies.get("access_token")

    if not token:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")

    # Verify the token and get user
    try:
        user_email = verify_token(token)  # Implement your token verification logic
        db_user = get_user_by_email(db, user_email)
        if db_user is None or not db_user.is_verified:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found or not verified in the database")

        # Render a template response
        return templates.TemplateResponse("protected.html", {"request": request, "user": db_user.username})
    except Exception as e:  # Replace with specific exceptions as per your verification logic
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
    
def verify_email(verification_token: str, db: Session = Depends(get_db)):
    # Verify the email using the token
    user = get_user_by_verification_token(db, verification_token)
    
    if not user:
        raise HTTPException(status_code=400, detail="Invalid verification token")

    if user.is_verified:
        raise HTTPException(status_code=400, detail="Email already verified")

    # Mark the email as verified
    user.is_verified = True
    user.email_verification_token = None  # Optionally clear the verification token
    db.commit()
    return {"message": "Email verification successful"}
    
def get_user_by_verification_token(db: Session, verification_token: str):
    return db.query(User).filter(User.email_verification_token == verification_token).first()

def reset_password(user: User, db: Session):
    verification_token = generate_verification_token(user.email)
    reset_link = f"http://gregniuki-loginauth.hf.space/reset-password?token={verification_token}"
    send_verification_email(user.email, reset_link)

    user.email_verification_token = verification_token
    db.commit()

def get_current_user(token: str = Depends(verify_token)):
    return token