Exemple #1
0
def profile(user_id):
    q = User.query.filter_by(id=user_id).first()
    if q is None:
        return fail('User not found', 404)

    user = user_schema.dump(q)
    return success(user.data, 200)
Exemple #2
0
 def get(self, id: int):
     """ Geta a user by id"""
     user = UserModel.fetch_by_id(id)
     if user:
         return user_schema.dump(user)
     else:
         return {"message": "That user does not exist"}, 404
Exemple #3
0
def delete(user_id):
    existing_user = User.query.filter_by(id=user_id).first()
    if existing_user is None:
        return fail('User not found', 404)

    deleted_user = user_schema.dump(existing_user)
    db.session.delete(existing_user)
    db.session.commit()

    return success(deleted_user.data, 200)
Exemple #4
0
def register():
    try:
        json = request.get_json()

        if 'password' in json:
            json['password'] = generate_password_hash(json['password'])

        user = user_schema.load(json).save()

        return ok(user_schema.dump(user))

    except ValidationError as err:
        return bad_request(err.to_dict())

    except NotUniqueError:
        return bad_request('User already exists')
Exemple #5
0
def updateProfile(user_id):
    try:
        user_password_schema.validate(request.json)
    except ValidationError as err:
        return fail(err.messages, 422)

    existing_user = User.query.filter_by(id=user_id).first()
    if existing_user is None:
        return fail('User not found', 404)
    if existing_user.password != request.json['password']:
        return fail('Password did not match', 400)

    existing_user.password = request.json['newPassword']
    db.session.commit()

    user = user_schema.dump(existing_user)
    return success(user.data, 200)
Exemple #6
0
def login_user():
    try:
        username = request.json['username']
        password = request.json['password']
        # selecting data without the password and salt as they are not required for the user session
        current_user = User.query.filter_by(telephone=username).first()
        db.session.commit()
        result = user_schema.dump(current_user)
        if (result != {}):
            # checking whether the hashed password matches the database
            if (password == result['password']):
                # returning a jwt to the app
                secret_key = SECRET_KEY
                token = jwt.encode(
                    {
                        'user':
                        username,
                        'userId':
                        result['id'],
                        'exp':
                        datetime.datetime.utcnow() +
                        datetime.timedelta(hours=1)
                    }, secret_key)
                userData = {
                    'id': result['id'],
                    'first_name': result['first_name'],
                    'last_name': result['last_name'],
                    'email': result['email'],
                    'telephone': result['telephone'],
                    'nic_number': result['nic_number']
                }
                return jsonify({
                    'token': token.decode('UTF-8'),
                    'userData': userData
                })
        # returning 401 error to the app
        return make_response('Could Not Authenticate', 401)

    except IOError:
        print("I/O error")
    except ValueError:
        print("Value Error")
    except:
        print("Unexpected error")
        raise
Exemple #7
0
def get_user_salt():
    # user will get their salt to generate the hash required to the provided password
    try:
        username = request.json['username']
        user_hash = User.query.with_entities(
            User.salt).filter_by(telephone=username).first()
        db.session.commit()
        result = user_schema.dump(user_hash)
        if (result != {}):
            return jsonify(result)
        return make_response('User Not Found', 404)

    except IOError:
        print("I/O error")
    except ValueError:
        print("Value Error")
    except:
        print("Unexpected error")
        raise
Exemple #8
0
def signin():

    remote_ip = request.remote_addr
    if request.is_json:
        json_data = request.get_json()
        username = sanitizer(json_data.get("username", "")).lower()
        password = sanitizer(json_data.get("password", ""))

        user = User.query.filter_by(username=username).first()
        if user:
            is_password_right = user.verify_password(password)
            if is_password_right:
                if not user.is_deleted:
                    access_token = create_access_token(
                        fresh=True,
                        identity=username,
                        expires_delta=timedelta(minutes=30))
                    add_log(f"{remote_ip} {user} logged in")
                    user = user_schema.dump(user)
                    return jsonify(message="Login succeeded.",
                                   access_token=access_token,
                                   user=user)
                else:
                    add_log(
                        f"{remote_ip} tried to login as {username} and failed because of user deleted by admin"
                    )
                    return jsonify(
                        message=
                        "Your admin has deleted your user. If you need more information, contact your admin."
                    ), 404
            else:
                add_log(
                    f"{remote_ip} tried to login as {username} and failed because of wrong password"
                )
                return jsonify(message="Wrong username or password!"), 403
        else:
            add_log(
                f"{remote_ip} tried to login as {username} and failed because of wrong username"
            )
            return jsonify(message="Wrong username or password!"), 403
    else:
        return jsonify(
            "Bad Request.\nyou need to send parameters as json object"), 400