def test_get_shelters_auth(app_with_envion_DB):
    jwt = create_jwt(identity="admin")

    client = app_with_envion_DB.test_client()
    rv = client.get('/api/shelters/',
                    environ_base={'HTTP_AUTHORIZATION': 'Bearer ' + jwt})
    assert rv.status_code == 200
Example #2
0
def handle_login():
    body = request.get_json()

    if body is None:
        return jsonify({
                'msg': 'login cannot be empty'
                })
    else:
        if body['email'] != loginEmail:
            return jsonify({
                'msg': 'wrong email'
                })
        elif body['password'] != loginPassword:
                return jsonify({
                'msg': 'wrong password'
                })
        else:
            TheLoginToken = create_jwt(identity=1)

            saveToken = logintokens.query.filter_by(id=1).first()
            saveToken.token = TheLoginToken
            db.session.commit()

            return jsonify({
                'token': TheLoginToken,
                'email': body['email'],
                'name': "admin"
                })

    return "Invalid Method", 404
def user_update():
    email=get_jwt_identity()
    userdb = User.query.filter(User.email == email).first()
    user=request.json["user"]

    if "email" in user:
        email=user["email"]
        return "Cannot change email",401
    
    if "bio" in user:
        userdb.bio=user["bio"]
    
    if "image" in user:
        userdb.image=user["image"]
    
    if "username" in user:
        userdb.username=user["username"]

    if "password" in user:
        userdb.password=user["password"]

    db.session.commit()

    updated_user={
        "user":{
            "email":userdb.email,
            "username":userdb.username,
            "token":create_jwt(identity=userdb.email),
            "bio":userdb.bio,
            "image":userdb.image
        }
    }

    return json.dumps(updated_user)
Example #4
0
def fetch_profile():
    """
        Fetch user info: pic, username, email, friends, and favorite songs. To
        fetch the profile pic, put the path specified in the GET_IMAGE route as
        the src for the IMG tag substituting <path:filename> with the path
        returned as the PROFILE_PIC attribute in this method's JSON response.

    """

    errors = {}

    try:
        req = request.get_json()
        user = User.objects.get(email=req['email'])
        user.creator_status = None
        data = {
            'profile_pic': user.profile_pic,
            'username': user.username,
            'email': user.email,
            'favorite_songs': user.favorite_songs_list,
        }
        token = create_jwt(identity=user.username)
        username = user.username
    except:
        errors['login'] = '******'
        token = None
        data = {}
        username = None

    return json.dumps({
        'username': username,
        'errors': errors,
        'data': data,
        'jwt': token
    })
Example #5
0
def login():

    if request.method == 'GET':
        return render_template('login.html', host=os.environ.get('API_HOST'))

    json = request.get_json()
    utils.check_params(json, 'email', 'password')

    user = Users.query.filter_by(email=json['email'],
                                 password=utils.sha256(
                                     json['password'])).first()

    if user is None:
        return jsonify({
            'login': False,
            'message': 'Email and password are incorrect',
        })

    return jsonify({
        'login': True,
        'jwt': create_jwt({
            'id': user.id,
            'role': 'admin'
        })
    })
Example #6
0
def post_user():
    try:
        utils.flask_validate_request_is_json(request)
        payload = utils.get_auth0_payload(app, request)
        now = datetime.datetime.now()
        uuid = str(utils.generate_uuid())
        in_user = utils.get_args(
            received=request.json,
            defaultable={
                'id': uuid,
                'created_at': now,
                'updated_at': now,
                'payload': {}
            },
            constant={'type_id': 1},
        )
        in_user['username'] = payload['sub']
        user = db_api.add_row(User, in_user)
        identity = utils.create_jwt_identity(user, payload)
        return utils.flask_return_success({
            'jwt': create_jwt(identity),
            'user': user.json_dict
        })
    except Exception as e:
        return utils.flask_handle_exception(e)
Example #7
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # check for user in database
    usercheck = User.query.filter_by(username=username,
                                     password=password).first()

    # if user not found
    if usercheck == None:
        return jsonify({"msg": "Invalid credentials provided"}), 401

    #if user found, Identity can be any data that is json serializable
    ret = {'jwt': create_jwt(identity=username)}
    return jsonify(ret), 200
Example #8
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    params = request.get_json()
    email = params.get('email', None)
    password = params.get('password', None)
    if not email:
        return jsonify({"msg": "Missing email parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    # vendor = Vendor.query.filter_by(email= email).one_or_none()
    # if vendor is None:
    #     return jsonify({"msg": "Email not found"}), 404
    # else:
    #     if password == vendor.password:
    #         return jsonify({
    #             token: create_jwt(identity=vendor.id),
    #             vendor: vendor.serialize()
    #         }), 200
    #     else:
    #         return jsonify({"msg": "Bad email or password"}),
    specific_vendor = Vendor.query.filter_by(email=email).one_or_none()
    if isinstance(specific_vendor, Vendor):
        if specific_vendor.password == password:
            # oh, this person is who it claims to be!
            # Identity can be any data that is json serializable
            response = {
                'jwt': create_jwt(identity=specific_vendor.id),
                "vendor": specific_vendor.serialize()
            }
            return jsonify(response), 200
        else:
            return jsonify({"msg": "bad credentials"}), 400
    else:
        return jsonify({"msg": "bad credentials"}), 400
Example #9
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400
    params = request.get_json()
    email = params.get('email', None)
    password = params.get('password', None)
    # type_of_user = params.get('type_of_user', None)
    if not email:
        return jsonify({"msg": "Missing email in request"}), 400
    if not password:
        return jsonify({"msg": "Missing password in request"}), 400

    # check for "type_of_user" in database
    type_of_user = '******'
    usercheck = User.query.filter_by(email=email, password=password).first()
    if usercheck is None:
        # type_of_user = '******'
        usercheck = Job-Seeker.query.filter_by(email=email, password=password).first()

    # if user not found
    if usercheck == None:
        return jsonify({"msg": "Invalid credentials provided"}), 401

    #if user found, Identity can be any data that is json serializable
    ret = {
        # 'jwt': create_jwt(identity=email), <---- Will not work if un-commented
        'user': usercheck.serialize(),
        'jwt': create_jwt(identity=email)
    }
    return jsonify(ret), 200

# PUT request
    if request.method == 'PUT':
        body = request.get_json()
        if body is None:
            raise APIException("You need to specify the request body as a json object", status_code=400)

        user1 = User.query.get(user_id)
        if user1 is None:
            raise APIException('User not found', status_code=404)

        if "first_name" in body:
            user1.name = body["first_name"]
        if "last_name" in body:
            user1.name = body["last_name"]
        if "email" in body:
            user1.email = body["email"]
        if "password" in body:
            user1.password = body["password"]
        if "address" in body:
            user1.zipcode = body["address"]
        if "sex" in body:
            user1.sex = body["sex"]
        if "zipcode" in body:
            user1.zipcode = body["zipcode"]
        if "type_of_user" in body:
            user1.zipcode = body["type_of_user"]
        db.session.commit()

        return jsonify(user1.serialize()), 200
Example #10
0
    def login():
        if not request.is_json:
            return common.make_response_error(-1, '请使用json传输数据!')

        params = request.get_json()
        username = params.get('username', None)
        password = params.get('password', None)

        if not username:
            return common.make_response_error(-1, '用户名不能为空!')
        if not password:
            return common.make_response_error(-1, '密码不能为空!')

        ua_info = UserAuth.query.filter_by(user_name=username).first()
        if ua_info is None:
            return common.make_response_error(-1, '用户不存在!')

        # 找到用户后获取用户信息表数据
        user_info = UserInfo.getByUserId(UserInfo, ua_info.id)
        if UserAuth.check_password(UserAuth,
                                   password_hash=ua_info.password_hash,
                                   password=password):
            login_time = datetime.datetime.now()
            user_info.login_time = login_time
            UserInfo.update(UserInfo)
        else:
            return common.make_response_error(-1, '密码不正确!')

        data = {
            'token': 'Bearer ' + create_jwt(identity=ua_info.id),
            'user_info': user_info
        }

        return common.make_response_ok(data=data)
Example #11
0
    def test_authexpire_with_valid_token(self):
        # get a valid token
        username = '******' + uuid.uuid4().hex[:4]
        with self.app.app_context():
            # create an admin user
            from app.models.user import User
            User.new_user(user_id=username, isAdmin=True)
            from flask_jwt_simple import create_jwt, decode_jwt
            token = create_jwt(identity=username)
        # act
        before_expire = self.client.get('/users',
                                        headers=[('Authorization',
                                                  'Bearer ' + token)])
        expire = self.client.post('/auth/expire',
                                  headers=[('Authorization', 'Bearer ' + token)
                                           ])
        test_expire = self.client.get('/users',
                                      headers=[('Authorization',
                                                'Bearer ' + token)])

        # assert
        self.assertEqual(before_expire.status_code, 200, before_expire.data)
        self.assertIn('users', before_expire.json)
        self.assertEqual(expire.status_code, 200, expire.data)
        self.assertIn('message', expire.json)
        self.assertIn('manually expired', expire.json['message'])
        self.assertEqual(test_expire.status_code, 401, test_expire.data)
        self.assertIn('message', test_expire.json)
        self.assertIn('token has expired', test_expire.json['message'])
Example #12
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('email',
                            type=str,
                            help='Email address to create user')
        parser.add_argument('password',
                            type=str,
                            help='Password to create user')
        args = parser.parse_args()

        _userEmail = args['email']
        _userPassword = args['password']

        stmt = select([data.users.c.id, data.users.c.name, data.users.c.email, data.users.c.phone, data.users.c.location, data.users.c.password]) \
            .select_from(data.users).where(data.users.c.email == _userEmail)
        res = data.conn.execute(stmt)
        res_dict = [dict(r) for r in res]
        if not len(res_dict):
            return {'message': 'Invalid Credentials'}, 401
        encrypted_pass = res_dict[0]['password']
        if bcrypt.checkpw(_userPassword.encode('utf-8'),
                          hashed_password=encrypted_pass.encode('utf-8')):
            ret = {
                'token':
                create_jwt({
                    'email': res_dict[0]['email'],
                    'id': res_dict[0]['id']
                })
            }
            res = jsonify(ret)
            res.status_code = 200
            return res

        else:
            return {'message': 'Invalid Credentials'}, 401
Example #13
0
def manejar_ingreso():
    """
        POST: revisamos si el usuario existe. Si existe, revisamos
        si el password que envía es correcto. ¿Cómo sabemos si el 
        usuario existe? Aquí vamos a recibir en el request un diccionario
        con cédula y password.
    """
    input_data = request.json
    if (
        "cedula" not in input_data or
        "password" not in input_data    
    ):
        return jsonify({
            "resultado": "Lo siento, persona, envíe los insumos correctos..."
        }), 400
    else:
        usuario = Donante.query.filter_by(
            cedula=input_data["cedula"]
        ).one_or_none()
        if usuario is None:
            return jsonify({
                "resultado": "En verdad el usuario no existe, pero le voy a decir que el password no es válido"
            }), 400
        else:
            if usuario.check_password(input_data["password"]):
                # success
                token = create_jwt(identity=usuario.id)
                return jsonify({
                    "token": token,
                    "cedula": usuario.cedula
                }), 200
            else:
                return jsonify({
                    "resultado": "El usuario sí existe y el password no sirve..."
                }), 400
Example #14
0
def login():
    try:
        data = request.json
        if employees.find_employee(data['login']):
            user = employees.validate_password(data['login'].lower(),
                                               data['password'])
            user_view = employees.user_view(user)
        elif guests.find_guest(data['login']):
            user = guests.validate_password(data['login'].lower(),
                                            data['password'])
            user_view = guests.user_view(user)
        else:
            raise Exception('Such user do not exist!')
        data = {
            'jwt': create_jwt(identity=data['login'].lower()),
            'user': user_view
        }
        if SECURITY_ALERT_ENABLED:
            # security_alert(get_user_ip(), login)
            print('Sending email')
        response = jsonify(data)

        expires = datetime.fromtimestamp(time.time() + 30 * 24 * 60 * 60)
        return response, 200
    except Exception as e:
        print(str(e))
        return 'Failed to login: ' + str(e), 400
Example #15
0
def reset_password(id):

    if id == 'me':
        id = str(get_jwt())['sub']

    if not id.isnumeric():
        raise APIException('Invalid id: ' + id, 400)

    if request.args.get('forgot') == 'true':
        return jsonify({
            'message':
            'A link has been sent to your email to reset the password',
            'link':
            os.environ.get('API_HOST') + '/users/reset_password/' +
            create_jwt({
                'id': id,
                'role': 'password'
            })
        }), 200

    body = request.get_json()
    check_params(body, 'email', 'password', 'new_password')

    user = Users.query.filter_by(id=int(id),
                                 email=body['email'],
                                 password=sha256(body['password'])).first()
    if not user:
        raise APIException('Invalid parameters', 400)

    user.password = sha256(body['new_password'])

    db.session.commit()

    return jsonify({'message': 'Your password has been changed'}), 200
    def login():

        req = request.get_json()
        check_params(req, 'email', 'password', 'device_token')

        user = Users.query.filter_by(email=req['email'],
                                     password=sha256(req['password'])).first()

        if user is None:
            raise APIException('Sorry you entered the wrong email or password',
                               404)
        if user.status._value_ == 'invalid':
            raise APIException('Email not validated', 405)
        if user.status._value_ == 'suspended':
            raise APIException('Your account is suspended', 405)

        is_token_registered = \
            Devices.query.filter_by( token=req['device_token'] ).first() is not None
        profile_exists = Profiles.query.get(user.id) is not None

        if profile_exists and not is_token_registered:
            db.session.add(Devices(user_id=user.id, token=req['device_token']))
            db.session.commit()

        return jsonify({
            'jwt':
            create_jwt({
                'id': user.id,
                'role': 'user',
                'exp': req.get('exp', 15)
            })
        }), 200
Example #17
0
def login(user_info):
    user = User.create_or_update(user_info)
    token = create_jwt(identity=user.id)
    redirect_url = current_app.config.get('AUTH_REDIRECT_URL', None)
    if redirect_url is None:
        return token
    return redirect(Href(redirect_url)(token=token))
Example #18
0
def login():
    try:
        if not request.is_json:
            return jsonify({"msg": "Missing JSON in request"}), 400

        params = request.get_json()
        username = params.get('username', None)
        password = params.get('password', None)

        if not username:
            return jsonify({"msg": "Missing username parameter"}), 400
        if not password:
            return jsonify({"msg": "Missing password parameter"}), 400

        usercheck = User.query.filter_by(username=username,
                                         password=password).first()
        if usercheck == None:
            return jsonify({"msg": "Bad username or password"}), 401
        ret = {
            'jwt': create_jwt(identity=username),
            "id": usercheck.id,
            "email": usercheck.email,
            "name": usercheck.name
        }
        return jsonify(ret), 200
    except SQLAlchemyError as e:
        return jsonify({"error": str(e.__dict__['orig'])}), 409

    return jsonify({"message": "success"}), 200
Example #19
0
 def post(self):
     parase.add_argument("username", type=str, required=True)
     parase.add_argument("password", type=str, required=True)
     args = parase.parse_args()
     username = args["username"]
     password = args["password"]
     name_check = User.query.filter_by(name=username).first()
     password_check = User.query.filter_by(name=username,
                                           password=password).first()
     if name_check:
         if password_check:
             auth = True
             message = "Welcome {0}!".format(username)
         else:
             auth = False
             message = "{0},Please input correct password!".format(username)
     else:
         auth = False
         message = "{0} is not found, please sign in first!".format(
             username)
     if auth:
         token = {"jwt": create_jwt(identity=username)}
         response = jsonify(token)
         response.status_code = 200
         return response
     else:
         response = jsonify({"Error": message})
         response.status_code = 400
         return response
Example #20
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    email = params.get('email', None)
    password = params.get('password', None)

    if not email:
        return jsonify({"msg": "Missing email in request"}), 400
    if not password:
        return jsonify({"msg": "Missing password in request"}), 400

    # check for user in database
    usercheck = User.query.filter_by(email=email, password=password).first()
    companycheck = Company.query.filter_by(email=email,
                                           password=password).first()
    # if user not found
    if usercheck is None and companycheck is None:
        return jsonify({"msg": "Invalid credentials provided"}), 401

    if usercheck is not None:
        usercheck = usercheck.serialize()

    if companycheck is not None:
        companycheck = companycheck.serialize()

    #if user found, Identity can be any data that is json serializable
    ret = {
        'jwt': create_jwt(identity=email),
        'user': usercheck,
        'company': companycheck
    }
    return jsonify(ret), 200
Example #21
0
def login():

    if request.method == 'POST':
        body = request.get_json()
        user = User.query.filter_by(email=body['email'],
                                    password=body['password']).first()

        if not user:
            return 'User not found', 404
        if not user.email:
            return jsonify({"msg": "Missing email parameter"}), 400
        if not user.password:
            return jsonify({"msg": "Missing password parameter"}), 400
        return jsonify({
            'token': create_jwt(identity=1),
            'id': user.id,
            'email': user.email,
            'firstName': user.firstName
        })
    # GET request
    if request.method == 'GET':
        all_users = User.query.all()
        all_users = list(map(lambda x: x.serialize(), all_users))
        return jsonify(all_users), 200

    return "Invalid Method", 404
Example #22
0
def signup():
    params = request.get_json(silent=True)
    invite_code = params.get('inviteCode', None)
    email = params.get('email', None)
    password = params.get('password', None)
    name = params.get('name', None)
    if not invite_code:
        raise JSONException('Missing inviteCode parameter')
    if not email:
        raise JSONException('Missing email parameter')
    if not password:
        raise JSONException('Missing password parameter')
    if not name:
        raise JSONException('Missing name parameter')
    if invite_code not in invites:
        raise JSONException('Invalid invite code')
    current_user = None
    if email in users:
        raise JSONException('Email is already signed up', status_code=409)
    current_user = User(email, password, name)
    users[email] = current_user
    del invites[invite_code]
    response = {
        'jwt': create_jwt(identity=current_user.email),
        'name': current_user.name,
        'admin': False
    }
    return jsonify(response), 200
Example #23
0
    def post(self):
        data = request.get_json()
        email = data['email']
        password = data['password']

        if email == '':
            return {'message': 'Email não informado'}, 401

        if password == '':
            return {'message': 'Senha não informada'}, 401

        user = UserModel.authenticate(email, password)

        if user is not None:
            token = create_jwt({
                'email': user.email,
                'name': user.name,
                'role': user.role,
                'id': user.id,
                'cpf': user.cpf,
            })

            return {'name': user.name, 'token': token}
        else:
            return {'message': 'Invalid credentials'}, 401
Example #24
0
def login():
    """View function for login view."""
    logger.info('Logged in user')

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg":
                        "Missing username parameter"}), Status.HTTP_BAD_REQUEST
    if not password:
        return jsonify({"msg":
                        "Missing password parameter"}), Status.HTTP_BAD_REQUEST

    # TODO Check from DB here
    if username != 'admin' or password != 'admin':
        return jsonify({"msg": "Bad username or password"
                        }), Status.HTTP_BAD_UNAUTHORIZED

    # Identity can be any data that is json serializable
    # TODO: rather than passing expiry time here explicitly, decode token on client side. But I'm lazy.
    ret = {
        'jwt': create_jwt(identity=username),
        'exp': datetime.utcnow() + current_app.config['JWT_EXPIRES']
    }
    return jsonify(ret), 200
Example #25
0
    def post(self):
        data = request.get_json()
        email = data['email'].strip()
        password = encrypt(data['password'])
        user = UserModel.authenticate(email, password)

        if user:

            access = create_jwt({
                'id_user': user.id,
                'email': user.email,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'active': user.active
            })

            return {
                'id_user': user.id,
                'email': user.email,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'active': user.active,
                'jwt': access
            }, 200
        else:
            return {'message': 'Invalid credentials'}, 400
Example #26
0
def register():
    username = request.json['username']
    password = request.json['password']

    new_user = User.save_user(username, generate_password_hash(password))

    return {'token': create_jwt(identity=new_user.id)}, 201
Example #27
0
    def post(self):
        if not request.is_json:
            return APIResult.ErrorResult(100,
                                         msg="Missing JSON in request"), 400

        params = request.get_json()
        username = params.get('username', None)
        password = params.get('password', None)

        if not username:
            return APIResult.ErrorResult(status=101,
                                         msg="Missing username parameter"), 400
        if not password:
            return APIResult.ErrorResult(status=101,
                                         msg="Missing password parameter"), 400

        if username != JWTEndpoint.user or password != JWTEndpoint.pwd:
            return APIResult.ErrorResult(status=101,
                                         msg="Bad username or password"), 401

        # Identity can be any data that is json serializable

        ret = {
            'jwt':
            create_jwt(identity=username),
            'exp':
            timegm((flask.current_app.config['JWT_EXPIRES'] +
                    datetime.now()).utctimetuple())
        }
        return ret, 200
Example #28
0
def login():
    '''
    User Login
    parameters:
        user, password
    response:
        200:
            jwt: token
            roles: list of roles user is authorized for
        400:
            missing credentials
        401:
            not authorized
    '''
    if not request.is_json:
        raise InvalidUsage("Missing JSON in request")

    params = request.get_json()
    user = params.get('user', None)
    password = params.get('password', None)

    if not user:
        raise InvalidUsage("Missing username parameter")
    if not password:
        raise InvalidUsage("Missing password paramter")

    db_user = User.query.filter_by(username=user).first()
    if not db_user or db_user.password != password:
        raise UnauthorizedUse()
    roles = [role.name for role in db_user.roles]
    return jsonify(jwt=create_jwt(identity=user), roles=roles), 200
Example #29
0
def login():
    """View function for login view."""
    logger.info('Logged in user')

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)
    user = Session.query(User).filter_by(username=username).first()

    print(user)
    if not username:
        return jsonify({"msg":
                        "Missing username parameter"}), Status.HTTP_BAD_REQUEST
    if not password:
        return jsonify({"msg":
                        "Missing password parameter"}), Status.HTTP_BAD_REQUEST
    if not user:
        return jsonify({"msg":
                        "Bad password or username"}), Status.HTTP_BAD_REQUEST

    # TODO Check from DB
    if username != user.username or not verify_password(
            password, user.password):
        return jsonify({"msg": "Bad username or password"
                        }), Status.HTTP_BAD_UNAUTHORIZED

    # Identity can be any data that is json serializable
    ret = {
        'jwt': create_jwt(identity=user.email),
        'exp': datetime.utcnow() + current_app.config['JWT_EXPIRES']
    }
    return jsonify(ret), 200
Example #30
0
def signup():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    email = params.get('email', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not email:
        return jsonify({"msg": "Missing email parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    email_query = Users.query.filter_by(email=email).first()
    if email_query is not None:
        return jsonify({"msg": "Email already exist"}), 401
    
    name_query = Users.query.filter_by(username=username).first()
    if name_query is not None:
        return jsonify({"msg": "User name already exist"}), 401

    user = Users(username=username, email=email, password=password, role_id=1)
    db.session.add(user)
    db.session.commit()

    # Identity can be any data that is json serializable
    ret = {'jwt': create_jwt(identity=username), 'lvl': 3}
    return jsonify(ret), 200
Example #31
0
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    ret = {'jwt': create_jwt(username)}
    return jsonify(ret), 200
Example #32
0
 def post(self):
     """ Authentication endpoint
     
         Args:
             uid (str) : user id
             password (str) : user password
         Returns:
             str: access token if login details are correct, otherwise
             returns an error message 
     """
     args = usr_parser.parse_args()
     user = User.query.get(args['uid'])
     if user and sha256.verify(args['password'], user.password):
         return {'access_token': create_jwt(identity=user.id)}, 200
     return { "message" : "Login details are incorrect" }, 401
Example #33
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = User.query.filter_by(username=username).first()
    if bcrypt.checkpw(password.encode("utf8"), user.password.encode("utf8")):
        ret = {'jwt': create_jwt(identity=username)}
        return jsonify(ret), 200
    else:
        return jsonify({"msg": "Bad username or password"}), 401
Example #34
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    ret = {'jwt': create_jwt(identity=username)}
    return jsonify(ret), 200
Example #35
0
def login():
    """View function for login view."""
    logger.info('Logged in user')

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), Status.HTTP_BAD_REQUEST
    if not password:
        return jsonify({"msg": "Missing password parameter"}), Status.HTTP_BAD_REQUEST

    # TODO Check from DB here
    if username != 'admin' or password != 'admin':
        return jsonify({"msg": "Bad username or password"}), Status.HTTP_BAD_UNAUTHORIZED

    # Identity can be any data that is json serializable
    # TODO: rather than passing expiry time here explicitly, decode token on client side. But I'm lazy.
    ret = {'jwt': create_jwt(identity=username), 'exp': datetime.utcnow() + current_app.config['JWT_EXPIRES']}
    return jsonify(ret), 200