Esempio n. 1
0
async def authenticate(request, *args, **kwargs):
    """
    After a new client successfully authenticates with strava, call this
    endpoint with a user_id (uuid) and auth_code (from strava).

    we'll exchange the code for access tokens, get the athlete_id, and
    register this user.
    """
    try:
        user_id = request.json.get('user_id', None)
        if not user_id:
            user_id = str(uuid.uuid4())
        code = request.json.get('code', None)
        if not code:
            raise exceptions.AuthenticationFailed("no code")

        logger.info("Looking up code...")
        token = await StravaToken.create_from_code(code)
        logger.info("Registering new user...")
        user = await User.register(user_id=user_id,
                                   athlete_id=token.athlete_id)

        print(f"Successfully registered user: {str(user)}")
        return user
    except Exception as e:
        raise exceptions.AuthenticationFailed(e)
Esempio n. 2
0
    def login(self,
              username: Text,
              password: Text,
              return_api_token: bool = False) -> Dict:
        pw_hash = self.hash_pw(password)
        user = self._fetch_user(username)

        if user is None:
            raise exceptions.AuthenticationFailed(
                "Incorrect user or password.")

        if username == config.SYSTEM_USER:
            raise exceptions.AuthenticationFailed(
                f"Cannot log in user '{username}'.")

        if not self.is_username_password_user(user):
            logger.info("Cannot log in user '{}' with username/password. User "
                        "has auth mechanism '{}'."
                        "".format(user.username,
                                  user.authentication_mechanism))
            raise exceptions.AuthenticationFailed(
                "Incorrect user or password.")

        if user.password_hash != pw_hash:
            raise exceptions.AuthenticationFailed(
                "Incorrect user or password.")

        return user.as_dict(return_api_token=return_api_token)
Esempio n. 3
0
def authenticate(request: sanic.request.Request):
    """
    Returns the user if the authentication was successful, otherwise raises a sanic_jwt.exception

    Passwords are saved hashed by `hash_password` and encoded in base64 in a JSON file.
    """

    # Get username and password from json
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    # Load users from json
    with open(USER_FILE, 'r') as f:
        users = json.load(f)['users']

    username_table = {u['username']: u for u in users}

    if username not in username_table:
        raise exceptions.AuthenticationFailed("User not found.")

    user = username_table[username]

    # Hash the given password and encode to compare with saved password
    if b64encode(hash_password(password)) != user['password'].encode():
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user
async def authenticate(request, *args, **kwargs):
    """Set up JWT auth."""

    user_service = UserService(request[REQUEST_DB_SESSION_KEY])
    rjs = request.json

    # enterprise SSO single-use-token login
    if rjs and rjs.get("single_use_token") is not None:
        user = user_service.single_use_token_login(rjs["single_use_token"],
                                                   return_api_token=True)
        if user:
            return user
        else:
            raise exceptions.AuthenticationFailed(
                "Wrong authentication token.")

    if not rjs:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    # standard auth with username and password in request
    username = rjs.get("username", None)
    password = rjs.get("password", None)

    if username and password:
        return user_service.login(username, password, return_api_token=True)

    raise exceptions.AuthenticationFailed("Missing username or password.")
Esempio n. 5
0
async def retrieve_user(request, payload, *args, **kwargs):
    user_id = None
    if payload:
        user_id = payload.get('user_id', None)
    try:
        if user_id is None or user_id not in refresh_tokens:
            raise exceptions.AuthenticationFailed("Invalid auth token or your refresh token is gone. Login again")
        query = await operator_query()
        user = await db_objects.get(query, id=user_id)
        user_json = user.to_json()
        query = await operatoroperation_query()
        operationmap = await db_objects.execute(query.where(OperatorOperation.operator == user))
        operations = []
        for operation in operationmap:
            op = operation.operation
            operations.append(op.name)
        query = await operation_query()
        admin_operations = await db_objects.execute(query.where(Operation.admin == user))
        admin_ops = []
        for op in admin_operations:
            admin_ops.append(op.name)
        if user_json['current_operation'] != "" and user_json['current_operation'] != 'null':
            links['current_operation'] = user.current_operation.name
        else:
            links['current_operation'] = ""
            user_json['current_operation'] = ""
        user_json['ui_config'] = json.loads(user_json['ui_config'])
        return {**user_json, "user_id": user.id, "operations": operations, "admin_operations": admin_ops}
    except exceptions.AuthenticationFailed as e:
        raise e
    except Exception as e:
        print(e)
        raise exceptions.AuthenticationFailed("Delete your cookies")
Esempio n. 6
0
async def authenticate(request, *args, **kwargs):
    """ - """
    del args, kwargs
    msg = "Error -> Auth -> authenticate"
    with ax_model.scoped_session(msg) as db_session:
        email = request.json.get("email", None)
        password = request.json.get("password", None)

        if not email or not password:
            raise exceptions.AuthenticationFailed("Missing email or password.")

        user = db_session.query(AxUser).filter(
            AxUser.email == email
        ).filter(
            AxUser.is_blocked.is_(False)
        ).first()

        if user is None:
            raise exceptions.AuthenticationFailed("User not found.")

        if not pbkdf2_sha256.verify(password, user.password):
            raise exceptions.AuthenticationFailed("Password is incorrect.")

        await check_if_admin(user_guid=str(user.guid), db_session=db_session)
        await write_perm_cache(db_session=db_session, user_guid=str(user.guid))
        await write_info_cache(user)

        db_session.expunge(user)
        return user
Esempio n. 7
0
    async def authenticate(request):
        email = request.json.get('email', None)
        password = request.json.get('password', None)

        if not email or not password:
            logger.error('Неверный логин или пароль')
            raise exceptions.AuthenticationFailed('Неверный логин или пароль')

        user = User(request.app.client.energy_db.users)
        user = await user.get(email=email)

        if user is None:
            logger.error('Пользователя не существует')
            raise exceptions.AuthenticationFailed(
                'Пользователя не с данной почтой существует')

        if user.get('is_approve') == False:
            logger.error('Аккаунт пользователя не подтвержден')
            raise exceptions.AuthenticationFailed(
                'Аккаунт пользователя не подтвержден')

        if not request.app.bcrypt.check_password_hash(
                user.get('password', None), password):
            logger.error('Неверный логин или пароль')
            raise exceptions.AuthenticationFailed('Неверный логин или пароль')

        return {'user_id': str(user.get('_id')), 'role': user.get('role')}
Esempio n. 8
0
 async def authenticate(self, request, *args, **kwargs):
     username = request.json.get("username", None)
     password = request.json.get("password", None)
     if not username or not password:
         raise exceptions.AuthenticationFailed("Must supply both username and password")
     try:
         query = await operator_query()
         user = await db_objects.get(query, username=username)
         # print("in authenticate, the user: "******"invalid username")
         raise exceptions.AuthenticationFailed("Incorrect username or password")
     if not user.active:
         raise exceptions.AuthenticationFailed("Account is deactivated")
     if await user.check_password(password):
         try:
             user.last_login = datetime.datetime.now()
             await db_objects.update(user)
             # now we have successful authentication, return appropriately
             # print("success authentication")
             return {'user_id': user.id, 'username': user.username, 'auth': 'user'}
         except Exception as e:
             print("failed to update user in authenticate")
             raise exceptions.AuthenticationFailed("Failed to authenticate")
     else:
         print("invalid password")
         raise exceptions.AuthenticationFailed("Incorrect username or password")
Esempio n. 9
0
 async def retrieve_user(self, request, payload, *args, **kwargs):
     user_id = None
     user = None
     if payload:
         user_id = payload.get('user_id', None)
     try:
         if user_id is None or (user_id not in refresh_tokens and 'apitoken' not in request.headers):
             raise exceptions.AuthenticationFailed("Invalid auth token or your refresh token is gone. Login again")
         if user is None:
             query = await operator_query()
             user = await db_objects.get(query, id=user_id)
             if not user.active:
                 # this allows us to reject apitokens of user that have been deactivated
                 print("User is not active, failing authentication")
                 raise exceptions.AuthenticationFailed("User is not active")
         user_json = user.to_json()
         query = await operatoroperation_query()
         operationmap = await db_objects.execute(query.where(OperatorOperation.operator == user))
         operations = []
         if user_json['current_operation'] != "" and user_json['current_operation'] != 'null':
             links['current_operation'] = user.current_operation.name
         else:
             links['current_operation'] = ""
             user_json['current_operation'] = ""
         for operation in operationmap:
             op = operation.operation
             if op.name == user_json['current_operation']:
                 user_json['view_mode'] = operation.view_mode
             operations.append(op.name)
         if 'view_mode' not in user_json:
             user_json['view_mode'] = "operator"
         query = await operation_query()
         admin_operations = await db_objects.execute(query.where(Operation.admin == user))
         admin_ops = []
         for op in admin_operations:
             admin_ops.append(op.name)
         user_json['ui_config'] = json.loads(user_json['ui_config'])
         # note for @inject_user headers if this is an apitoken or normal login request
         if 'apitoken' in request.headers:
             query = await apitokens_query()
             token = await db_objects.get(query, operator=user, token_value=request.headers.get('apitoken'))
             if not token.active:
                 # allows us to not allow inactive tokens
                 raise exceptions.AuthenticationFailed("Token is no longer active")
             user_json['auth'] = 'apitoken'
             user_json['token_type'] = token.token_type
             user_json['apitoken_active'] = token.active
         elif 'Authorization' in request.headers:
             user_json['auth'] = 'access_token'
         else:
             user_json['auth'] = 'cookie'
         return {**user_json, "user_id": user.id, "operations": operations, "admin_operations": admin_ops}
     except exceptions.AuthenticationFailed as e:
         print("got authentication failed in retrieve_user. {}".format(str(e)))
         raise e
     except Exception as e:
         print("Error in retrieve user:"******"Auth Error")
Esempio n. 10
0
 async def post(self, request):
     registered_phone = request.json.get('registered_phone', None)
     if not registered_phone:
         raise exceptions.AuthenticationFailed("注册手机号格式不正确")
     if len(registered_phone) != 11:
         raise exceptions.AuthenticationFailed("注册手机号格式不正确")
     helper = MyCustomUserAuthHelper()
     return await helper.check_registered_phone(
         registered_phone=registered_phone)
Esempio n. 11
0
 def authenticate(self, username, password, user_id):
     if not username or not password:
         raise exceptions.AuthenticationFailed("Missing username or password.")
     user = self.session.query(User).filter_by(name=username, id=user_id).first()
     user_data = user.to_json()
     if user is None:
         raise exceptions.AuthenticationFailed("User not found.")
     if password != user_data['password']:
         raise exceptions.AuthenticationFailed("Password is incorrect.")
     return user_data
Esempio n. 12
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username or not password:
        return exceptions.AuthenticationFailed("Missing username or password")
    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed('User not found')
    if not user.check_password(password.encode("utf-8")):
        raise exceptions.AuthenticationFailed("Password is incorrect")
    return user
Esempio n. 13
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    hash_password = hashlib.sha256(str(password).encode('utf-8')).hexdigest()

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password")
    try:
        user = User.get(username=username, password=hash_password)
    except:
        raise exceptions.AuthenticationFailed("Invalid username or password")
    return {"user_id": user.id}
Esempio n. 14
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = await User().get_user_by_name(username)

    if password != user.get('password'):
        raise exceptions.AuthenticationFailed()

    return user
Esempio n. 15
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password")

    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found")
    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect")
    return user
    async def login(self, request, *args, **kwargs):
        """Logs in the user into this application
        - Receive and parse get request
        - Verify that the user is valid on the service
        - Go into AWS RDS and fetch user details and verify
        - Return success or unauthorized
        - end

        Arguments:
            request {object} -- the query parameters passed into this function

        Returns:
            object -- response from this endpoint
        """

        request_body = request.body
        body_params = {}
        if request_body != b'':
            body_params = json.loads(request_body)

        self.logger.info(
            'Received user login request: {params}'.format(params=body_params))

        username = request.json.get("username", None)
        password = request.json.get("password", None)

        if not username or not password:
            raise exceptions.AuthenticationFailed(
                "Missing username or password.")

        try:
            user = self.service.login(username, password)
        except LookupError as error:
            self.logger.error('Error Occurred: {error}'.format(error=error))
            raise exceptions.AuthenticationFailed(
                "You are not authorized to login.")

        if user is None:
            raise exceptions.AuthenticationFailed(
                "You are not authorized to login.")

        last_login_time = datetime.datetime.now(
        )  #.strftime("%Y-%m-%d %H:%M:%S")
        # pylint: disable=unused-variable,invalid-name
        ip, routable = get_client_ip(request)
        if ip is not None:
            # update the ip_address here for user
            pass

        return user
Esempio n. 17
0
async def jwt_authenticate(request, *args, **kwargs):
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    if not username or not password:
        raise exceptions.AuthenticationFailed('Missing username or password.')

    ok, user = await validate_login(username, password)
    if not ok:
        raise exceptions.AuthenticationFailed('User or Password is incorrect.')

    if not user.active:
        raise exceptions.AuthenticationFailed(
            'The account has been deactivated!')
    return {'user_id': user.id}
Esempio n. 18
0
async def authenticate(request, *args, **kargs):
    email = request.json.get("email", None)
    password = request.json.get("password", None)

    if email is None or password is None:
        raise exceptions.AuthenticationFailed('Missing email or password.')

    with scoped_session() as session:
        user = session.query(User).filter_by(email=email).first()
        if user is None:
            raise exceptions.AuthenticationFailed('User not found.')
        if not bcrypt.checkpw(password.encode('utf-8'),
                              user.password.encode('utf-8')):
            raise exceptions.AuthenticationFailed('Password is incorrect.')
        return user.to_dict()
Esempio n. 19
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = await db.users.find_one({'username': username})
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.get('password'):
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user
Esempio n. 20
0
async def authenticate(request, *args, **kwargs):
    email = request.json.get("email", None)
    password = request.json.get("password", None)

    if not email or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = User.get_by_email(email)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if not user.password_matched(password):
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user
Esempio n. 21
0
async def authenticate(request):
    body = request.json
    username = body.get('username', '')
    password = body.get('password', '')

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = get_user(username)

    if user and pbkdf2_sha256.verify(password, user.password):
        logger.info('user: %s', user.username)
        return user

    raise exceptions.AuthenticationFailed("Wrong user name or password")
Esempio n. 22
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    if not username or not password:
        raise exceptions.AuthenticationFailed('Missing username or password.')

    user = username_table.get(username, None)

    if not user:
        raise exceptions.AuthenticationFailed('User not found.')
    if password != user.password:
        raise exceptions.AuthenticationFailed('Password is incorrect.')

    return user
Esempio n. 23
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user_password = _USERS_AUTH.get(username)
    if user_password is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user_password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return {username: user_password}
Esempio n. 24
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = await User.find_one({
        "username": username,
        "password": hash_password(password)
    })
    if user is None:
        raise exceptions.AuthenticationFailed("Credentials aren't valid")

    return JWTUser(str(user["_id"]), user["username"], user["password"])
Esempio n. 25
0
async def authenticate(request, *args, **kwargs):
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = await get_user_from_mongo(username)

    if user is None or compute_pass_hash(password) != user.password_hash:
        raise exceptions.AuthenticationFailed("Wrong credentials.")

    user.password_hash = ''

    return user
Esempio n. 26
0
    async def get(self, request, *args, **kwargs):
        # go here if we're in the browser and our JWT expires so we can update it and continue on
        payload = self.instance.auth.extract_payload(request, verify=True)
        try:
            user = await utils.call(self.instance.auth.retrieve_user,
                                    request,
                                    payload=payload)
        except exceptions.MeEndpointNotSetup:
            raise exceptions.RefreshTokenNotImplemented

        user_id = await self.instance.auth._get_user_id(user)
        refresh_token = await utils.call(
            self.instance.auth.retrieve_refresh_token,
            request=request,
            user_id=user_id,
        )
        if isinstance(refresh_token, bytes):
            refresh_token = refresh_token.decode("utf-8")
        token = await self.instance.auth.retrieve_refresh_token_from_request(
            request)

        if refresh_token != token:
            raise exceptions.AuthenticationFailed()

        access_token, output = await self.responses.get_access_token_output(
            request, user, self.config, self.instance)
        redirect_to = request.headers[
            'referer'] if 'referer' in request.headers else "/"
        resp = response.redirect(redirect_to)
        resp.cookies[self.config.cookie_access_token_name()] = access_token
        resp.cookies[self.config.cookie_access_token_name()]['httponly'] = True
        return resp
Esempio n. 27
0
async def authenticate(request: Request):
    """Callback for authentication failed."""
    raise exceptions.AuthenticationFailed(
        "Direct JWT authentication not supported. You should already have "
        "a valid JWT from an authentication provider, Rasa will just make "
        "sure that the token is valid, but not issue new tokens."
    )
Esempio n. 28
0
 def api_token_auth(self,
                    api_token: Text,
                    return_api_token: bool = False) -> Dict:
     user = self.query(User).filter(User.api_token == api_token).first()
     if user is None:
         raise exceptions.AuthenticationFailed("Incorrect api_token.")
     return user.as_dict(return_api_token=return_api_token)
Esempio n. 29
0
async def retrieve_user(request, payload, *args, **kwargs):
    user_id = None
    if payload:
        user_id = payload.get('user_id', None)
    try:
        user = await db_objects.get(Operator, id=user_id)
        user_json = user.to_json()
        operationmap = await db_objects.execute(
            OperatorOperation.select().where(
                OperatorOperation.operator == user))
        operations = []
        for operation in operationmap:
            op = await db_objects.get(Operation, id=operation.operation)
            operations.append(op.name)
        admin_operations = await db_objects.execute(
            Operation.select().where(Operation.admin == user))
        admin_ops = []
        for op in admin_operations:
            admin_ops.append(op.name)
        if user_json['current_operation'] != "" and user_json[
                'current_operation'] != 'null':
            links['current_operation'] = user.current_operation.name
        else:
            links['current_operation'] = ""
            user_json['current_operation'] = ""
        return {
            **user_json, "user_id": user.id,
            "operations": operations,
            "admin_operations": admin_ops
        }
    except Exception as e:
        print("failed to get user in retrieve_user")
        print(e)
        raise exceptions.AuthenticationFailed("Delete your cookies")
Esempio n. 30
0
 async def check_registered_phone(self, registered_phone):
     res = await self.user_model.find_by_registered_phone(
         registered_phone=registered_phone)
     if res is not False:
         raise exceptions.AuthenticationFailed("手机号已被注册")
     else:
         return json(response_package("200", "手机号未被注册"))