Esempio n. 1
0
def get_user_status():
    # get auth token
    auth_header = request.headers.get("Authorization")
    response_object = {
        "status": "fail",
        "message": "Provide a valid auth token."
    }
    if auth_header:
        auth_token = auth_header.split(" ")[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(id=resp).first()
            response_object.update({
                "status": "success",
                "message": "Success",
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "email": user.email,
                    "active": user.active,
                    "created_at": user.created_at,
                }
            })
            return jsonify(response_object), 200
        response_object["message"] = resp
        return jsonify(response_object), 401
    else:
        return jsonify(response_object), 401
Esempio n. 2
0
    def post(self):
        """ Logout Existing User """
        # Authenticate using Auth-Token
        auth_header = request.headers.get('Auth-Token')
        uid = request.headers.get('UID')
        print(request.headers)
        if auth_header:
            auth_token = auth_header
            print("Here is our token: %s" % (auth_token))
            resp = User.decode_auth_token(auth_token)
            if resp == uid:
                response = jsonify({
                    'status': 'success',
                    'message': 'Successfully logged out.'
                })

                response.status_code = 200
                return response
            else:
                response = jsonify({
                    'status': 'error',
                    'message': 'Invalid UID or Auth-Token'
                })
                response.status_code = 401
                return response

        # handle error
        else:
            response = jsonify({
                'status ': 'error',
                'message': 'Invalid token. Please login again.'
            })
            response.status_code = 403
            return response
 def test_decode_auth_token(self):
     """Ensure auth tokens are decoded correctly."""
     user = add_user('*****@*****.**', 'test')
     auth_token = user.encode_auth_token(user.id)
     self.assertTrue(isinstance(auth_token, bytes))
     self.assertTrue(
         User.decode_auth_token(auth_token.decode("utf-8")) == 1)
Esempio n. 4
0
def status():
    response_object = {
        'status': 'fail',
        'message': 'Provide a valid auth token.'
    }

    auth_header = request.headers.get('Authorization')

    if auth_header:
        auth_token = auth_header.split(' ')[1]
        resp = User.decode_auth_token(auth_token)

        if not isinstance(resp, str):
            user = User.query.filter_by(id=resp).first()
            response_object['status'] = 'success'
            response_object['message'] = 'Success.'
            response_object['data'] = user.to_json()

            return jsonify(response_object), 200
        else:
            response_object['message'] = resp

            return jsonify(response_object), 401
    else:
        return jsonify(response_object), 403
Esempio n. 5
0
    def decorated_function(*args, **kwargs):
        response_object = {
            'status': 'fail',
            'message': 'Provide a valid auth token.'
        }
        auth_header = request.headers.get('Authorization')

        # check if the header is provided
        if not auth_header:
            return jsonify(response_object), 403

        # get the token and decode it
        auth_token = auth_header.split(' ')[1]
        resp = User.decode_auth_token(auth_token)

        if isinstance(resp, str):
            # this means that an exception is caught
            response_object['message'] = resp
            return jsonify(response_object), 401

        # get the user and varify its identity and activity
        user = User.query.filter_by(id=resp).first()
        if not user or not user.active:
            return jsonify(response_object), 401

        return f(resp, *args, **kwargs)
Esempio n. 6
0
def get_user_status():
    response_object = {
        'status': 'fail',
        'message': 'Provide a valid auth token.'
    }
    # get auth header
    auth_header = request.headers.get('Authorization')

    if auth_header:
        auth_token = auth_header.split(' ')[-1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            print(f'resp = {resp}, {type(resp)}')
            user = User.query.filter_by(id=resp).first()
            response_object['status'] = 'success'
            response_object['data'] = {
                'username': user.username,
                'email': user.email,
                'active': user.active
            }
            return jsonify(response_object), 200

        response_object['message'] = resp
        return jsonify(response_object), 401

    else:
        jsonify(response_object), 401
Esempio n. 7
0
 def post(self):
     # get auth token
     auth_header = request.headers.get('Authorization')
     if auth_header:
         auth_token = auth_header.split(" ")[1]
     else:
         auth_token = ''
     if auth_token:
         resp = User.decode_auth_token(auth_token)
         if not isinstance(resp, str):
             # mark the token as blacklisted
             blacklist_token = BlacklistToken(token=auth_token)
             try:
                 # insert the token
                 db.session.add(blacklist_token)
                 db.session.commit()
                 responseObject = {
                     'status': 'success',
                     'message': 'Successfully logged out.'
                 }
                 return make_response(jsonify(responseObject)), 200
             except Exception as e:
                 responseObject = {'status': 'fail', 'message': e}
                 return make_response(jsonify(responseObject)), 401
         else:
             responseObject = {'status': 'fail', 'message': resp}
             return make_response(jsonify(responseObject)), 401
     else:
         responseObject = {
             'status': 'fail',
             'message': 'Provide a valid auth token.'
         }
         return make_response(jsonify(responseObject)), 403
Esempio n. 8
0
    def post(self):
        """ Current User Status """
        auth_header = request.headers.get('Auth-Token')
        uid = request.headers.get('UID')
        # get auth token

        if auth_header:
            auth_token = auth_header
            resp = User.decode_auth_token(auth_token)

            if resp == uid:
                user = User.query.filter_by(uid=resp).first()
                response = jsonify({
                    'status': 'success',
                    'data': {
                        'status': user.status
                    }
                })
                response.status_code = 200
                return response
            response = jsonify({'status': 'error', 'message': resp})
            response.status_code = 401
            return response

        # handle error
        else:
            response = jsonify({
                'status': 'error',
                'message': 'Provide a valid auth token.'
            })
            response.status_code = 401
            return response
Esempio n. 9
0
 def test_decode_auth_token(self):
     company = add_company('Kalkuli', '00.000.000/0000-00',
                           '*****@*****.**', 'kaliu', '789548546',
                           'ceilandia', 'df', '40028922')
     user = add_user('dutra', '*****@*****.**', 'test', company.id)
     auth_token = user.encode_auth_token(user.id)
     self.assertTrue(isinstance(auth_token, bytes))
     self.assertEqual(User.decode_auth_token(auth_token), user.id)
 def test_decode_auth_token(self):
     """
     Ensure that we can decode auth token
     """
     user = add_user('0x0e35462535dae6fd521f0eea67dc4e9485c714dc')
     auth_token = user.encode_auth_token(user.id)
     self.assertTrue(isinstance(auth_token, bytes))
     self.assertEqual(User.decode_auth_token(auth_token), user.id)
Esempio n. 11
0
    def test_decode_auth_token(self):
        school = add_school('testschool')

        user = add_user('justatest', '*****@*****.**', 'test', TEACHER, 'MAO',
                        school.id)
        auth_token = user.encode_auth_token(user.id)
        self.assertTrue(isinstance(auth_token, bytes))
        self.assertTrue(User.decode_auth_token(auth_token), user.id)
Esempio n. 12
0
    def get(self, uid):
        # Authenticate using Auth-Token
        auth_header = request.headers.get('Auth-Token')
        if auth_header: 
            auth_token = auth_header
            print("AUTH TOKEN: %s"%(auth_token))
            resp = User.decode_auth_token(auth_token)
            print("RESP : %s"%(resp))
            if resp == uid:
                """ Getting single user details """
                userData = User.query.filter_by(uid=uid).first()
                if not userData:
                    response = jsonify({
                        'status':'fail',
                        'message': 'Fail to pull user data',
                        'status_code': 401
                    })
                else:
                    response = jsonify({
                        'status': 'success',
                        'message': 'Successful pull user data',
                        'data': {
                            'first_name':userData.first_name,
                            'last_name':userData.last_name,
                            'email':userData.email,
                            'admin':userData.admin,
                            'status':userData.status,
                            'username':userData.username,
                            'profile':userData.profile,
                            'ssn':userData.ssn, 
                            'created_at':userData.created_at,
                            'driverLicense':userData.driverLicense,
                            'birthday':userData.birthday.strftime("%Y-%m-%d"),
                            'company':userData.company,
                            'last_step':userData.last_step,
                            'dl_front':userData.dl_front,
                            'dl_back':userData.dl_back,
                        },
                        'status_code': 200
                    })    
                return response
            else:
                response = jsonify({
                    'status':'error', 
                    'message': resp
                })
                response.status_code = 401
                return response

        # handle error
        else:
            response = jsonify({
                'status ': 'error',
                'message': 'Invalid token. Please login again.'
            })
            response.status_code = 403
            return response
Esempio n. 13
0
 def test_decode_auth_token(self):
     user = User(username='******',
                 email='*****@*****.**',
                 password="******")
     db.session.add(user)
     db.session.commit()
     token = user.encode_auth_token()
     user_obj = User.decode_auth_token(token)
     self.assertTrue(user_obj.id == user.id)
Esempio n. 14
0
 def get(self):
     auth_header = request.headers.get("Authorization")
     if not auth_header:
         return {"message": "Provide a valid auth token."}, 403
     auth_token = auth_header.split(" ")[1]
     resp = User.decode_auth_token(auth_token)
     if isinstance(resp, str):
         return {"message": resp}, 401
     return {"message": "Successfully signed out."}, 200
Esempio n. 15
0
 def test_decode_auth_expired_token(self):
     user = User(username='******',
                 email='*****@*****.**',
                 password="******")
     db.session.add(user)
     db.session.commit()
     token = user.encode_auth_token()
     time.sleep(6)
     message = User.decode_auth_token(token)
     self.assertEqual(message, 'Signature expired. Please log in again.')
Esempio n. 16
0
    def test_req_marked_done_by_teacher(self):
        """ensure correct response if req is marked done by a teacher"""

        school = add_school(name='testschool')
        teacher = add_user('ollie mansell', '*****@*****.**', 'olliepass',
                           TEACHER, 'MAO', school.id)
        add_user('gary tyler', '*****@*****.**', 'garypass', TECHNICIAN, 'TGA',
                 school.id)

        now = datetime.now()
        req = add_req("title", "equipment", "notes", now, teacher.id,
                      school.id)
        req.isDone = False

        with self.client:
            resp_login = self.client.post('/auth/login',
                                          data=json.dumps({
                                              'email':
                                              '*****@*****.**',
                                              'password':
                                              '******'
                                          }),
                                          content_type='application/json')
            token = json.loads(resp_login.data.decode())['user']['token']

            User.decode_auth_token(token)

            response = self.client.patch(
                '/reqs/' + str(req.id),
                content_type='application/json',
                data=json.dumps([{
                    "op": "replace",
                    "path": "/isDone",
                    "value": True
                }]),
                headers={'Authorization': f'Bearer {token}'})

            data = json.loads(response.data.decode())
            self.assertEqual(response.status_code, 401)
            self.assertIn('You are not authorised to do that.',
                          data['message'])
            self.assertIn('fail', data['status'])
Esempio n. 17
0
 def decorated_function(*args, **kwargs):
     auth_header = request.headers.get("Authorization")
     if not auth_header:
         return f(None, *args, **kwargs)
     auth_token = auth_header.split(" ")[1]
     valid_token, value = User.decode_auth_token(auth_token)
     if not valid_token:
         return f(None, *args, **kwargs)
     user = User.query.filter_by(user_id=value).first()
     if user is None:
         return f(None, *args, **kwargs)
     return f(value, *args, **kwargs)
Esempio n. 18
0
def auth_logout():
    auth_header = request.headers.get('Authorization')
    INVALID_MESSAGE = {'status': 'fail', 'message': 'Token missing'}
    resp = ""
    try:
        token = auth_header.split(' ')
        resp = User.decode_auth_token(token[1])
        print(resp)
        if not isinstance(resp, str):
            return jsonify({'status': 'success', 'message': 'logged out'}), 200
    except Exception as e:
        resp = str(e)
        print(resp)
    return jsonify({'status': 'fail', 'message': resp}), 401
Esempio n. 19
0
 def decorated_function(*args, **kwargs):
     response_object = {"status": "fail", "message": "Provide a valid auth token."}
     auth_header = request.headers.get("Authorization")
     if not auth_header:
         return jsonify(response_object), 403
     auth_token = auth_header.split(" ")[1]
     resp = User.decode_auth_token(auth_token)
     if isinstance(resp, str):
         response_object["message"] = resp
         return jsonify(response_object), 401
     user = User.query.filter_by(id=resp).first()
     if not user or not user.active:
         return jsonify(response_object), 401
     return f(resp, *args, **kwargs)
Esempio n. 20
0
 def decorated_function(*args, **kwargs):
     response = {'status': 'fail', 'message': 'Provide a valid auth token'}
     auth_header = request.headers.get('Authorization')
     if not auth_header:
         return jsonify(response), 403
     auth_token = auth_header.split(' ')[1]
     resp = User.decode_auth_token(auth_token)
     if isinstance(resp, str):
         response['message'] = resp
         return jsonify(response), 401
     user = User.query.filter_by(id=resp).first()
     if not user or not user.active:
         return jsonify(response), 401
     return f(resp, *args, **kwargs)
Esempio n. 21
0
 def decorated_function(*args, **kwargs):
     response = {"message": "Provide a valid auth token."}
     auth_header = request.headers.get("Authorization")
     if not auth_header:
         return jsonify(response), 403
     auth_token = auth_header.split(" ")[1]
     valid_token, value = User.decode_auth_token(auth_token)
     if not valid_token:
         response["message"] = value
         return jsonify(response), 401
     user = User.query.filter_by(user_id=value).first()
     if user is None:
         return jsonify(response), 401
     return f(value, *args, **kwargs)
Esempio n. 22
0
def logout_user():
    auth_header = request.headers.get('Authorization')
    response_object = {'status': 'fail', 'message': 'Provide a valid token.'}
    if auth_header:
        auth_token = auth_header.split(' ')[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            response_object['status'] = 'success'
            response_object['message'] = 'Successfully logged out.'
            return jsonify(response_object), 200
        else:
            response_object['message'] = resp
            return jsonify(response_object), 401
    else:
        return jsonify(response_object), 403
Esempio n. 23
0
def logout_user():
    auth_header = request.headers.get("Authorization")
    response_object = {"status": "fail", "message": "Provide a valid auth token."}
    if auth_header:
        auth_token = auth_header.split(" ")[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            response_object["status"] = "success"
            response_object["message"] = "Successfully logged out."
            return jsonify(response_object), 200
        else:
            response_object["message"] = resp
            return jsonify(response_object), 401
    else:
        return jsonify(response_object), 403
Esempio n. 24
0
def get_user_status():
    auth_header = request.headers.get("Authorization")
    response_object = {"status": "fail", "message": "Provide a valid auth token."}
    if auth_header:
        auth_token = auth_header.split(" ")[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(id=resp).first()
            response_object["status"] = "success"
            response_object["message"] = "Success."
            response_object['data'] = user.to_json()
            return jsonify(response_object), 200
        response_object['message'] = resp
        return jsonify(response_object), 401
    else:
        return jsonify(response_object), 401
Esempio n. 25
0
def get_user_status():
    authorization = request.headers.get('Authorization')
    response = {'status': 'fail', 'message': 'Provide a valid auth token.'}
    if authorization:
        auth_token = authorization.split(' ')[1]
        token_res = User.decode_auth_token(auth_token)
        if not isinstance(token_res, str):
            user = User.query.filter_by(id=token_res).first()
            response['status'] = 'success'
            response['message'] = 'Success'
            response['data'] = user.to_json()
            return jsonify(response), 200
        response['message'] = token_res
        return jsonify(response), 401
    else:
        return jsonify(response), 401
Esempio n. 26
0
def auth_status():
    auth_header = request.headers.get('Authorization')
    resp = ""
    try:
        token = auth_header.split(' ')[1]
        response = User.decode_auth_token(token)
        if (isinstance(response, User)):
            data = {'status': 'success', 'data': response.to_json()}
            status_code = 200
        else:
            data = {'status': 'fail', 'message': response}
            status_code = 401
        return jsonify(data), status_code
    except Exception as e:
        resp = str(e)
    return jsonify({'status': 'fail', 'message': resp}), 401