File size: 10,002 Bytes
b7a7f32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
from typing import Any, List, Optional

import aiofiles
from fastapi import APIRouter, Body
from fastapi import Cookie as ReqCookie
from fastapi import Depends, File, HTTPException, Request, UploadFile, Form
from fastapi.params import Cookie
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import update
from sqlalchemy.sql.functions import current_user
from starlette.responses import JSONResponse, Response
from starlette.status import HTTP_401_UNAUTHORIZED

import cruds
import models
import schemas
from core import throttle
from core.config import settings
from core.db import redis_session_client
from core.security import (
    create_sesssion_token,
    get_password_hash,
    create_2fa_temp_token,
    create_passwordless_create_token,
    authorize_passwordless_token,
    verify_passwordless_token,
)
from cruds import group
from schemas.user import UserUpdate, VerifyUser
from utils import deps
from utils.utils import (
    expire_web_session,
    generate_password_reset_token,
    send_reset_password_email,
    send_verification_email,
    verify_password_reset_token,
    verify_user_verify_token,
)

router = APIRouter()


@router.post(
    "/web/",
    response_model=Optional[schemas.user.UserLoginReturn],
    response_model_exclude_none=True,
)
async def login_web_session(
    db: Session = Depends(deps.get_db),
    *,
    form_data: schemas.LoginData,
    request: Request,
    response: Response,
) -> Any:
    if not form_data.username:
        form_data.username = form_data.email

    user = cruds.crud_user.authenticate(
        db, email=form_data.username, password=form_data.password
    )

    if not user:
        raise HTTPException(
            status_code=401, detail="Error ID: 111"
        )  # Incorrect email or password
    elif not user.is_active:
        raise HTTPException(
            status_code=401, detail="Error ID: 112")  # Inactive user

    if user.two_fa_secret:
        temp_token = await create_2fa_temp_token(user, form_data.remember_me)
        response.set_cookie("temp_session", temp_token, httponly=True)
        return {
            "msg": "2FA required before proceeding!",
            "two_fa_required": True,
            "user": None,
        }
    else:
        session_token = await create_sesssion_token(
            user, form_data.remember_me, request
        )
        response.set_cookie("session", session_token, httponly=True)
        return {
            "msg": "Logged in successfully!",
            "user": user,
            "two_fa_required": False,
        }


@router.get("/password-less/create")
async def generate_passwordless_login_token(
    db: Session = Depends(deps.get_db),
):
    token = await create_passwordless_create_token()

    return {"token": token}


@router.post("/password-less/authorize")
async def authorize_passwordless_login(
    db: Session = Depends(deps.get_db),
    current_user: models.User = Depends(deps.get_current_active_user),
    token: str = Form(None),
):
    _ = await authorize_passwordless_token(current_user, token)

    return {"msg": "Success"}


@router.post(
    "/password-less/verify",
    response_model=Optional[schemas.user.UserLoginReturn],
    response_model_exclude_none=True,
)
async def verify_passwordless_login(
    response: Response,
    request: Request,
    db: Session = Depends(deps.get_db),
    token: str = Form(None),
):
    user_id = await verify_passwordless_token(token)

    user = cruds.crud_user.get_by_id(db, id=user_id)

    if not user:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED, detail="Invalid user!")

    session_token = await create_sesssion_token(user, True, request)
    response.set_cookie("session", session_token, httponly=True)
    return {"msg": "Logged in successfully!", "user": user, "two_fa_required": False}


@router.post("/signup/", response_model=schemas.Msg)
async def sign_up(
    *,
    db: Session = Depends(deps.get_db),
    user_in: schemas.UserSignUp,
) -> Any:
    if not settings.USERS_OPEN_REGISTRATION:
        raise HTTPException(
            status_code=403,
            detail="Error ID: 129",
        )  # Open user registration is forbidden on this server
    user = cruds.crud_user.get_by_email(db, email=user_in.email)
    if user:
        raise HTTPException(
            status_code=400,
            detail="Email is associated with another user!",
        )  # The user with this username already exists in the system
    email_host = user_in.email[user_in.email.index("@") + 1:]

    if email_host not in settings.ALLOWED_EMAIL_HOST:
        raise HTTPException(
            status_code=403,
            # TODO: Reflected XSS test
            detail=f"Email of host {email_host} not allowed!",
        )

    user = cruds.crud_user.create(
        db, obj_in=schemas.UserCreate(**user_in.dict(), profile_pic="")
    )
    await send_verification_email(user=user)
    return schemas.Msg(msg="Success")


@router.post("/resend-verification-email/")
async def resend_verification_email(
    email: str,
    current_user: models.User = Depends(deps.get_current_admin_or_above),
    db: Session = Depends(deps.get_db),
):
    user = cruds.crud_user.get_by_email(db=db, email=email)
    if not user:
        raise HTTPException(status_code="404", detail="User doesn't exist")

    await send_verification_email(user)
    return schemas.Msg(msg="Success")


@router.post("/change-password/")
async def change_password(
    current_password: str = Body(...),
    new_password: str = Body(...),
    current_user: models.User = Depends(deps.get_current_user),
    db: Session = Depends(deps.get_db),
) -> Any:
    user = cruds.crud_user.authenticate(
        db, email=current_user.email, password=current_password
    )

    if not user:
        raise HTTPException(
            status_code=403, detail="Error ID: 111"
        )  # Incorrect email or password

    data = schemas.user.PasswordUpdate(
        password=new_password,
    )

    cruds.crud_user.update(db=db, db_obj=current_user, obj_in=data)


@router.get("/active-sessions/", response_model=List[schemas.auth.ActiveSession])
async def get_active_sessions(
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    active_sessions = json.loads(
        await redis_session_client.client.get(
            f"user_{current_user.id}_sessions", encoding="utf-8"
        )
    )
    return active_sessions.get("sessions")


@router.get("/logout-all-sessions/")
async def logout_all_sessions(
    current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    active_sessions = json.loads(
        await redis_session_client.client.get(
            f"user_{current_user.id}_sessions", encoding="utf-8"
        )
    )

    for session in active_sessions.get("sessions"):
        await redis_session_client.client.expire(session.get("token"), 0)

    await redis_session_client.client.expire(f"user_{current_user.id}_sessions", 0)

    resp = JSONResponse({"status": "success"})
    resp.delete_cookie("session")
    return resp


@router.post("/password-recovery/", response_model=schemas.Msg)
# @throttle.ip_throttle(rate=3, per=1 * 60 * 60)
# @throttle.ip_throttle(rate=1, per=20)
async def recover_password(
    request: Request,
    email: str,
    db: Session = Depends(deps.get_db),
) -> Any:
    """
    Password Recovery
    """
    user = cruds.crud_user.get_by_email(db, email=email)

    if not user:
        raise HTTPException(
            status_code=404,
            detail="Error ID: 113",
        )  # The user with this username does not exist in the system.
    await send_reset_password_email(user=user)
    return {"msg": "Password recovery email sent"}


@router.post("/reset-password/", response_model=schemas.Msg)
async def reset_password(
    request: Request,
    token: str = Body(...),
    new_password: str = Body(...),
    db: Session = Depends(deps.get_db),
) -> Any:
    """
    Reset password
    """
    uid = await verify_password_reset_token(token)
    user = cruds.crud_user.get_by_id(db, id=uid)
    if not user:
        raise HTTPException(
            status_code=404,
            detail="Error ID: 114",
        )  # The user with this username does not exist in the system.
    elif not cruds.crud_user.is_active(user):
        raise HTTPException(
            status_code=400, detail="Error ID: 115")  # Inactive user
    hashed_password = get_password_hash(new_password)
    user.hashed_password = hashed_password
    db.add(user)
    db.commit()
    return {"msg": "Password updated successfully"}


@router.post("/verify/", response_model=schemas.Msg)
async def verify_account(
    token: str,
    db: Session = Depends(deps.get_db),
) -> Any:
    uid = await verify_user_verify_token(token)
    user = cruds.crud_user.get_by_id(db, id=uid)
    if not user:
        raise HTTPException(
            status_code=404,
            detail="Error ID: 146",
        )  # The user with this username does not exist in the system.
    cruds.crud_user.verify_user(db=db, db_obj=user)
    return {"msg": "Verified successfully"}


@router.get("/logout/", response_model=schemas.Token)
async def session_logout(
    session: str = ReqCookie(None),
) -> Any:
    if not session:
        raise HTTPException(status_code=401, detail="Invalid session token!")
    await expire_web_session(session)
    resp = JSONResponse({"status": "success"})
    resp.delete_cookie("session")
    return resp


@router.get("/thtest1")
@throttle.ip_throttle(rate=10, per=60)
async def throttle_test(
    request: Request,
    db: Session = Depends(deps.get_db),
    current_user: models.User = Depends(deps.get_current_user),
):
    return "Throttle test endpoint 1 Hello"


@router.get("/thtest2")
@throttle.user_throttle(rate=20, per=60)
async def throttle_test1(
    request: Request,
    db: Session = Depends(deps.get_db),
    current_user: models.User = Depends(deps.get_current_user),
):
    return "Throttle test endpoint 2"