Ejemplo n.º 1
0
 def __call__(self,term):
     query_user=User.get_users_like(term)
     if query_user:
         user_schema=UserSchema(many=True)
         user=user_schema.dump(query_user)
         return jsonify({'users': user})
     else:
         return response_message(False, f"No users like {term}")
Ejemplo n.º 2
0
def load_data(user_db_obj):
    """ Load user's data """
    from app.models.schemas import UserSchema

    user_schema = UserSchema()

    data = user_schema.dump(user_db_obj)

    return data
Ejemplo n.º 3
0
    def post(self):
        data = request.get_json()
        if 'roles' in data:
            del data['roles']
        if data is None or len(data) == 0:
            return {"message": "Request params required"}, 400
        create_user_schema = CreateUserSchema()
        errors = create_user_schema.validate(data)
        if len(errors) == 0:
            data = create_user_schema.load(data)

            # check username
            user = User.query.filter_by(username=data['username']).first()
            if user is not None:
                return {'message': 'Username exists!'}, 400

            # check email
            user = User.query.filter_by(email=data['email']).first()
            if user is not None:
                return {'message': 'Email exists!'}, 400

            # create user
            u = User(username=data['username'],
                     email=data['email'],
                     first_name=data['first_name'],
                     last_name=data['last_name'])
            u.set_password(data['password'])
            roles = Role.query.filter(Role.name.in_(data['roles'])).all()
            for r in roles:
                u.roles.append(r)
            try:
                db.session.add(u)
                db.session.commit()

            except SQLAlchemyError as e:
                db.session.rollback()
                if type(e).__name__ == 'IntegrityError':
                    response = {
                        'message':
                        'Error inserting new user: '******'message': 'DB error: ' + e.orig.args[0]}
                return response, 500

            user_schema = UserSchema()
            result = user_schema.dumps(u)
            response = {'data': result}
            sendWelcomeEmail(u)
            return "", 201
        else:
            response = {
                'message': 'there were errors with the user submission',
                'errors': errors
            }
            return response, 400
Ejemplo n.º 4
0
 def post(self):
     username = get_jwt_identity()
     user = User.query.filter_by(username=username).first()
     if user is None:
         return {'message': 'Invalid token'}, 401
     users_schema = UserSchema()
     u = users_schema.dump(user)
     expires = datetime.timedelta(days=365)
     token = create_access_token(u, expires_delta=expires)
     return {'token': token}, 201
Ejemplo n.º 5
0
def load_data(user_db_obj):
    """ Load user's data

    Parameters:
    - User db object
    """
    from app.models.schemas import UserSchema

    user_schema = UserSchema()

    data = user_schema.dump(user_db_obj)

    return data
Ejemplo n.º 6
0
    def __call__(self, user_email):

        if validate_email(user_email):
            query_user = User.query.filter_by(active=True,
                                              email=user_email).first()
            if query_user:
                user_schema = UserSchema()
                user = user_schema.dump(query_user)
                return jsonify({'user': user})
            else:
                return response_message(False, f"{user_email} doesn't exists")
        else:
            return response_message(False,
                                    f"{user_email} is not a valid email")
Ejemplo n.º 7
0
    def test_schema(self):
        u = User(username="******", password="******")
        u_dump = UserSchema().dump(u)

        self.assertTrue(u_dump["username"] == "gentoo")

        with self.assertRaises(KeyError):
            u_dump["password_hash"]
Ejemplo n.º 8
0
 def post(self):
     data = request.get_json()
     if len(data) == 0:
         return {"message": "Request params required"}, 400
     login_schema = LoginSchema()
     errors = login_schema.validate(data)
     if len(errors) != 0:
         response = {
             'message': 'there were errors with the user submission',
             'errors': errors
         }
         return response, 400
     data = login_schema.load(data)
     user = User.query.filter_by(username=data['username'],
                                 active=True).first()
     if user is None:
         return {'message': 'Invalid username or password'}, 401
     if user.check_password(data['password']):
         users_schema = UserSchema()
         u = users_schema.dump(user)
         token = create_access_token(identity=u)
         return {'token': token}, 200
     else:
         return {"message": "Invalid username or password"}, 401
Ejemplo n.º 9
0
from datetime import datetime

from flask import current_app
from flask_jwt_extended import create_access_token

from app import db
from app.models.schemas import UserSchema
from app.models.user import User
from app.utils import err_resp, internal_err_resp, message

user_schema = UserSchema()


class AuthService:
    @staticmethod
    def login(data):
        # Assign vars
        email = data["email"]
        password = data["password"]

        try:
            # Fetch user data
            if not (user := User.query.filter_by(email=email).first()):
                return err_resp(
                    "The email you have entered does not match any account.",
                    "email_404",
                    404,
                )

            elif user and user.verify_password(password):
                user_info = user_schema.dump(user)
Ejemplo n.º 10
0
 def __call__(self):
     query_users = User.query.filter_by(active=True).all()
     user_schema = UserSchema(many=True)
     users = user_schema.dump(query_users)
     return jsonify({'users': users})