File size: 10,212 Bytes
75e2b6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app/routers/auth.py
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, EmailStr
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, timedelta
import random
import string
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import os
from app.database.database_query import DatabaseQuery
from app.middleware.auth import create_access_token, get_current_user
from dotenv import load_dotenv


load_dotenv()

SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
FROM_EMAIL = os.getenv("FROM_EMAIL")


router = APIRouter()
query = DatabaseQuery()

class LoginRequest(BaseModel):
    identifier: str
    password: str

class LoginResponse(BaseModel):
    message: str
    token: str

class RegisterRequest(BaseModel):
    username: str
    email: EmailStr
    password: str
    name: str
    age: int

class VerifyEmailRequest(BaseModel):
    username: str
    code: str

class ResendCodeRequest(BaseModel):
    username: str

class ForgotPasswordRequest(BaseModel):
    email: EmailStr

class ResetPasswordRequest(BaseModel):
    token: str
    password: str

class ChatSessionCheck(BaseModel):
    session_id: str

@router.post('/login', response_model=LoginResponse)
async def login(login_data: LoginRequest):
    try:
        identifier = login_data.identifier
        password = login_data.password

        user = query.get_user_by_identifier(identifier)
        if user:
            if not user.get('is_verified'):
                raise HTTPException(status_code=401, detail="Please verify your email before logging in")

            if check_password_hash(user['password'], password):
                access_token = create_access_token({"sub": user['username']})
                return {"message": "Login successful", "token": access_token}

        raise HTTPException(status_code=401, detail="Invalid username/email or password")
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))

@router.post('/register', status_code=201)
async def register(register_data: RegisterRequest):
    try:
        username = register_data.username
        email = register_data.email
        password = register_data.password
        name = register_data.name
        age = register_data.age
        
        if query.is_username_or_email_exists(username, email):
            raise HTTPException(status_code=409, detail="Username or email already exists")
            
        verification_code = ''.join(random.choices(string.digits, k=6))
        code_expiration = datetime.utcnow() + timedelta(minutes=10)
        hashed_password = generate_password_hash(password)
        created_at = datetime.utcnow()
        
        temp_user = {
            'username': username,
            'email': email,
            'password': hashed_password,
            'name': name,
            'age': age,
            'created_at': created_at,
            'verification_code': verification_code,
            'code_expiration': code_expiration
        }
        
        query.create_or_update_temp_user(username, email, temp_user)
        
        message = Mail(
            from_email=FROM_EMAIL,
            to_emails=email,
            subject='Verify your email address',
            html_content=f'''
            <p>Hi {name},</p>
            <p>Thank you for registering. Please use the following code to verify your email address:</p>
            <h2>{verification_code}</h2>
            <p>This code will expire in 10 minutes.</p>
            '''
        )
        
        try:
            sg = SendGridAPIClient(SENDGRID_API_KEY)
            sg.send(message)
        except Exception as e:
            raise HTTPException(status_code=500, detail="Failed to send verification email")

        return {"message": "Registration successful. A verification code has been sent to your email."}
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))

@router.post('/verify-email')
async def verify_email(verify_data: VerifyEmailRequest):
    try:
        username = verify_data.username
        code = verify_data.code
        
        temp_user = query.get_temp_user_by_username(username)
        if not temp_user:
            raise HTTPException(status_code=404, detail="User not found or already verified")

        if temp_user['verification_code'] != code:
            raise HTTPException(status_code=400, detail="Invalid verification code")

        if datetime.utcnow() > temp_user['code_expiration']:
            raise HTTPException(status_code=400, detail="Verification code has expired")
            
        user_data = temp_user.copy()
        user_data['is_verified'] = True
        user_data.pop('verification_code', None)
        user_data.pop('code_expiration', None)
        user_data.pop('_id', None)
        
        query.create_user_from_data(user_data)
        query.delete_temp_user(username)
        
        # Set default language to English
        query.set_user_language(username, "English")
        
        # Set default theme to light (passing false for dark theme)
        query.set_user_theme(username, False)

        default_preferences = {
            'keywords': True,
            'references': True, 
            'websearch': False,
            'personalized_recommendations': True,
            'environmental_recommendations': True
        }
        
        query.set_user_preferences(username, default_preferences)

        return {"message": "Email verification successful"}
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))

@router.post('/resend-code')
async def resend_code(resend_data: ResendCodeRequest):
    try:
        username = resend_data.username
        
        temp_user = query.get_temp_user_by_username(username)
        if not temp_user:
            raise HTTPException(status_code=404, detail="User not found or already verified")
            
        verification_code = ''.join(random.choices(string.digits, k=6))
        code_expiration = datetime.utcnow() + timedelta(minutes=10)
        
        temp_user['verification_code'] = verification_code
        temp_user['code_expiration'] = code_expiration
        
        query.create_or_update_temp_user(username, temp_user['email'], temp_user)
        
        message = Mail(
            from_email=FROM_EMAIL,
            to_emails=temp_user['email'],
            subject='Your new verification code',
            html_content=f'''
            <p>Hi {temp_user['name']},</p>
            <p>You requested a new verification code. Please use the following code to verify your email address:</p>
            <h2>{verification_code}</h2>
            <p>This code will expire in 10 minutes.</p>
            '''
        )
        
        try:
            sg = SendGridAPIClient(SENDGRID_API_KEY)
            sg.send(message)
        except Exception as e:
            raise HTTPException(status_code=500, detail="Failed to send verification email")

        return {"message": "A new verification code has been sent to your email."}
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))

@router.post('/checkChatsession')
async def check_chatsession(data: ChatSessionCheck, username: str = Depends(get_current_user)):
    session_id = data.session_id
    is_chat_exit = query.check_chat_session(session_id)
    return {"ischatexit": is_chat_exit}

@router.get('/check-token')
async def check_token(username: str = Depends(get_current_user)):
    try:
        return {'valid': True, 'user': username}
    except Exception as e:
        raise HTTPException(status_code=401, detail=str(e))

@router.post('/forgot-password')
async def forgot_password(data: ForgotPasswordRequest):
    try:
        email = data.email
        
        user = query.get_user_by_identifier(email)
        if not user:
            raise HTTPException(status_code=404, detail="Email not found")
            
        reset_token = ''.join(random.choices(string.ascii_letters + string.digits, k=32))
        expiration = datetime.utcnow() + timedelta(hours=1)
        
        query.store_reset_token(email, reset_token, expiration)
        
        reset_link = f"http://localhost:3000/reset-password?token={reset_token}"
        
        message = Mail(
            from_email=FROM_EMAIL,
            to_emails=email,
            subject='Reset Your Password',
            html_content=f'''
            <p>Hi,</p>
            <p>You requested to reset your password. Click the link below to reset it:</p>
            <p><a href="{reset_link}">Reset Password</a></p>
            <p>This link will expire in 1 hour.</p>
            <p>If you didn't request this, please ignore this email.</p>
            '''
        )
        
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        sg.send(message)

        return {"message": "Password reset instructions sent to email"}
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))

@router.post('/reset-password')
async def reset_password(data: ResetPasswordRequest):
    try:
        token = data.token
        new_password = data.password
        
        if not token or not new_password:
            raise HTTPException(status_code=400, detail="Token and new password are required")
            
        reset_info = query.verify_reset_token(token)
        if not reset_info:
            raise HTTPException(status_code=400, detail="Invalid or expired reset token")
            
        hashed_password = generate_password_hash(new_password)
        query.update_password(reset_info['email'], hashed_password)

        return {"message": "Password successfully reset"}
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        raise HTTPException(status_code=500, detail=str(e))