def login(credentials: LoginSchema, jwt: JWT) -> str: """ View d'authentification Args: credentials: credentials username/password jwt: JWT componement pour l'encodage du payload Toutes les erreurs "raise" Returns: token """ user = User.get(username=credentials["username"]) if not user or not user.check_password(credentials["password"]): raise exceptions.Forbidden("Incorrect username or password.") if not user.actif: raise exceptions.Forbidden("Utilisateur inactif") payload = { "id": user.id, "username": user.username, "iat": pendulum.now(), "exp": pendulum.now() + pendulum.Duration(seconds=1000), } token = jwt.encode(payload) if token is None: raise exceptions.ConfigurationError("échec de l'encodage jwt") return token
def login(data: UserData, jwt: JWT) -> dict: # do some check with your database here to see if the user is authenticated user = db_login(data) # print(user) if not user: raise exceptions.Forbidden('Incorrect username or password.') payload = { 'id': user.id, 'username': user.email, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'phone': user.phone, 'language': user.language, 'groups': user.groups, 'location': user.location, 'picture': user.picture, # expiration data 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + JWT_EXPIRATION_TIME } # noinspection PyUnresolvedReferences token = jwt.encode(payload) if token is None: # encoding failed, handle error raise exceptions.BadRequest() return {'token': token}
def db_login(data: UserData) -> AuthenticatedUserData: db = DbWrapper() db.cursor.execute( """SELECT id, firstname as first_name, surname as last_name, email, phone, userlanguage as language, password, groupid as groups, locationid as location, picture FROM backoffice.users WHERE not del and ( email = %(email)s OR phone = %(phone)s ) LIMIT 1""", data) result = db.cursor.fetchone() if not result or not bcrypt.checkpw(data.password.encode('utf8'), result['password'].encode('utf8')): raise exceptions.Forbidden("Invalid login credentials.") return AuthenticatedUserData(dict(result))
def only_owner_can_edit(self): """ Permission où seul l'utilisateur ayant créé l'acte peut le modifier. """ if self.user.id != self.acte.owner.id: raise exceptions.Forbidden( "Un utilisateur ne peut modifier un acte créé par un autre utilisateur" )
def resolve(self, authorization: http.Header, route: Route) -> AuthData: """ Describe """ if route.handler.__name__ in self.no_auth_list: log.info(f"No auth handler") return AuthData() scheme, token = self.get_data_by_header(authorization) if "Bearer" in scheme: try: payload = jwt.decode(token, self.secret, self.algorithms) user_id = payload.get("user_id") user = User.find(user_id) if user is None: msg = "Unauthorized, invalid token" raise exceptions.HTTPException({"message": msg}, status_code=401) return AuthData(user, None) except jwt.DecodeError: msg = "Unauthorized, invalid token" raise exceptions.HTTPException({"message": msg}, status_code=401) except jwt.ExpiredSignatureError: msg = "Unauthorized, token expired" raise exceptions.HTTPException({"message": msg}, status_code=401) if "Token" in scheme: if route.handler.__name__ in self.accept_token_list: service = Service.where("token", token).first() if service is None: msg = "Unauthorized, invalid token" raise exceptions.HTTPException({"message": msg}, status_code=401) return AuthData(None, service) msg = f"This endpoint is not available by Token, please use Bearer header" raise exceptions.Forbidden({"message": msg})
async def check_permissions_async(handler: Handler, injector: Injector, settings: Settings): """ An async variant of 'check_permissions'. """ default_permissions = settings.get('PERMISSIONS', None) permissions = getattr(handler, 'permissions', default_permissions) if permissions is None: return for permission in permissions: if not await injector.run_async(permission.has_permission): raise exceptions.Forbidden()
def _check_rules(feature, auth): if feature.enabled: return query = auth.service.features.where("id", feature.id).first() if feature.deny: query = not query if not query: msg = f"Access denied to resource." log.info(f"{msg} - ID: {id}, service: {auth.service.name}") raise exceptions.Forbidden({"message": msg})
def login(data: UserData, jwt: JWT) -> dict: # do some check with your database here to see if the user is authenticated if data.email != USERS_DB['email'] or data.password != USERS_DB['password']: raise exceptions.Forbidden('Incorrect username or password.') payload = { 'id': USERS_DB['id'], 'username': USERS_DB['email'], 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60) # ends in 60 minutes } token = jwt.encode(payload) if token is None: # encoding failed, handle error raise exceptions.BadRequest() return {'token': token}
def check_permissions(handler: Handler, injector: Injector, settings: Settings) -> None: """ Ensure that any configured permissions are met. Used in the default `BEFORE_REQUEST` configuration. """ default_permissions = settings.get('PERMISSIONS', None) permissions = getattr(handler, 'permissions', default_permissions) if permissions is None: return for permission in permissions: if not injector.run(permission.has_permission): raise exceptions.Forbidden()
def resolve(self, authorization: http.Header) -> User: """ Determine the user associated with a request, using HTTP Basic Authentication. """ if authorization is None: return None scheme, token = authorization.split() if scheme.lower() != 'basic': return None username, password = base64.b64decode(token).decode('utf-8').split(':') if not self.check_authentication(username, password): raise exceptions.Forbidden('Incorrect username or password.') return User(username)
def delete(patient_id: int, user: UserC) -> dict: """ delete un patient Args: id: id du patient Returns: msg "delete success" Raises: NotFound si non trouvé """ pat = get_or_404(db.Patient, patient_id) if user.permissions.del_patient: pat.delete() return {"msg": "delete success"} else: raise exceptions.Forbidden( f"Action non autorisée pour l'utilisateur {user.username}")
def _reject(self, reason): raise exceptions.Forbidden(reason)
def on_request(self, route: Route) -> None: if route.handler is auth_required: raise exceptions.Forbidden({"message": "forbidden"})
def _auth(password): if not password or not bcrypt.verify(password, config.PASSWORD): raise exceptions.Forbidden()
def wrapper(*args, **kwargs): for group in kwargs['user'].groups: if group in groups[0]: return func(*args, **kwargs) raise exceptions.Forbidden()