def generate_password_reset_token(self, email: str) -> str: """ Generate Access Token for password Reset email""" delta = timedelta(hours=EmailSettings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) now = datetime.utcnow() expires = now + delta encoded_jwt = self.__instance.encode( {"exp": get_int_from_datetime(expires), "ist": get_int_from_datetime(now), "sub": email}, self.__signing_key, alg=self.__algorithm, ) return encoded_jwt
def create_access_token(self, *, data: dict, expires_delta: timedelta = None) -> str: to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"ist": get_int_from_datetime(datetime.utcnow())}) to_encode.update({"exp": get_int_from_datetime(expire)}) encoded_jwt = self.__instance.encode(to_encode, self.__signing_key, self.__algorithm) return encoded_jwt
def new_jwt(): """Generate a new JSON Web Token signed by RSA private key.""" with open(GITHUB_PEM_FILE, 'rb') as fp: signing_key = jwt.jwk_from_pem(fp.read()) payload = { 'iat': get_int_from_datetime(datetime.now()), 'exp': get_int_from_datetime( datetime.now(timezone.utc) + timedelta(minutes=10)), 'iss': GITHUB_APP_ID } compact_jws = instance.encode(payload, signing_key, alg='RS256') return compact_jws
def test_no_before_used_after(self): message = { 'nbf': get_int_from_datetime( datetime.now(timezone.utc) - timedelta(hours=1)) } compact_jws = self.inst.encode(message, self.key) self.assertEqual(self.inst.decode(compact_jws, self.key), message)
def test_no_before_used_before(self): compact_jws = self.inst.encode({ 'nbf': get_int_from_datetime(datetime.now(timezone.utc) + timedelta(hours=1)) }, self.key) self.assertRaisesRegex( JWTDecodeError, 'JWT Not valid yet', self.inst.decode, compact_jws, self.key )
def build_jwt(self, subject: str) -> str: utc_now: "datetime" = datetime.now(timezone.utc) return JWT().encode( { 'iss': 'https://rsvp.adriandmikejones.com/', 'sub': subject, 'iat': get_int_from_datetime(utc_now), 'exp': get_int_from_datetime(utc_now + timedelta( **{self._duration_units: self._duration_amount})), }, self._jwt_secret, alg=self._ALG, )
def encode(cls, user: str): return JWT.__instance.encode( { 'user': user, 'iat': get_int_from_datetime(datetime.datetime.now()) }, JWT.signing_key, alg='RS256')
def get_email_data(self): token = jwtToken.encode( dict( iss="https://edurange.org/", email=self.user.email, iat=get_int_from_datetime(datetime.now(timezone.utc)), exp=get_int_from_datetime( datetime.now(timezone.utc) + timedelta(hours=1) ), ), key=oct_data, alg="HS256", ) email_data = { "subject": "Reset Password", "token": token, "email": self.user.email, } return email_data
def generate_objective_token(cls, objective_key: str, authorizer: Authorizer, duration: timedelta = None): if duration is None: duration = timedelta(days=1) jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'jwk.json') with open(jwk_path, 'r') as f: jwk = jwt.jwk_from_dict(json.load(f)) encoder = jwt.JWT() now = datetime.now(timezone.utc) payload = { 'sub': authorizer.sub, "iat": get_int_from_datetime(now), "exp": get_int_from_datetime(now + duration), "objective": objective_key } return encoder.encode(payload, jwk)
def generate_reward_token(cls, authorizer: Authorizer, static: RewardSet = None, area: Optional[str] = None, boxes: List[RewardSet] = None, duration: timedelta = None, reason: Enum = None) -> str: from core.services.beneficiaries import BeneficiariesService if duration is None: duration = timedelta(days=7) jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'jwk.json') with open(jwk_path, 'r') as f: jwk = jwt.jwk_from_dict(json.load(f)) encoder = jwt.JWT() now = datetime.now(timezone.utc) token_index = int(BeneficiariesService.add_token_index(authorizer)) payload = { "sub": authorizer.sub, "iat": get_int_from_datetime(now), "exp": get_int_from_datetime(now + duration), "static": static.to_map_list() if static is not None else [], "boxes": [box.to_map_list() for box in boxes] if boxes is not None else [], "index": token_index, "area": area, "reason": None if reason is None else reason.value } return encoder.encode(payload, jwk)
def get_jwt(subject, name, issuer) -> str: ident = { 'sub': subject, 'name': name, 'iss': issuer, 'iat': get_int_from_datetime(datetime.now(timezone.utc)), } signing_key = get_signing_key() instance = JWT() return instance.encode(ident, signing_key, alg='RS256')
def post(): data = rest.request.get_json(silent=True) if data is None: response = jsonify({'data': {'success': False, 'code': 403, 'message': 'bad module name'}}) response.status_code = 403 return response username = data['username'] password = data['password'] if username != '!admin!' and password != '!admin!': user = PostGre().check_user(username, password) else: user = ['1'] if len(user) == 0: response = jsonify({'data': {'success': False, 'code': 401, 'message': 'Kullanıcı Adı veya Şifre Hatalı'}}) response.status_code = 401 return response else: instance = JWT() user_id = user[0][0] JWT_ALGORITHM = 'RS512' with open('/opt/ante-jamnet/helper/certs/rsa_private_key.pem', 'rb') as fh: signing_key = jwk_from_pem(fh.read()) payload = { 'iss': 'Ante-Jamnet', 'user_name': username, 'iat': get_int_from_datetime(datetime.now(timezone.utc)), 'user_id': user_id, 'exp': get_int_from_datetime( datetime.now(timezone.utc) + timedelta(hours=240)), } jwt_token = instance.encode(payload, signing_key, JWT_ALGORITHM) try: PostGre().set_user_token(user_id, username, jwt_token) except Exception as e: print(e) return {'data': {'success': True, 'token': jwt_token}}
def get_current_admin(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> UserVerify: """ Verify User Authentication""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) expire_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="access expired", headers={"WWW-Authenticate": "Bearer"}, ) require_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="access denied", headers={"WWW-Authenticate": "Bearer"}, ) if token: try: payload = access_token.decode_access_token(token=token) token_validity = payload.get("exp") if get_int_from_datetime(datetime.utcnow()) >= token_validity: raise expire_exception email: str = payload.get("sub") if email is None: raise credentials_exception token_data = TokenData(email=email) except exceptions.JWTException as e: raise credentials_exception user = crud_users.verify_user(email=token_data.email, db=db) if user is None: raise credentials_exception if user.is_admin == False: raise credentials_exception return user else: raise require_exception
def reset_password( reset_data: schemas.UserPasswordReset, db: Session = Depends(deps.get_db) ) -> JSONResponse: """ Reset password """ credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) expire_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="access expired", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = access_token.verify_password_reset_token( token=reset_data.token) token_validity = payload.get("exp") if get_int_from_datetime(datetime.utcnow()) >= token_validity: raise expire_exception token_email: str = payload.get("sub") if token_email is None: raise credentials_exception except exceptions.JWTException as e: print(e) raise credentials_exception db_user = crud.verify_user(db, email=token_email) if db_user is None: raise credentials_exception data = crud.update_user_password(db, email=token_email, password=reset_data.password) if data is None: return JSONResponse(status_code=500, content={"message": "Internal Server Error"}) return JSONResponse(status_code=200, content={"message": "success"})
def test_get_int_from_datetime_with_timezone(): param = datetime(2011, 3, 22, 19, 43, tzinfo=timezone(timedelta(hours=1))) assert get_int_from_datetime(param) == 1300819380
def test_get_int_from_datetime_with_timezone(): param = datetime.strptime('2011-03-22T19:43:00+0100', '%Y-%m-%dT%H:%M:%S%z') assert get_int_from_datetime(param) == 1300819380
def test_get_int_from_datetime_with_utc_timezone(): param = datetime(2011, 3, 22, 18, 43, tzinfo=timezone.utc) assert get_int_from_datetime(param) == 1300819380
def claim_reward(cls, authorizer: Authorizer, reward_token: str, release: int, box_index: int = None) -> \ List[Reward]: from core.services.beneficiaries import BeneficiariesService jwk_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'jwk.json') with open(jwk_path, 'r') as f: jwk = jwt.jwk_from_dict(json.load(f)) decoder = jwt.JWT() try: decoded = decoder.decode(reward_token, jwk) except JWTDecodeError as e: raise InvalidException(f'Invalid token: {e.args}') now = get_int_from_datetime(datetime.now()) if now > decoded["exp"]: raise ForbiddenException("The reward token has expired") if authorizer.sub != decoded["sub"]: raise ForbiddenException( "This token does not belong to the claimer") BeneficiariesService.set_reward_index(authorizer, decoded['index']) boxes = decoded["boxes"] probabilities: List[RewardProbability] = [ RewardProbability.from_map(reward) for reward in decoded["static"] ] if len(boxes) > 0: if box_index is None: raise InvalidException("A box must be chosen") if box_index >= len(boxes): raise InvalidException( f"Box index out of range, it must be between 0 (inclusive) and {len(boxes)} (exclusive)" ) probabilities += [ RewardProbability.from_map(reward) for reward in boxes[box_index] ] rewards = [ RewardsService.get_random(probability.type, release, probability.rarity) for probability in probabilities ] LogsService.batch_create(logs=[ Log(sub=authorizer.sub, tag=join_key(LogTag.REWARD.name, rewards[reward_i].type.name, rewards[reward_i].id), log='Won a reward', data=rewards[reward_i].to_api_map(), append_timestamp=rewards[reward_i].type != RewardType.AVATAR) for reward_i in range(len(rewards)) ]) area: Optional[str] = decoded.get('area') areas: List[str] = VALID_AREAS if area is None else [area] scores = {} for r in rewards: if r.type != RewardType.POINTS: continue total_score = r.description['amount'] for a in areas: scores[a] = scores.get(a, 0) + (total_score / len(areas)) for key in scores: scores[key] = math.ceil(scores[key]) BeneficiariesService.add_score(authorizer.sub, scores) return rewards