Пример #1
0
    def _internal_db_authenticate(self, user: typing.Optional[User],
                                  email: str, password: str) -> User:
        """
        Authenticate with internal db, return authenticated user
        or raise Exception like WrongAuthTypeForUser, UserDoesNotExist,
        WrongUserPassword or UserAuthenticatedIsNotActive
        :param user: user to check, can be none if user not found, will raise
        UserDoesNotExist exception if none
        :param password: cleartext password of the user
        :param ldap_connector: ldap connector, enable ldap auth if provided
        """
        auth_type = AuthType.INTERNAL

        if not user:
            raise UserDoesNotExist(
                'User {} not found in database'.format(email))  # nopep8

        if user.auth_type not in [auth_type, AuthType.UNKNOWN]:
            raise WrongAuthTypeForUser(
                'User "{}" auth_type is {} not {}'.format(
                    email, user.auth_type.value, auth_type.value))
        if not user.validate_password(password):
            raise WrongUserPassword(
                'User "{}" password is incorrect'.format(email))  # nopep8

        if user.is_deleted:
            raise UserDoesNotExist('This user has been deleted')  # nopep8

        if not user.is_active:
            raise UserAuthenticatedIsNotActive(
                'This user is not activated')  # nopep8

        if user.auth_type == AuthType.UNKNOWN:
            user.auth_type = auth_type
        return user
Пример #2
0
 def get_one_by_email(self, email: typing.Optional[str]) -> User:
     """
     Get one user by email
     :param email: Email of the user
     :return: one user
     """
     if not email:
         raise UserDoesNotExist("User not found : no email provided")
     try:
         user = self._base_query().filter(User.email == email.lower()).one()
     except NoResultFound as exc:
         raise UserDoesNotExist(
             'User "{}" not found in database'.format(email)) from exc
     return user
Пример #3
0
    def find(self,
             user_id: int = None,
             email: str = None,
             public_name: str = None) -> typing.Tuple[TypeUser, User]:
        """
        Find existing user from all theses params.
        Check is made in this order: user_id, email, public_name
        If no user found raise UserDoesNotExist exception
        """
        user = None

        if user_id:
            try:
                user = self.get_one(user_id)
                return TypeUser.USER_ID, user
            except UserDoesNotExist:
                pass
        if email:
            try:
                user = self.get_one_by_email(email)
                return TypeUser.EMAIL, user
            except UserDoesNotExist:
                pass
        if public_name:
            try:
                user = self.get_one_by_public_name(public_name)
                return TypeUser.PUBLIC_NAME, user
            except UserDoesNotExist:
                pass

        raise UserDoesNotExist('User not found with any of given params.')
Пример #4
0
 def get_current_user(self) -> User:
     """
     Get current_user
     """
     if not self._user:
         raise UserDoesNotExist('There is no current user')
     return self._user
Пример #5
0
 def get_one_by_token(self, token: str) -> User:
     try:
         user = self._base_query().filter(User.auth_token == token).one()
     except NoResultFound as exc:
         raise UserDoesNotExist(
             "User with given token not found in database") from exc
     return user
Пример #6
0
 def _get_candidate_user(
         self,
         request: 'TracimRequest',
 ) -> User:
     """
     Get candidate user
     :param request: pyramid request
     :return: user found from header/body
     """
     app_config = request.registry.settings['CFG']
     uapi = UserApi(None, show_deleted=True, session=request.dbsession, config=app_config)
     login = ''
     try:
         login = None
         if 'user_id' in request.matchdict:
             user_id_str = request.matchdict['user_id']
             if not isinstance(user_id_str, str) or not user_id_str.isdecimal():
                 raise InvalidUserId('user_id is not a correct integer')  # nopep8
             login = int(request.matchdict['user_id'])
         if not login:
             raise UserNotFoundInTracimRequest('You request a candidate user but the context not permit to found one')  # nopep8
         user = uapi.get_one(login)
     except UserNotFoundInTracimRequest as exc:
         raise UserDoesNotExist('User {} not found'.format(login)) from exc
     return user
Пример #7
0
 def get_one(self, user_id: int) -> User:
     """
     Get one user by user id
     """
     try:
         user = self._base_query().filter(User.user_id == user_id).one()
     except NoResultFound as exc:
         raise UserDoesNotExist('User "{}" not found in database'.format(
             user_id)) from exc  # nopep8
     return user
Пример #8
0
 def get_one_by_public_name(self, public_name: str) -> User:
     """
     Get one user by public_name
     """
     try:
         user = self._base_query().filter(
             User.display_name == public_name).one()
     except NoResultFound as exc:
         raise UserDoesNotExist('User "{}" not found in database'.format(
             public_name)) from exc  # nopep8
     return user
Пример #9
0
 def get_one_by_email(self, email: str) -> User:
     """
     Get one user by email
     :param email: Email of the user
     :return: one user
     """
     try:
         user = self._base_query().filter(User.email == email).one()
     except NoResultFound as exc:
         raise UserDoesNotExist('User "{}" not found in database'.format(
             email)) from exc  # nopep8
     return user
Пример #10
0
 def get_one_by_username(self, username: str) -> User:
     """
     Get one user by username
     :param username: username of the user
     :return: one user
     """
     try:
         user = self._base_query().filter(User.username == username).one()
     except NoResultFound as exc:
         raise UserDoesNotExist(
             'User for username "{}" not found in database'.format(
                 username)) from exc
     return user
Пример #11
0
    def _remote_user_authenticate(self, user: typing.Optional[User],
                                  login: str) -> User:
        """
        Authenticate with remote_auth, return authenticated user
        or raise Exception like WrongAuthTypeForUser,
        UserDoesNotExist or UserAuthenticatedIsNotActive
        :param user: user to check, can be none if user not found, will try
         to create new user if none
        :param login: email of the user
        """
        auth_type = AuthType.REMOTE

        # INFO - G.M - 2018-12-12 - Do not authenticate user with auth_type
        # different from REMOTE
        if user and user.auth_type not in [auth_type, AuthType.UNKNOWN]:
            raise WrongAuthTypeForUser(
                'User "{}" auth_type is {} not {}'.format(
                    login, user.auth_type.value, auth_type.value))

        # INFO - G.M - 2018-12-12 - Create new user
        if not user:
            profile = None
            use_email = False
            if "@" in login:
                use_email = True
            user = self.create_user(
                email=login if use_email else None,
                username=login if not use_email else None,
                profile=profile,
                auth_type=AuthType.REMOTE,
                do_save=True,
                do_notify=False,
            )
            self.execute_created_user_actions(user)
            transaction.commit()
            # INFO - G.M - 2018-12-02 - get new created user
            user = self.get_one_by_login(login)

        if user.is_deleted:
            raise UserDoesNotExist("This user has been deleted")

        if not user.is_active:
            raise UserAuthenticatedIsNotActive("This user is not activated")

        if user.auth_type == AuthType.UNKNOWN:
            user.auth_type = auth_type
        return user
Пример #12
0
    def _remote_user_authenticate(
        self,
        user: User,
        email: str,
    ) -> User:
        """
        Authenticate with remote_auth, return authenticated user
        or raise Exception like WrongAuthTypeForUser,
        UserDoesNotExist or UserAuthenticatedIsNotActive
        :param user: user to check, can be none if user not found, will try
         to create new user if none
        :param email: email of the user
        """
        auth_type = AuthType.REMOTE

        # INFO - G.M - 2018-12-12 - Do not authenticate user with auth_type
        # different from REMOTE
        if user and user.auth_type not in [auth_type, AuthType.UNKNOWN]:
            raise WrongAuthTypeForUser(
                'User "{}" auth_type is {} not {}'.format(
                    email, user.auth_type.value, auth_type.value))

        # INFO - G.M - 2018-12-12 - Create new user
        if not user:
            groups = None
            self.create_user(email=email,
                             groups=groups,
                             auth_type=AuthType.REMOTE,
                             do_save=True,
                             do_notify=False)
            transaction.commit()
            # INFO - G.M - 2018-12-02 - get new created user
            user = self.get_one_by_email(email)

        if user.is_deleted:
            raise UserDoesNotExist('This user has been deleted')  # nopep8

        if not user.is_active:
            raise UserAuthenticatedIsNotActive(
                'This user is not activated')  # nopep8

        if user.auth_type == AuthType.UNKNOWN:
            user.auth_type = auth_type
        return user
Пример #13
0
    def _ldap_authenticate(self, user: typing.Optional[User], email: str,
                           password: str, ldap_connector: 'Connector') -> User:
        """
        Authenticate with ldap, return authenticated user or raise Exception
        like WrongAuthTypeForUser, WrongLDAPCredentials, UserDoesNotExist
        or UserAuthenticatedIsNotActive
        :param user: user to check,, can be none if user not found, will try
         to create new user if none but ldap auth succeed
        :param email: email of the user
        :param password: cleartext password of the user
        :param ldap_connector: ldap connector, enable ldap auth if provided
        """
        auth_type = AuthType.LDAP

        # INFO - G.M - 2018-11-22 - Do not authenticate user with auth_type
        # different from LDAP
        if user and user.auth_type not in [auth_type, AuthType.UNKNOWN]:
            raise WrongAuthTypeForUser(
                'User "{}" auth_type is {} not {}'.format(
                    email, user.auth_type.value, auth_type.value))

        # INFO - G.M - 2018-11-22 - LDAP Auth
        data = ldap_connector.authenticate(email, password)
        if not data:
            raise WrongLDAPCredentials('LDAP credentials are not correct')
        ldap_data = data[1]

        # INFO - G.M - 2018-11-22 - Create new user
        if not user:
            groups = None
            # TODO - G.M - 2018-12-05 - [ldap_profile]
            # support for profile attribute disabled
            # Should be reenabled later probably with a better code
            # if self._config.LDAP_PROFILE_ATTR:
            #     ldap_profile = ldap_data[self._config.LDAP_PROFILE_ATTR][0]
            #     try:
            #         gapi = GroupApi(
            #             current_user=self._user,  # User
            #             session=self._session,
            #             config=self._config,
            #         )
            #         groups = [gapi.get_one_with_name(ldap_profile)] # nopep8
            #     except GroupDoesNotExist:
            #         logger.warning(self,
            #             'Profile {} does not exist, create ldap user'
            #             'with default profile.'.format(
            #                 ldap_profile
            #             )
            #         )
            name = None
            if self._config.LDAP_NAME_ATTR:
                name = ldap_data[self._config.LDAP_NAME_ATTR][0]
            # INFO - G.M - 2018-11-08 - Create new user from ldap credentials
            self.create_user(email=email,
                             name=name,
                             groups=groups,
                             auth_type=AuthType.LDAP,
                             do_save=True,
                             do_notify=False)
            transaction.commit()
            # INFO - G.M - 2018-11-08 - get new created user
            user = self.get_one_by_email(email)

        if user.is_deleted:
            raise UserDoesNotExist('This user has been deleted')  # nopep8

        if not user.is_active:
            raise UserAuthenticatedIsNotActive(
                'This user is not activated')  # nopep8

        if user.auth_type == AuthType.UNKNOWN:
            user.auth_type = auth_type
        return user
Пример #14
0
    def _ldap_authenticate(
        self,
        user: typing.Optional[User],
        login: str,
        password: str,
        ldap_connector: "Connector",
    ) -> User:
        """
        Authenticate with ldap, return authenticated user or raise Exception
        like WrongAuthTypeForUser, WrongLDAPCredentials, UserDoesNotExist
        or UserAuthenticatedIsNotActive
        :param user: user to check,, can be none if user not found, will try
         to create new user if none but ldap auth succeed
        :param login: login of the user
        :param password: cleartext password of the user
        :param ldap_connector: ldap connector, enable ldap auth if provided
        """
        auth_type = AuthType.LDAP

        # INFO - G.M - 2018-11-22 - Do no_t authenticate user with auth_type
        # different from LDAP
        if user and user.auth_type not in [auth_type, AuthType.UNKNOWN]:
            raise WrongAuthTypeForUser(
                'User "{}" auth_type is {} not {}'.format(
                    login, user.auth_type.value, auth_type.value))

        # INFO - G.M - 2018-11-22 - LDAP Auth
        data = ldap_connector.authenticate(login, password)
        if not data:
            raise WrongLDAPCredentials("LDAP credentials are not correct")
        ldap_data = data[1]

        # INFO - G.M - 2018-11-22 - Create new user
        if not user:
            profile = None
            # TODO - G.M - 2018-12-05 - [ldap_profile]
            # support for profile attribute disabled
            # Should be reenabled later probably with a better code
            # if self._config.LDAP_PROFILE_ATTR:
            #     ldap_profile = ldap_data[self._config.LDAP_PROFILE_ATTR][0]
            #     try:
            #         profile = Profile.get_one_by_slug(ldap_profile)
            #     except ProfileDoesNotExist:
            #         logger.warning(self,
            #             'Profile {} does not exist, create ldap user'
            #             'with default profile.'.format(
            #                 ldap_profile
            #             )
            #         )
            name = None
            if self._config.LDAP_NAME_ATTRIBUTE:
                name = ldap_data[self._config.LDAP_NAME_ATTRIBUTE][0]
            # INFO - G.M - 2018-11-08 - Create new user from ldap credentials
            use_email = False
            if "@" in login:
                use_email = True
            user = self.create_user(
                email=login if use_email else None,
                username=login if not use_email else None,
                name=name,
                profile=profile,
                auth_type=AuthType.LDAP,
                do_save=True,
                do_notify=False,
            )
            self.execute_created_user_actions(user)
            transaction.commit()
            # INFO - G.M - 2018-11-08 - get new created user
            user = self.get_one_by_login(login)

        if user.is_deleted:
            raise UserDoesNotExist("This user has been deleted")

        if not user.is_active:
            raise UserAuthenticatedIsNotActive("This user is not activated")

        if user.auth_type == AuthType.UNKNOWN:
            user.auth_type = auth_type
        return user