async def test_access_token(): user_id = 1 token = create_access_token(user_id) actual = get_user_id_from_token(token) assert int(actual) == user_id token = create_access_token(user_id, timedelta(minutes=1234)) actual = get_user_id_from_token(token) assert int(actual) == user_id
def get_access_from_refresh(user: models.User = Depends( deps.get_user_from_refresh_token)): new_access_token = security.create_access_token( subject=user.id, expires_delta=timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)) logger.info('Created new access token %s', new_access_token) return {"access_token": new_access_token, "token_type": "bearer"}
def client2( db, provider, user, provider2, user2, collection, collection2, collection_private, collection_empty, obstacles, sensors, item, item2, item_poly, item_empty_geom, item_private, series, metric, request, ): from app.core.security import create_access_token token = create_access_token(user2["uuid"]) with TestClient(app) as client: client.headers["AUTHORIZATION"] = "Bearer " + token client.headers["CONTENT_TYPE"] = "application/json" client.headers["ACCEPT"] = "application/json" return client
async def login(db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()): 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_expires = timedelta( minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES) if user.is_superuser: permissions = "admin" else: permissions = "user" access_token = security.create_access_token( data={ "sub": user.email, "permissions": permissions }, expires_delta=access_token_expires, ) return {"access_token": access_token, "token_type": "bearer"}
async def get_token_by_scan( db: Session = Depends(database.get_db), scan: str = None): if not scan: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Could not Found scan", ) for i in range(60): wx_openid = Cache.get(key=scan) if wx_openid: db_user = crud.user.get_by_wx_openid(db, wx_openid) if db_user: return { "access_token": security.create_access_token(db_user.id), "token_type": "bearer" } else: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Could not Found scan", ) else: print("sleep" + str(i)) await asyncio.sleep(1) raise HTTPException( status_code=status.HTTP_408_REQUEST_TIMEOUT, detail="request timeout", )
async def user(user: CreateUser): hash_password = get_password_hash(user.password) await Users.objects.create(email=user.email, phone=user.phone, password=hash_password, username=user.username) task = celery_app.send_task("app.api.api_v1.tasks.emails.decoratorEmail", args=[user.email, "".join([str(random.randint(1, 9)) for i in range(6)])]) print(task, "---------") return create_access_token(data={"username": user.username, "email": user.email})
async def signup(db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends(), first_name: str = Form(...), last_name: str = Form(...)): user = sign_up_new_user(db, form_data.username, first_name, last_name, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="Account already exists", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta( minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES) if user.is_superuser: permissions = "admin" else: permissions = "user" access_token = security.create_access_token( data={ "sub": user.email, "permissions": permissions }, expires_delta=access_token_expires, ) return {"access_token": access_token, "token_type": "bearer"}
async def update_current_user( user_update: schemas.UserUpdate = Body(..., embed=True, alias="user"), current_user: schemas.UserDB = Depends(deps.get_current_user()), ) -> schemas.UserResponse: if user_update.username and user_update.username != current_user.username: user_db = await crud_user.get_user_by_username( username=user_update.username) if user_db: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="user with this username already exists", ) if user_update.email and user_update.email != current_user.email: user_db = await crud_user.get_user_by_email(email=user_update.email) if user_db: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail="user with this email already exists", ) user_id = await crud_user.update(user_id=current_user.id, payload=user_update) user_db = await crud_user.get(user_id) token = security.create_access_token(current_user.id) return schemas.UserResponse(user=schemas.UserWithToken( username=user_db.username, # type: ignore email=user_db.email, # type: ignore bio=user_db.bio, # type: ignore image=user_db.image, # type: ignore token=token, ))
async def login(user_info: user_schema.UserInfo): increase_dict = { 'username': user_info.username, 'password': user_info.password } password = hashlib.md5(increase_dict['password'].encode()) return_dict = {'code': 200, 'message': 'ok', 'data': None} access_token_expires = timedelta( minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) if curd_category.login(increase_dict) == False: return {"code": 500, "message": "操作失败", "data": None} else: df, sql_username_list = curd_category.login(increase_dict) list = [] for i in sql_username_list['username'].values.tolist(): list.append(i) if increase_dict['username'] in list: if password.hexdigest() == df[0][2]: return_dict['data'] = {'user_id': df[0][0]} return_dict['token'] = create_access_token( increase_dict['username'], expires_delta=access_token_expires) return JSONResponse(return_dict) else: return {"code": 403, "message": "密码错误", "data": None} else: return {"code": 403, "message": "用户名错误", "data": None}
async def update_current_user( user_update: schemas.UserUpdate = Body(..., embed=True, alias="user"), current_user: models.User = Depends(deps.get_current_user), db: Session = Depends(deps.get_db), ) -> schemas.UserResponse: if user_update.username and user_update.username != current_user.username: user = crud.user.get_user_by_username(db, username=user_update.username) if user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="user with this username already exists", ) if user_update.email and user_update.email != current_user.email: user = crud.user.get_user_by_email(db, email=user_update.email) if user: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail="user with this email already exists", ) user = crud.user.update(db, db_obj=current_user, obj_in=user_update) token = security.create_access_token(user.id) return schemas.UserResponse(user=schemas.UserWithToken( username=user.username, email=user.email, bio=user.bio, image=user.image, token=token, ))
async def login_access_token( *, db: Session = Depends(deps.get_db), user_info: user_schema.UserEmailAuth, ) -> Any: """ 用户登录 :param db: :param user_info: :return: """ # 验证用户 user = curd_user.authenticate(db, email=user_info.username, password=user_info.password) if not user: logger.info( f"用户邮箱认证错误: email{user_info.username} password:{user_info.password}" ) return response_code.resp_500(message="用户名或者密码错误") elif not curd_user.is_active(user): return response_code.resp_500(message="用户邮箱未激活") access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) # 登录token 只存放了user.id return response_code.resp_200( data={ "token": security.create_access_token(user.id, expires_delta=access_token_expires), })
async def access_token(form_data: OAuth2PasswordRequestForm = Depends() ) -> Any: """ OAuth2 compatible token login, get an access token for future requests """ user = await crud.user.authenticate(username=form_data.username, password=form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") elif not crud.user.is_active(user): raise HTTPException(status_code=400, detail="Inactive user") access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) scopes = crud.user.get_scopes(user) access_token = security.create_access_token( data={ "sub": user.username, "scopes": scopes }, expires_delta=access_token_expires, ) return { "access_token": access_token, "token_type": "bearer", }
def login_access_token(login: Login): ''' :param login: :return: ''' appid = login.appId secret_key = login.secretKey try: db: Session = SessionLocal() invoker: Invoker = db.query(Invoker).filter(Invoker.app_id == appid).filter(Invoker.secret_key == secret_key)\ .filter(Invoker.active==1).first() if invoker: # token = create_access_token({'appid': appid, 'nick_name': invoker.nick_name}) token = create_access_token(appid) msg = { 'success': True, 'data': { 'access_token': token }, 'message': '成功' } return msg except Exception as e: logger.exception(e) msg = {'success': False, 'data': {}, 'message': '非法请求'} return msg
def login_access_token( db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends(), ) -> Any: """ OAuth2 compatible token login, get an access token for future requests """ user = crud.user.authenticate(db, email=form_data.username, password=form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") elif not crud.user.is_active(user): raise HTTPException(status_code=400, detail="Inactive user") access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) if not user.user_role: role = "GUEST" else: role = user.user_role.role.name token_payload = { "id": str(user.id), "role": role, "account_id": str(user.account_id), } return { "access_token": security.create_access_token(token_payload, expires_delta=access_token_expires), "token_type": "bearer", }
def login_access_token( db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends() ) -> Any: """ OAuth2 compatible token login, get an access token for future requests """ user = crud.user.authenticate( db, email=form_data.username, password=form_data.password ) if not user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect email or password" ) elif not crud.user.is_active(user): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user" ) access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) return { "access_token": security.create_access_token( user.id, expires_delta=access_token_expires ), "token_type": "bearer", }
async def login_access_token( *, uow: IUnitOfWork = Depends(common.get_uow), form_data: OAuth2PasswordRequestForm = Depends(), ) -> tp.Dict[str, str]: """OAuth2 compatible login to get access token for future requests. """ user = uow.user.authenticate(form_data.username, form_data.password) if not user: raise HTTPException( status_code=400, detail="Incorrect email or password", ) elif not user.is_active: raise HTTPException( status_code=400, detail="Inactive user", ) expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) return { "access_token": security.create_access_token( user.uid, expires_delta=expires, ), "token_type": "bearer", }
async def user_auth(*, db: Session = Depends(get_db), username: str = Body(...), password: str = Body(...)): """ 简单模拟登录 :param db; :param username: :param password: :return: """ sql_query_user = f"SELECT user_id, hashed_password from chat_user WHERE username='******'" query_user = db.execute(sql_query_user) user_res = query_user.fetchone() if not user_res: return response_code.resp_5000(message="用户名或者密码错误") verify_res = verify_password(password, user_res.hashed_password) if not verify_res: return response_code.resp_5000(message="用户名或者密码错误") access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) return response_code.resp_200( data={ "token": create_access_token(user_res.user_id, expires_delta=access_token_expires), })
def login( *, db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends(OAuth2PasswordRequestForm) ) -> dict: """ 用户JWT登录 :param db: :param user_info: :return: """ user = crud_user.CRUDUser.authenticate( db=db, user_name=form_data.username, password=form_data.password ) if not user: return { "return_code": -1, "return_msg": "认证失败" } access_token_expires = timedelta(minutes=setting.ACCESS_TOKEN_EXPIRE_MINUTES) return { "return_code": 0, "return_msg": "OK", "uid": user.uid, "access_token": security.create_access_token( user.uid, expires_delta=access_token_expires ), "token_type": "bearer", }
async def login(user_login: user.UserLogin, redis_cli: Redis = Depends(get_redis_cli)): user_info = await curd_user.authenticate(account=user_login.phone, password=user_login.password) token_data = {"uid": user_info.id, "uuid": user_info.user_id} access_token = security.create_access_token( token_data, ) await redis_cli.set(f"user:token:{user_info.user_id}", access_token) return Token(token=access_token)
def test_create_access_token(): fake_user_id = uuid4() token = create_access_token(subject=fake_user_id) claims = jwt.decode(token, key=settings.SECRET_KEY, algorithms=ALGORITHM) assert claims assert 'sub' in claims assert claims['sub'] == str(fake_user_id)
def get_superuser_token_headers() -> Dict[str, str]: access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) user_id = -1 a_token = security.create_access_token(user_id, expires_delta=access_token_expires) headers = {"Authorization": f"Bearer {a_token}"} return headers
async def user(email: str = Body(..., min_length=6), password: str = Body(..., min_length=6)): try: user = await Users.objects.get(email=email) except Exception as e: return HTTPException(status.HTTP_204_NO_CONTENT, detail="用户不存在") if not verify_password(password, user.password): return HTTPException(status.HTTP_401_UNAUTHORIZED, detail="密码错误请重试") token = create_access_token(data={"username": user.username, "email": user.email, "scopes": [user.permission]}) return {"username": user.username, "email": user.email, "id": user.id, "token": token}
def refresh_access_token(current_user: User = Depends(deps.get_current_user)): refresh_token = security.create_access_token( current_user.id, expires_delta=timedelta(minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES), ) return { "access_token": refresh_token, "token_type": "bearer", }
def generate_password(email: str): """Generate a temporary password and send it by email""" password = security.create_access_token( email, timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)) if password: send_generate_password_email(email_to=email, password=password) return {"msg": "Check your Email"}
def create_user( user: UserCreate, db: Session = Depends(deps.get_db) ) -> Any: db_user = crud.get_user(db, user.name) if db_user: raise HTTPException(status_code=400, detail="Name already registered") created_user = crud.create_user(db, user) access_token = create_access_token(created_user.name) return {"access_token": access_token, "token_type": "bearer"}
def create_session(email: str, password: str) -> str: user: User = User.first_or_fail(email=email) try: if verify_password(password, user.password): token = create_access_token(user.uuid, timedelta(days=14)) return str(token) else: raise UnauthorizedError except Exception: raise UnauthorizedError
async def retrieve_current_user( current_user: schemas.UserDB = Depends(deps.get_current_user()), ) -> schemas.UserResponse: token = security.create_access_token(current_user.id) return schemas.UserResponse(user=schemas.UserWithToken( username=current_user.username, email=current_user.email, bio=current_user.bio, image=current_user.image, token=token, ))
def create_invite_to_room( dataroom_id: UUID, org_id: UUID, req: schemas.InviteAPIRequest, current_user: models.User = Depends(deps.get_current_active_user), db: Session = Depends(deps.get_db), auth: Oso = Depends(deps.get_oso), ): # check whether the path is correct so that dataroom belongs to org # and dataroom actually exists room = crud.dataroom.get(db, id=dataroom_id) if not room: raise HTTPException(status_code=400) if not room.organization_fk == org_id: raise HTTPException(status_code=400) # check whether the user is allowed to create invites if not auth.is_allowed(current_user, "INVITE_GUESTS", room): raise HTTPException(status_code=404, detail="Not enough privileges") # check whether the invitee already exists in db, if not create him/her create_user = schemas.UserCreate(email=req.email, password=security.random_password()) invitee = crud.user.create_if_not_exists(db, obj_in=create_user) # add user to the specific role crud.room_roles.add_user_role(db, invitee, room, req.user_role) # generate access url access_token_expires = timedelta(days=req.expires_in) token = security.create_access_token(invitee.id, expires_delta=access_token_expires) # generate invitation entry in db create_invite = schemas.InviteCreate( invitee=invitee, jwt_token=token, dataroom=room, creator=current_user, expires_in=security.calculate_expires_in_days(req.expires_in), ) crud.invite.create(db, obj_in=create_invite) # generate access link access_link = f"{settings.DOMAIN_NAME}/access?token={token}" # generate email and send invite to the user send_access_email( email_to=req.email, access_link=access_link, invitor_name=f"{current_user.first_name} {current_user.last_name}", ) return "OK"
def test_read_account_without_id(test_client: TestClient, db: Session) -> None: client = create_random_client(db) access_token_expires = timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) a_token = security.create_access_token(client.id, expires_delta=access_token_expires) token = {"Authorization": f"Bearer {a_token}"} response = test_client.get( f"{settings.API_V1_STR}/accounts/100000", headers=token, ) assert response.status_code == 404
def face_authorize_access_token( file: UploadFile = File(...), db: Session = Depends(deps.get_db) ) -> Any: user = user_crud.authenticate_face_detection(db, file.file) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found", ) access_token = create_access_token(user.name) return {"access_token": access_token, "token_type": "bearer"}