def login_authenticate(username: str, password: str, db: Session): """ 用户登陆成功后返回token,并将登陆时间写入数据库,登陆失败返回失败原因 """ result = {} user = Auth.authenticate_user(username, password, db) if not user: db.close() return common.falseReturn(result, '登录失败') # 登陆时间 login_time = int(time.time()) user.login_time = login_time DBUser.update_login_time(db, user.id, login_time) origin_data = {'user_id': user.id, 'login_time': login_time} access_token = Auth.encode_auth_token(origin_data, None).decode() bearer_token = 'Bearer ' + access_token result['user_id'] = user.id result['username'] = user.username result['access_token'] = access_token result['token_type'] = "bearer" print(result) rsp = common.trueReturn(result, '登录成功') rsp.set_cookie(key="Bearer", value=bearer_token) return rsp
async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): # 密码加密 password = Auth.get_password_hash(form_data.password) db_user = DBUser.get_by_username(db, form_data.username) if db_user: return db_user db_user = DBUser(username=form_data.username, password=password) DBUser.add(db, db_user) request.session['test'] = "test" return db_user
def authenticate_user(username: str, password: str, db: Session): user = DBUser.get_by_username(db, username) if not user: return False if not Auth.verify_password(password, user.password): return False return user
async def register(username: str, db: Session = Depends(get_db)): db_user = await DBUser.get_by_username(db, username) if db_user: return db_user db_user = DBUser(username=username) await DBUser.add(db, db_user) return db_user
def identifyAll(request): """ 用户鉴权 :return: list """ auth_header = request.headers.get('Authorization') logger.info('auth_header %s', auth_header) jwt_cookie = request.cookies.get('Bearer') logger.info('jwt_cookie %s', jwt_cookie) if (auth_header or jwt_cookie): auth_tokenArr = '' if (auth_header): auth_tokenArr = auth_header.split(" ") # print('auth token from auth_header. ', auth_header) else: auth_tokenArr = jwt_cookie.split(" ") # print('auth token from jwt_cookie. ', jwt_cookie) if (not auth_tokenArr or auth_tokenArr[0] != 'Bearer' or len(auth_tokenArr) != 2): result = common.falseContent('', '请传递正确的验证头信息') else: auth_token = auth_tokenArr[1] payload = Auth.decode_auth_token(auth_token) if not isinstance(payload, str): user_id = payload['data']['user_id'] login_time = payload['data']['login_time'] # get db db = get_db_local() user = DBUser.get_by_user_id(db, user_id) if (user is None): result = common.falseContent('', '找不到该用户信息') else: if (user.login_time == login_time): returnUser = {'user': user} result = common.trueContent(returnUser, '请求成功') else: result = common.falseContent( '', 'Token已更改,请重新登录获取') # close db db.close() else: result = common.falseContent('', payload) else: result = common.falseContent('', '没有提供认证token') return result
async def recover_password(email: EmailStr): """ Recover password """ record = await crud.user.get_by_email(email=email) if not record: raise HTTPException( status_code=404, detail="The user with this email does not exist in the system") user = DBUser(**record) password_reset_token = generate_password_reset_token(email=email, subject=user.id) send_reset_password_email(email=user.email, username=user.username, first_name=user.first_name, token=password_reset_token) return {"msg": "Password recovery email sent"}
async def login_route(request: Request, ticket: str = None, cas_client: CASClient = Depends(get_cas), db: Session = Depends(get_db)): current_time = datetime.datetime.now() if not ticket: # No ticket, the request come from end user, send to CAS login cas_login_url = cas_client.get_login_url() return RedirectResponse(url=cas_login_url) username, attributes, _ = cas_client.verify_ticket(ticket) request.session['username'] = username if not username: return {"success": 0, "message": "Invalid user! Retry logging in!"} else: logging.debug(f"CAS verify ticket response: user: {username}") existing = await DBUser.get_by_username(db, username) if existing: db_user = {"last_login": current_time} await DBUser.update(db, username, db_user) else: # add the initial state as unanswered db_user = DBUser( username=username, last_login=current_time, first_login=current_time, ) await DBUser.add(db, db_user) access_token = jwt.encode({ 'username': username }, str(SECRET_KEY), algorithm="HS256").decode() return { "access_token": access_token, "username": username, "token_type": "bearer", }
async def reset_password(token: str = Body(...), new_password: str = Body(...)): """ Reset password """ email = await verify_password_reset_token(token) if not email: raise HTTPException(status_code=400, detail="Invalid password reset token") record = await crud.user.get_by_email(email=email) if not record: raise HTTPException( status_code=404, detail="The user with this email does not exist in the system", ) user = DBUser(**record) if not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") user.password = new_password await crud.user.update(user.id, user) return {"msg": "Password updated successfully"}
async def verify_account(token: str = Form(...)): """ Verify account using token. """ email = await verify_register_token(token) if not email: raise HTTPException(status_code=400, detail="Invalid email verify token") record = await crud.user.get_by_email(email) if not record: raise HTTPException( status_code=404, detail="The user with this email does not exist in the system.") user = DBUser(**record) if user.is_email_verified: raise HTTPException( status_code=HTTP_409_CONFLICT, detail="User already verified", ) await crud.user.update(user.id, {'is_email_verified': True}) send_new_account_email(email=user.email, username=user.username, first_name=user.first_name) return {"msg": "Account verified"}