Esempio n. 1
0
 def mutate(self, info, username, password):
     user = User.query.filter_by(username=username).first()
     print(user)
     if not user:
         raise Exception('Authenication Failure : User is not registered')
     return AuthMutation(access_token=create_access_token(username),
                         refresh_token=create_refresh_token(username))
Esempio n. 2
0
 def mutate(cls, _, info, username, password):
     return AuthMutation(
         access_token=create_access_token(username,
                                          user_claims=user_claims),
         refresh_token=create_refresh_token(username,
                                            user_claims=user_claims),
     )
Esempio n. 3
0
 def mutate(cls, _, info, username, password):
     query = f'EXEC sp_validate_user \'{username}\', \'{password}\''
     query_result = sql_server_execute_query(query)
     userId = query_result[0]
     result = AuthMutation(
         access_token=create_access_token(userId),
         refresh_token=create_refresh_token(userId),
     ) if userId['userId'] else AuthMutation(access_token=None, refresh_token=None)
     return result
Esempio n. 4
0
 def mutate(cls, _, info, username, password):
     if username in allowed.USERS.keys(
     ) and password == allowed.USERS[username]:
         return AuthMutation(
             access_token=create_access_token(username),
             refresh_token=create_refresh_token(username),
         )
     else:
         return {}
Esempio n. 5
0
    def mutate(self, info, email_or_username, password, with_google):
        #if email_or_username is None or password is None or email_or_username == '' or password == '':
        #    return Authentication(response= ResponseMessage(text= 'Kolom tidak boleh ada yang kosong!', status= False))

        #LOGIN WITH GOOGLE
        if with_google:
            google_auth = Authentication.login_with_google(with_google)

            if google_auth is False:
                return Authentication(response=ResponseMessage(
                    text=
                    'Terjadi kesalahan terhadap akun Google anda, silahkan coba kembali',
                    status=False))
            else:
                email_or_username = with_google.email
                password = with_google.password

        authenticated_user = mongo.db.users.find_one({
            '$or': [{
                'email': email_or_username
            }, {
                'username': email_or_username
            }],
            'is_admin':
            False
        })

        if authenticated_user is None:
            return Authentication(response=ResponseMessage(
                text='Alamat surel/nama pengguna atau kata sandi anda salah!',
                status=False))
        else:
            try:
                if not with_google and check_password_hash(
                        authenticated_user['password'], password) is False:
                    return Authentication(response=ResponseMessage(
                        text=
                        'Alamat surel/nama pengguna atau kata sandi anda salah!',
                        status=False))
            except:
                return Authentication(response=ResponseMessage(
                    text=
                    'Alamat surel/nama pengguna atau kata sandi anda salah!',
                    status=False))

        if 'img_url' not in authenticated_user:
            authenticated_user['img_url'] = 'https://via.placeholder.com/100'

        if 'date_of_birth' in authenticated_user:
            authenticated_user['date_of_birth'] = authenticated_user[
                'date_of_birth'].date()

        return Authentication(
            authenticated_user=authenticated_user,
            access_token=create_access_token(str(authenticated_user['_id'])),
            refresh_token=create_refresh_token(str(authenticated_user['_id'])),
            response=ResponseMessage(text='Berhasil masuk', status=True))
 def mutate(cls, _, info, username, password):
     if not (AdminModel.objects(username=username) and check_password_hash(
             AdminModel.objects.get(username=username).password, password)):
         return Auth(ok=False)
     else:
         return Auth(
             access_token=create_access_token(username,
                                              user_claims=admin_claim),
             refresh_token=create_refresh_token(username,
                                                user_claims=admin_claim),
             ok=True)
Esempio n. 7
0
    def mutate(self, info, **kwargs):
        user = User.objects(**kwargs).first()

        if user is not None:
            access_token = create_access_token(identity=kwargs["email"])
            refresh_token = create_refresh_token(identity=str(uuid4()))

            return AuthMutation(result=AuthField(access_token=access_token,
                                                 refresh_token=refresh_token,
                                                 message="Login Success"))
        else:
            return AuthMutation(result=AuthField(message="Login failed"))
Esempio n. 8
0
    def mutate(cls, _, info, email, password):

        user = User.query.filter(User.email == email).first()
        if not user:
            raise GraphQLError("Incorrect email or password.")
        if not user.check_password(password):
            raise GraphQLError("Incorrect email or password.")

        return AuthMutation(
            access_token=create_access_token({"id": user.id}),
            refresh_token=create_refresh_token({"id": user.id}),
        )
 def mutate(cls, info, username, password):
     """
     This class is to create the mutation in the side of the graphql
     :param info:
     :param username: Graphene.String type
     :param password: Graphene.String type
     :return: JWT token type
     """
     return AuthMutation(
         access_token=create_access_token(username, password),
         refresh_token=create_refresh_token(username),
     )
Esempio n. 10
0
def test_mutation_refresh_jwt_token_required(flask_app: Flask):
    test_cli = flask_app.test_client()

    with flask_app.test_request_context():
        refresh_token = create_refresh_token('username')

    response = request(test_cli, "mutation",
                       'refresh(refreshToken:"{0}")'.format(refresh_token),
                       """newToken""")

    with flask_app.test_request_context():
        assert get_jwt_data(response['refresh']["newToken"],
                            "access")["identity"] == "username"
Esempio n. 11
0
    def mutate(cls, _, info: ResolveInfo, email: str,
               password: str) -> "AuthMutation":
        """
        Mutate is a class method that creates an access and refresh tokens for the given user.

        :param _ :type...
        :param info :type ResolveType
        :param email :type str: User object's email
        :param password :type str: User object's password
        :return :type AuthMutation (self)
        """
        return AuthMutation(
            access_token=create_access_token(email),
            refresh_token=create_refresh_token(email),
        )
Esempio n. 12
0
    def mutate(self, info, **kwargs):
        user = AccountModel.objects(**kwargs).first()

        if user is not None:
            access_token = create_access_token(identity=kwargs["id"])
            refresh_token = create_refresh_token(identity=str(uuid4()))

            return AuthMutation(
                AuthField(
                    access_token=access_token,
                    refresh_token=refresh_token,
                    message="Login Success",
                )
            )
        else:
            return AuthMutation(
                ResponseMessageField(is_success=False, message="Login failed")
            )
Esempio n. 13
0
    def mutate(self, info, Input):
        username, password = Input['username'], Input['password']

        # Username and password authentication
        _user = UserTable(username)
        valid_password = _user.valid_password(password)

        # Verifying that authentication was successful and that the user is
        # enabled
        if not (_user.exists and valid_password):
            err = ('''Authentication Failure: incorrect credentials or user not
                   enabled!''')
            raise GraphQLError(err)

        # Creating tokens
        access_token = create_access_token(username)
        refresh_token = create_refresh_token(username)

        return AuthMutation(access_token, refresh_token)
Esempio n. 14
0
    def mutate(cls, _, info, username, password):
        print("\n[MUTATION]: [AuthMutation]: mutate: user: {}, password: {}".
              format(username, password),
              file=sys.stderr)

        try:
            dbUser = db.dbMan.getUser(username)
            if dbUser == None or password != dbUser["password"]:
                raise GraphQLError(
                    "[MUTATION]: [AuthMutation]: wrong password")
        except Exception as e:
            print(e, file=sys.stderr)
            raise GraphQLError(e)
        tok = create_access_token(username)
        refrshTok = create_refresh_token(username)
        SessionManager.session.addNewSession(username, tok)
        return AuthMutation(
            access_token=tok,
            refresh_token=refrshTok,
        )
Esempio n. 15
0
    def mutate(self, info, email, password):
        cleaned_email = email.strip().lower()
        user: User = User.query.filter_by(email=cleaned_email).one_or_none()
        if not user or not user.password or not user.is_correct_password(
                password):
            return LoginMutation(
                ResponseMessageField(is_success=False, message="Login failed"))

        access_token = create_access_token(identity={
            "email": user.email,
            "full_name": user.full_name
        })
        refresh_token = create_refresh_token(identity=str(uuid4()))

        return LoginMutation(
            AuthField(
                access_token=access_token,
                refresh_token=refresh_token,
                message="Login Success",
            ))
Esempio n. 16
0
    def mutate(self, info, email_or_username, password):
        result = mongo.db.users.find_one({
            '$or': [{
                'email': email_or_username
            }, {
                'username': email_or_username
            }],
            'is_admin':
            True
        })

        if result is None or check_password_hash(result['password'],
                                                 password) is False:
            return AdminAuthentication(response=ResponseMessage(
                text='Alamat surel/nama pengguna atau kata sandi anda salah!',
                status=False))

        return AdminAuthentication(
            access_token=create_access_token(str(result['_id'])),
            refresh_token=create_refresh_token(str(result['_id'])),
            response=ResponseMessage(text='Berhasil masuk', status=True))
Esempio n. 17
0
    def mutate(self, info, email, password):
        # setup variables
        error = ''
        ok = False
        access_token = ''
        refresh_token = ''

        # retrieve user from db
        user = UserModel.find_user(email=email)

        if user is not None:
            if user.check_password(password):
                ok = True
                access_token = create_access_token(email)
                refresh_token = create_refresh_token(email)
            else:
                error = 'User credentials do not match.'
        else:
            error = 'User not found.'

        return UserLogin(ok=ok,
                         error=error,
                         access_token=access_token,
                         refresh_token=refresh_token)
Esempio n. 18
0
 def mutate(self, info, **kwargs):
     user = User(email=kwargs.get('email')).fetch_by_email()
     if user is None:
         return LoginUser(success=False,
                          user_not_exists=True,
                          wrong_password=None,
                          access_token=None,
                          refresh_token=None,
                          user=None)
     if user.password == kwargs.get('password'):
         return LoginUser(
             success=True,
             wrong_password=None,
             user_not_exists=None,
             access_token=create_access_token(kwargs.get('email')),
             refresh_token=create_refresh_token(kwargs.get('email')),
             user=UserSchema(**user.as_dict()))
     else:
         return LoginUser(success=False,
                          wrong_password=True,
                          user_not_exists=False,
                          access_token=None,
                          refresh_token=None,
                          user=UserSchema(**user.as_dict()))