def post(self):
        try:
            context = request.json
            validation_result = userRegister.validate(request.json)
            if validation_result.get('success', False) is False:
                return response.badRequest(validation_result.get('data'),
                                           validation_result.get('error'))

            userEmail = User.query.filter_by(email=context['email']).first()
            if userEmail != None:
                return response.badRequest(userEmail.email,
                                           'email must be unique'), 400

            if validation_result.get('success', False) is False:
                return response.badRequest(validation_result.get('error'),
                                           'error'), 400

            created_user = User(name=context['name'],
                                email=context['email'],
                                role=context['role'])
            created_user.setPassword(context['password'])
            db.session.add(created_user)
            db.session.commit()
            print(user_schema.dump(created_user))
            return response.success(user_schema.dump(created_user),
                                    'success'), 201
        except Exception as e:
            return response.badRequest(e, 'error'), 500
예제 #2
0
def delete_user(user_id):
    user = User.query.filter_by(user_id=user_id).first()

    user_details = user_schema.dump(user)
    response = {"msg": "User has been deleted", "user_details": user_details}

    db.session.delete(user)
    db.session.commit()
    return make_response(jsonify(response)), 201
예제 #3
0
    def post(self):
        try:
            context = request.json
            data = User.query.filter_by(email=context['email']).first()
            if data is None:
                return response.badRequest("", "Email doens't exis")

            if not data.checkPassword(context['password']):
                return response.badRequest("", "Password salah")

            user = user_schema.dump(data)
            return response.success(user, auth.generateJwt(user))
        except Exception as e:
            return response.badRequest(e, 'error')
 def get(self, id=None):
     try:
         user = get_jwt_identity()
         if user.get('role.name') == "supervisor":
             if id is None:
                 data = User.query.all()
                 return response.success(users_schema.dump(data), 'success')
             else:
                 dataFilter = User.query.filter_by(id=id).first()
                 if dataFilter is None:
                     return response.badRequest([], "Data doens't exist")
                 dataUser = user_schema.dump(dataFilter)
                 return response.success(dataUser, '')
         else:
             return response.badRequest([], 'Unauthorization'), 401
     except Exception as e:
         return response.badRequest(e, 'error')
예제 #5
0
def register_user():
    data = request.get_json()
    status, msg = validate_register_schema(data)
    if status < 0:
        response = {
            'msg': msg
        }
        return make_response(jsonify(response)), 400

    name = data.get("name")
    email = data.get("email")
    password = data.get("password")

    user = User.query.filter_by(email=email).first()

    if not user:
        try:
            user = User(name=name, email=email, password=password)

            access_token = user.generate_jwt_token(user.user_id)

            db.session.add(user)
            db.session.flush()

            user_details = user_schema.dump(user)
            response = {
                'msg': 'The user is registered successfully!',
                'access_token': access_token,
                'user_details': user_details
            }

            db.session.commit()
            return make_response(jsonify(response)), 201

        except Exception as e:
            response = {
                'msg': str(e)
            }
            return make_response(jsonify(response)), 401
    else:
        response = {
            'msg': 'User is already registered'
        }

        return make_response(jsonify(response)), 202
예제 #6
0
def update_user(user_id):
    data = request.get_json()

    status, msg = validate_update_schema(data)
    if status < 0:
        response = {'msg': msg}
        return make_response(jsonify(response)), 401

    user = User.query.filter_by(user_id=user_id).first()
    for key, value in data.items():
        setattr(user, key, value)

    db.session.commit()
    user_details = user_schema.dump(user)
    response = {
        'msg': 'User has been updated successfully',
        'user_details': user_details
    }
    return make_response(jsonify(response)), 201
예제 #7
0
def login():
    """Endpoint for a user's credentials to be checked in order to log in to their account

    .. :quickref: User; Validate user credentials for login.

    **Example request**:

    .. sourcecode:: http

        POST /api/login HTTP/1.1
        Host: localhost
        Accept: application/json
        Content-Type: application/json

        {
            "username": "******",
            "password": "******"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
            "message": "Logged in successfully",
            "user": {
                "username": "******"
            }
        }

    .. sourcecode:: http

        HTTP/1.1 401 UNAUTHORIZED
        Content-Type: application/json

        {
            "message": "Incorrect password",
            "user": null
        }

    :<json string username: unique username
    :<json string password: password for specified account
    :>json message: repsonse information such as error information
    :>json app.models.user.User user: the user object that has been created
    :resheader Content-Type: application/json
    :status 200: successful login
    :status 400: malformed request
    :status 401: incorrect password
    :status 404: user does not exist
    """

    response = {
        'message': '',
        'user': None
    }
    status = 200

    form_schema = LoginFormSchema()
    form_errors = form_schema.validate(request.json)
    if form_errors:
        response['message'] = form_errors
        status = 400
    else:
        username = request.json["username"]
        password = request.json["password"]

        # Checking if user is in database
        user = User.query.get(username)
        if user is None:
            response['message'] = {
                'user': ['User does not exist.']
            }
            status = 404
        else:
            # Checking wether passwords match
            passwords_match = bcrypt.check_password_hash(user.password, password)
            if passwords_match:
                response['message'] = "Logged in successfully"
                response['user'] = user_schema.dump(user)
                status = 200
            else:
                response['message'] = {
                    'user': ['Incorrect password.']
                }
                status = 401

    return response, status
예제 #8
0
def register_user():
    """Creates a user account that does not already exist

    .. :quickref: User; Create new user.

    **Example request**:

    .. sourcecode:: http

        POST /api/user HTTP/1.1
        Host: localhost
        Accept: application/json
        Content-Type: application/json

        {
            "username": "******",
            "f_name": "John",
            "l_name": "Doe",
            "email": "*****@*****.**",
            "password": "******",
            "confirm_password": "******"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
            "message": "Registered user successfully",
            "user": {
                "username": "******"
            }
        }

    .. sourcecode:: http

        HTTP/1.1 400 BAD REQUEST
        Content-Type: application/json

        {
            "message": "Passwords do not match",
            "user": null
        }

    :<json string username: username that does not already exist within the database
    :<json string f_name: first name of the user
    :<json string l_name: last name of the user
    :<json string email: email of the user (in the correct format)
    :<json string password: password for new accoutn
    :<json string confirm_password: retyped password which should match the previous password value
    :>json message: repsonse information such as error information
    :>json app.models.user.User user: the user object that has been created
    :resheader Content-Type: application/json
    :status 200: successful registration
    :status 400: malformed request
    """

    response = {
        'message': '',
        'user': None
    }
    status = 200

    # Checking that form data is correct
    form_schema = RegisterFormSchema()
    form_errors = form_schema.validate(request.json)
    if form_errors:
        response['message'] = form_errors
        status = 400
    else:
        username = request.json["username"]
        f_name =  request.json["f_name"]
        l_name =  request.json["l_name"]
        email =  request.json["email"]
        password = request.json["password"]

        # Checking that user is not already in the system
        if User.query.get(username) is not None:
            response['message'] = {
                'user': ['User already exists.']
            }
            status = 400
        else:
            # Hashing password using brcypt's one-way encryption
            hashed_password = bcrypt.generate_password_hash(password)

            # Creating user and adding to the database
            new_user = User(username, hashed_password, f_name, l_name, email)
            db.session.add(new_user)
            db.session.commit()

            response['message'] = "Success"
            response['user'] = user_schema.dump(new_user)

    return response, status
예제 #9
0
def login_bluetooth():
    """Endpoint for to login via bluetooth

    .. :quickref: User; Validate MAC address to login.

    **Example request**:

    .. sourcecode:: http

        POST /api/login_bluetooth HTTP/1.1
        Host: localhost
        Accept: application/json
        Content-Type: application/json

        {
            "mac_address": "18:F1:D8:E2:E9:6B"
        }

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

        {
            "message": "Logged in successfully",
            "user": {
                "username": "******"
            }
        }

    .. sourcecode:: http

        HTTP/1.1 401 UNAUTHORIZED
        Content-Type: application/json

        {
            "message": "MAC Address either not set, or does not match received.",
            "user": null
        }

    :<json string mac_address: mac address for specified account
    :>json message: repsonse information such as error information
    :>json app.models.user.User user: the user object that has been created
    :resheader Content-Type: application/json
    :status 200: successful login
    :status 401: invalid mac address
    """

    response = {
        'message': '',
        'user': None
    }
    status = 200

    mac_address = request.json["mac_address"]
    # Getting the user that corresponds to this MAC address
    user = User.query.filter_by(mac_address=mac_address).first()

    if user is None:
        response['message'] = "ERROR: Bluetooth device is not registered to a user"
        status = 401
    else:
        response['message'] = "Logged in successfully"
        response['user'] = user_schema.dump(user)
        status = 200

    return response, status
예제 #10
0
파일: user.py 프로젝트: lixiaosheng957/HRMS
def get_userinfo():
    uid = g.user.uid
    user_info = User.query.filter_by(id=uid).first_or_404()
    user_info_result = user_schema.dump(user_info)
    return user_info_result